diff --git a/Makefile b/Makefile index 4d73dfd1c..3cf09644c 100644 --- a/Makefile +++ b/Makefile @@ -338,7 +338,7 @@ mock: ##@other Regenerate mocks mockgen -package=status -destination=services/status/account_mock.go -source=services/status/service.go mockgen -package=peer -destination=services/peer/discoverer_mock.go -source=services/peer/service.go mockgen -package=mock_transactor -destination=transactions/mock_transactor/transactor.go -source=transactions/transactor.go - mockgen -package=mock_bridge -destination=services/wallet/bridge/mock_bridge/bridge.go -source=services/wallet/bridge/bridge.go + mockgen -package=mock_pathprocessor -destination=services/wallet/router/pathprocessor/mock_pathprocessor/processor.go -source=services/wallet/router/pathprocessor/processor.go docker-test: ##@tests Run tests in a docker container with golang. docker run --privileged --rm -it -v "$(PWD):$(DOCKER_TEST_WORKDIR)" -w "$(DOCKER_TEST_WORKDIR)" $(DOCKER_TEST_IMAGE) go test ${ARGS} diff --git a/services/ens/api.go b/services/ens/api.go index 8beca2b0f..dcd64b06e 100644 --- a/services/ens/api.go +++ b/services/ens/api.go @@ -124,7 +124,7 @@ func (api *API) GetRegistrarAddress(ctx context.Context, chainID uint64) (common } func (api *API) Resolver(ctx context.Context, chainID uint64, username string) (*common.Address, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return nil, err } @@ -135,7 +135,7 @@ func (api *API) Resolver(ctx context.Context, chainID uint64, username string) ( } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - resolver, err := registry.Resolver(callOpts, nameHash(username)) + resolver, err := registry.Resolver(callOpts, NameHash(username)) if err != nil { return nil, err } @@ -152,7 +152,7 @@ func (api *API) GetName(ctx context.Context, chainID uint64, address common.Addr } func (api *API) OwnerOf(ctx context.Context, chainID uint64, username string) (*common.Address, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return nil, err } @@ -163,7 +163,7 @@ func (api *API) OwnerOf(ctx context.Context, chainID uint64, username string) (* } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - owner, err := registry.Owner(callOpts, nameHash(username)) + owner, err := registry.Owner(callOpts, NameHash(username)) if err != nil { return nil, err } @@ -172,7 +172,7 @@ func (api *API) OwnerOf(ctx context.Context, chainID uint64, username string) (* } func (api *API) ContentHash(ctx context.Context, chainID uint64, username string) ([]byte, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return nil, err } @@ -188,7 +188,7 @@ func (api *API) ContentHash(ctx context.Context, chainID uint64, username string } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - contentHash, err := resolver.Contenthash(callOpts, nameHash(username)) + contentHash, err := resolver.Contenthash(callOpts, NameHash(username)) if err != nil { return nil, nil } @@ -197,7 +197,7 @@ func (api *API) ContentHash(ctx context.Context, chainID uint64, username string } func (api *API) PublicKeyOf(ctx context.Context, chainID uint64, username string) (string, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return "", err } @@ -213,7 +213,7 @@ func (api *API) PublicKeyOf(ctx context.Context, chainID uint64, username string } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - pubKey, err := resolver.Pubkey(callOpts, nameHash(username)) + pubKey, err := resolver.Pubkey(callOpts, NameHash(username)) if err != nil { return "", err } @@ -221,7 +221,7 @@ func (api *API) PublicKeyOf(ctx context.Context, chainID uint64, username string } func (api *API) AddressOf(ctx context.Context, chainID uint64, username string) (*common.Address, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return nil, err } @@ -237,7 +237,7 @@ func (api *API) AddressOf(ctx context.Context, chainID uint64, username string) } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - addr, err := resolver.Addr(callOpts, nameHash(username)) + addr, err := resolver.Addr(callOpts, NameHash(username)) if err != nil { return nil, err } @@ -308,7 +308,7 @@ func (api *API) ExpireAt(ctx context.Context, chainID uint64, username string) ( } callOpts := &bind.CallOpts{Context: ctx, Pending: false} - expTime, err := registrar.GetExpirationTime(callOpts, usernameToLabel(username)) + expTime, err := registrar.GetExpirationTime(callOpts, UsernameToLabel(username)) if err != nil { return "", err } @@ -348,7 +348,7 @@ func (api *API) Release(ctx context.Context, chainID uint64, txArgs transactions } txOpts := txArgs.ToTransactOpts(utils.GetSigner(chainID, api.accountsManager, api.config.KeyStoreDir, txArgs.From, password)) - tx, err := registrar.Release(txOpts, usernameToLabel(username)) + tx, err := registrar.Release(txOpts, UsernameToLabel(username)) if err != nil { return "", err } @@ -382,7 +382,7 @@ func (api *API) ReleasePrepareTxCallMsg(ctx context.Context, chainID uint64, txA return ethereum.CallMsg{}, err } - data, err := registrarABI.Pack("release", usernameToLabel(username)) + data, err := registrarABI.Pack("release", UsernameToLabel(username)) if err != nil { return ethereum.CallMsg{}, err } @@ -414,7 +414,7 @@ func (api *API) ReleaseEstimate(ctx context.Context, chainID uint64, txArgs tran return 0, err } - data, err := registrarABI.Pack("release", usernameToLabel(username)) + data, err := registrarABI.Pack("release", UsernameToLabel(username)) if err != nil { return 0, err } @@ -459,8 +459,8 @@ func (api *API) Register(ctx context.Context, chainID uint64, txArgs transaction return "", err } - x, y := extractCoordinates(pubkey) - extraData, err := registrarABI.Pack("register", usernameToLabel(username), common.Address(txArgs.From), x, y) + x, y := ExtractCoordinates(pubkey) + extraData, err := registrarABI.Pack("register", UsernameToLabel(username), common.Address(txArgs.From), x, y) if err != nil { return "", err } @@ -517,8 +517,8 @@ func (api *API) RegisterPrepareTxCallMsg(ctx context.Context, chainID uint64, tx return ethereum.CallMsg{}, err } - x, y := extractCoordinates(pubkey) - extraData, err := registrarABI.Pack("register", usernameToLabel(username), common.Address(txArgs.From), x, y) + x, y := ExtractCoordinates(pubkey) + extraData, err := registrarABI.Pack("register", UsernameToLabel(username), common.Address(txArgs.From), x, y) if err != nil { return ethereum.CallMsg{}, err } @@ -578,7 +578,7 @@ func (api *API) RegisterEstimate(ctx context.Context, chainID uint64, txArgs tra } func (api *API) SetPubKey(ctx context.Context, chainID uint64, txArgs transactions.SendTxArgs, password string, username string, pubkey string) (string, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return "", err } @@ -593,9 +593,9 @@ func (api *API) SetPubKey(ctx context.Context, chainID uint64, txArgs transactio return "", err } - x, y := extractCoordinates(pubkey) + x, y := ExtractCoordinates(pubkey) txOpts := txArgs.ToTransactOpts(utils.GetSigner(chainID, api.accountsManager, api.config.KeyStoreDir, txArgs.From, password)) - tx, err := resolver.SetPubkey(txOpts, nameHash(username), x, y) + tx, err := resolver.SetPubkey(txOpts, NameHash(username), x, y) if err != nil { return "", err } @@ -624,18 +624,18 @@ func (api *API) SetPubKey(ctx context.Context, chainID uint64, txArgs transactio } func (api *API) SetPubKeyPrepareTxCallMsg(ctx context.Context, chainID uint64, txArgs transactions.SendTxArgs, username string, pubkey string) (ethereum.CallMsg, error) { - err := validateENSUsername(username) + err := ValidateENSUsername(username) if err != nil { return ethereum.CallMsg{}, err } - x, y := extractCoordinates(pubkey) + x, y := ExtractCoordinates(pubkey) resolverABI, err := abi.JSON(strings.NewReader(resolver.PublicResolverABI)) if err != nil { return ethereum.CallMsg{}, err } - data, err := resolverABI.Pack("setPubkey", nameHash(username), x, y) + data, err := resolverABI.Pack("setPubkey", NameHash(username), x, y) if err != nil { return ethereum.CallMsg{}, err } diff --git a/services/ens/strings.go b/services/ens/strings.go index 272bf8a5b..2e0e33753 100644 --- a/services/ens/strings.go +++ b/services/ens/strings.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -func nameHash(name string) common.Hash { +func NameHash(name string) common.Hash { node := common.Hash{} if len(name) > 0 { @@ -24,7 +24,7 @@ func nameHash(name string) common.Hash { return node } -func validateENSUsername(username string) error { +func ValidateENSUsername(username string) error { if !strings.HasSuffix(username, ".eth") { return fmt.Errorf("username must end with .eth") } @@ -32,7 +32,7 @@ func validateENSUsername(username string) error { return nil } -func usernameToLabel(username string) [32]byte { +func UsernameToLabel(username string) [32]byte { usernameHashed := crypto.Keccak256([]byte(username)) var label [32]byte copy(label[:], usernameHashed) @@ -40,7 +40,7 @@ func usernameToLabel(username string) [32]byte { return label } -func extractCoordinates(pubkey string) ([32]byte, [32]byte) { +func ExtractCoordinates(pubkey string) ([32]byte, [32]byte) { x, _ := hex.DecodeString(pubkey[4:68]) y, _ := hex.DecodeString(pubkey[68:132]) diff --git a/services/wallet/api.go b/services/wallet/api.go index d445e0d52..0530a02f6 100644 --- a/services/wallet/api.go +++ b/services/wallet/api.go @@ -25,7 +25,7 @@ import ( "github.com/status-im/status-go/services/wallet/history" "github.com/status-im/status-go/services/wallet/onramp" "github.com/status-im/status-go/services/wallet/router" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/status-im/status-go/services/wallet/thirdparty" "github.com/status-im/status-go/services/wallet/token" "github.com/status-im/status-go/services/wallet/transfer" @@ -576,7 +576,7 @@ func (api *API) SendTransactionWithSignature(ctx context.Context, chainID uint64 return api.s.transactionManager.SendTransactionWithSignature(chainID, params, sig) } -func (api *API) CreateMultiTransaction(ctx context.Context, multiTransactionCommand *transfer.MultiTransactionCommand, data []*bridge.TransactionBridge, password string) (*transfer.MultiTransactionCommandResult, error) { +func (api *API) CreateMultiTransaction(ctx context.Context, multiTransactionCommand *transfer.MultiTransactionCommand, data []*pathprocessor.MultipathProcessorTxArgs, password string) (*transfer.MultiTransactionCommandResult, error) { log.Debug("[WalletAPI:: CreateMultiTransaction] create multi transaction") cmd, err := api.s.transactionManager.CreateMultiTransactionFromCommand(multiTransactionCommand, data) @@ -590,7 +590,7 @@ func (api *API) CreateMultiTransaction(ctx context.Context, multiTransactionComm return nil, err } - cmdRes, err := api.s.transactionManager.SendTransactions(ctx, cmd, data, api.router.GetBridges(), selectedAccount) + cmdRes, err := api.s.transactionManager.SendTransactions(ctx, cmd, data, api.router.GetPathProcessors(), selectedAccount) if err != nil { return nil, err } @@ -603,7 +603,7 @@ func (api *API) CreateMultiTransaction(ctx context.Context, multiTransactionComm return cmdRes, nil } - return nil, api.s.transactionManager.SendTransactionForSigningToKeycard(ctx, cmd, data, api.router.GetBridges()) + return nil, api.s.transactionManager.SendTransactionForSigningToKeycard(ctx, cmd, data, api.router.GetPathProcessors()) } func (api *API) ProceedWithTransactionsSignatures(ctx context.Context, signatures map[string]transfer.SignatureDetails) (*transfer.MultiTransactionCommandResult, error) { diff --git a/services/wallet/router/bridge/bridge.go b/services/wallet/router/bridge/bridge.go deleted file mode 100644 index ce65e62a8..000000000 --- a/services/wallet/router/bridge/bridge.go +++ /dev/null @@ -1,200 +0,0 @@ -package bridge - -import ( - "encoding/hex" - "fmt" - "math/big" - "strings" - - ethTypes "github.com/ethereum/go-ethereum/core/types" - - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/status-im/status-go/account" - "github.com/status-im/status-go/eth-node/types" - "github.com/status-im/status-go/params" - "github.com/status-im/status-go/services/wallet/token" - "github.com/status-im/status-go/transactions" -) - -var ( - ZeroAddress = common.Address{} - ZeroBigIntValue = big.NewInt(0) -) - -const ( - IncreaseEstimatedGasFactor = 1.1 - - EthSymbol = "ETH" - SntSymbol = "SNT" - SttSymbol = "STT" - - TransferName = "Transfer" - HopName = "Hop" - CBridgeName = "CBridge" - SwapParaswapName = "Paraswap" - ERC721TransferName = "ERC721Transfer" - ERC1155TransferName = "ERC1155Transfer" - ENSRegisterName = "ENSRegister" - ENSReleaseName = "ENSRelease" - ENSPublicKeyName = "ENSPublicKey" -) - -func getSigner(chainID uint64, from types.Address, verifiedAccount *account.SelectedExtKey) bind.SignerFn { - return func(addr common.Address, tx *ethTypes.Transaction) (*ethTypes.Transaction, error) { - s := ethTypes.NewLondonSigner(new(big.Int).SetUint64(chainID)) - return ethTypes.SignTx(tx, s, verifiedAccount.AccountKey.PrivateKey) - } -} - -type TransactionBridge struct { - BridgeName string - ChainID uint64 - TransferTx *transactions.SendTxArgs - HopTx *HopTxArgs - CbridgeTx *CBridgeTxArgs - ERC721TransferTx *ERC721TransferTxArgs - ERC1155TransferTx *ERC1155TransferTxArgs - SwapTx *SwapTxArgs -} - -func (t *TransactionBridge) Value() *big.Int { - if t.TransferTx != nil && t.TransferTx.To != nil { - return t.TransferTx.Value.ToInt() - } else if t.HopTx != nil { - return t.HopTx.Amount.ToInt() - } else if t.CbridgeTx != nil { - return t.CbridgeTx.Amount.ToInt() - } else if t.ERC721TransferTx != nil { - return big.NewInt(1) - } else if t.ERC1155TransferTx != nil { - return t.ERC1155TransferTx.Amount.ToInt() - } - - return big.NewInt(0) -} - -func (t *TransactionBridge) From() types.Address { - if t.TransferTx != nil && t.TransferTx.To != nil { - return t.TransferTx.From - } else if t.HopTx != nil { - return t.HopTx.From - } else if t.CbridgeTx != nil { - return t.CbridgeTx.From - } else if t.ERC721TransferTx != nil { - return t.ERC721TransferTx.From - } else if t.ERC1155TransferTx != nil { - return t.ERC1155TransferTx.From - } - - return types.HexToAddress("0x0") -} - -func (t *TransactionBridge) To() types.Address { - if t.TransferTx != nil && t.TransferTx.To != nil { - return *t.TransferTx.To - } else if t.HopTx != nil { - return types.Address(t.HopTx.Recipient) - } else if t.CbridgeTx != nil { - return types.Address(t.HopTx.Recipient) - } else if t.ERC721TransferTx != nil { - return types.Address(t.ERC721TransferTx.Recipient) - } else if t.ERC1155TransferTx != nil { - return types.Address(t.ERC1155TransferTx.Recipient) - } - - return types.HexToAddress("0x0") -} - -func (t *TransactionBridge) Data() types.HexBytes { - if t.TransferTx != nil && t.TransferTx.To != nil { - return t.TransferTx.Data - } else if t.HopTx != nil { - return types.HexBytes("") - } else if t.CbridgeTx != nil { - return types.HexBytes("") - } else if t.ERC721TransferTx != nil { - return types.HexBytes("") - } else if t.ERC1155TransferTx != nil { - return types.HexBytes("") - } - - return types.HexBytes("") -} - -type BridgeParams struct { - FromChain *params.Network - ToChain *params.Network - FromAddr common.Address - ToAddr common.Address - FromToken *token.Token - ToToken *token.Token - AmountIn *big.Int - - // extra params - BonderFee *big.Int - Username string - PublicKey string -} - -type Bridge interface { - // returns the name of the bridge - Name() string - // checks if the bridge is available for the given networks/tokens - AvailableFor(params BridgeParams) (bool, error) - // calculates the fees for the bridge and returns the amount BonderFee and TokenFee (used for bridges) - CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) - // Pack the method for sending tx and method call's data - PackTxInputData(params BridgeParams, contractType string) ([]byte, error) - EstimateGas(params BridgeParams) (uint64, error) - CalculateAmountOut(params BridgeParams) (*big.Int, error) - Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (types.Hash, error) - GetContractAddress(params BridgeParams) (common.Address, error) - BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) - BuildTx(params BridgeParams) (*ethTypes.Transaction, error) -} - -func ValidateENSUsername(username string) error { - if !strings.HasSuffix(username, ".eth") { - return fmt.Errorf("username must end with .eth") - } - - return nil -} - -func extractCoordinates(pubkey string) ([32]byte, [32]byte) { - x, _ := hex.DecodeString(pubkey[4:68]) - y, _ := hex.DecodeString(pubkey[68:132]) - - var xByte [32]byte - copy(xByte[:], x) - - var yByte [32]byte - copy(yByte[:], y) - - return xByte, yByte -} - -func usernameToLabel(username string) [32]byte { - usernameHashed := crypto.Keccak256([]byte(username)) - var label [32]byte - copy(label[:], usernameHashed) - - return label -} - -func nameHash(name string) common.Hash { - node := common.Hash{} - - if len(name) > 0 { - labels := strings.Split(name, ".") - - for i := len(labels) - 1; i >= 0; i-- { - labelSha := crypto.Keccak256Hash([]byte(labels[i])) - node = crypto.Keccak256Hash(node.Bytes(), labelSha.Bytes()) - } - } - - return node -} diff --git a/services/wallet/router/bridge/mock_bridge/README.md b/services/wallet/router/bridge/mock_bridge/README.md deleted file mode 100644 index a80b77ac6..000000000 --- a/services/wallet/router/bridge/mock_bridge/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# To generate mocks, from status-go root directory: -mockgen -source=services/wallet/bridge/bridge.go -destination=services/wallet/bridge/mock_bridge/bridge.go -package=mock_bridge diff --git a/services/wallet/router/filter.go b/services/wallet/router/filter.go index 8affb6b7c..c99b3976f 100644 --- a/services/wallet/router/filter.go +++ b/services/wallet/router/filter.go @@ -4,7 +4,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "go.uber.org/zap" ) @@ -89,7 +89,7 @@ func setupRouteValidationMapsV2(fromLockedAmount map[uint64]*hexutil.Big) (map[u fromExcluded := make(map[uint64]bool) for chainID, amount := range fromLockedAmount { - if amount.ToInt().Cmp(bridge.ZeroBigIntValue) <= 0 { + if amount.ToInt().Cmp(pathprocessor.ZeroBigIntValue) <= 0 { fromExcluded[chainID] = false } else { fromIncluded[chainID] = false diff --git a/services/wallet/router/filter_test.go b/services/wallet/router/filter_test.go index 554d02e79..407af5074 100644 --- a/services/wallet/router/filter_test.go +++ b/services/wallet/router/filter_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" "github.com/status-im/status-go/params" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/stretchr/testify/assert" ) @@ -84,9 +84,9 @@ func TestSetupRouteValidationMapsV2(t *testing.T) { { name: "Mixed zero and non-zero amounts", fromLockedAmount: map[uint64]*hexutil.Big{ - 1: (*hexutil.Big)(bridge.ZeroBigIntValue), + 1: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), 2: (*hexutil.Big)(big.NewInt(200)), - 3: (*hexutil.Big)(bridge.ZeroBigIntValue), + 3: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), 4: (*hexutil.Big)(big.NewInt(400)), }, expectedIncluded: map[uint64]bool{ @@ -113,8 +113,8 @@ func TestSetupRouteValidationMapsV2(t *testing.T) { { name: "All zero amounts", fromLockedAmount: map[uint64]*hexutil.Big{ - 1: (*hexutil.Big)(bridge.ZeroBigIntValue), - 2: (*hexutil.Big)(bridge.ZeroBigIntValue), + 1: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), + 2: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), }, expectedIncluded: map[uint64]bool{}, expectedExcluded: map[uint64]bool{ @@ -135,7 +135,7 @@ func TestSetupRouteValidationMapsV2(t *testing.T) { { name: "Single zero amount", fromLockedAmount: map[uint64]*hexutil.Big{ - 1: (*hexutil.Big)(bridge.ZeroBigIntValue), + 1: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), }, expectedIncluded: map[uint64]bool{}, expectedExcluded: map[uint64]bool{ diff --git a/services/wallet/router/bridge/cbridge/cbridge.pb.go b/services/wallet/router/pathprocessor/cbridge/cbridge.pb.go similarity index 100% rename from services/wallet/router/bridge/cbridge/cbridge.pb.go rename to services/wallet/router/pathprocessor/cbridge/cbridge.pb.go diff --git a/services/wallet/router/bridge/cbridge/gateway.pb.go b/services/wallet/router/pathprocessor/cbridge/gateway.pb.go similarity index 100% rename from services/wallet/router/bridge/cbridge/gateway.pb.go rename to services/wallet/router/pathprocessor/cbridge/gateway.pb.go diff --git a/services/wallet/router/bridge/cbridge/query.pb.go b/services/wallet/router/pathprocessor/cbridge/query.pb.go similarity index 100% rename from services/wallet/router/bridge/cbridge/query.pb.go rename to services/wallet/router/pathprocessor/cbridge/query.pb.go diff --git a/services/wallet/router/pathprocessor/common.go b/services/wallet/router/pathprocessor/common.go new file mode 100644 index 000000000..14d6c3645 --- /dev/null +++ b/services/wallet/router/pathprocessor/common.go @@ -0,0 +1,19 @@ +package pathprocessor + +import ( + "math/big" + + ethTypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/status-im/status-go/account" + "github.com/status-im/status-go/eth-node/types" +) + +func getSigner(chainID uint64, from types.Address, verifiedAccount *account.SelectedExtKey) bind.SignerFn { + return func(addr common.Address, tx *ethTypes.Transaction) (*ethTypes.Transaction, error) { + s := ethTypes.NewLondonSigner(new(big.Int).SetUint64(chainID)) + return ethTypes.SignTx(tx, s, verifiedAccount.AccountKey.PrivateKey) + } +} diff --git a/services/wallet/router/pathprocessor/constants.go b/services/wallet/router/pathprocessor/constants.go new file mode 100644 index 000000000..d04def0a5 --- /dev/null +++ b/services/wallet/router/pathprocessor/constants.go @@ -0,0 +1,30 @@ +package pathprocessor + +import ( + "math/big" + + "github.com/ethereum/go-ethereum/common" +) + +var ( + ZeroAddress = common.Address{} + ZeroBigIntValue = big.NewInt(0) +) + +const ( + IncreaseEstimatedGasFactor = 1.1 + + EthSymbol = "ETH" + SntSymbol = "SNT" + SttSymbol = "STT" + + ProcessorTransferName = "Transfer" + ProcessorBridgeHopName = "Hop" + ProcessorBridgeCelerName = "CBridge" + ProcessorSwapParaswapName = "Paraswap" + ProcessorERC721Name = "ERC721Transfer" + ProcessorERC1155Name = "ERC1155Transfer" + ProcessorENSRegisterName = "ENSRegister" + ProcessorENSReleaseName = "ENSRelease" + ProcessorENSPublicKeyName = "ENSPublicKey" +) diff --git a/services/wallet/router/bridge/mock_bridge/bridge.go b/services/wallet/router/pathprocessor/mock_pathprocessor/processor.go similarity index 52% rename from services/wallet/router/bridge/mock_bridge/bridge.go rename to services/wallet/router/pathprocessor/mock_pathprocessor/processor.go index 5cb427e84..cfb01ef86 100644 --- a/services/wallet/router/bridge/mock_bridge/bridge.go +++ b/services/wallet/router/pathprocessor/mock_pathprocessor/processor.go @@ -1,47 +1,46 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: services/wallet/bridge/bridge.go +// Source: services/wallet/router/pathprocessor/processor.go -// Package mock_bridge is a generated GoMock package. -package mock_bridge +// Package mock_pathprocessor is a generated GoMock package. +package mock_pathprocessor import ( big "math/big" reflect "reflect" - gomock "github.com/golang/mock/gomock" - common "github.com/ethereum/go-ethereum/common" types "github.com/ethereum/go-ethereum/core/types" + gomock "github.com/golang/mock/gomock" account "github.com/status-im/status-go/account" types0 "github.com/status-im/status-go/eth-node/types" - bridge "github.com/status-im/status-go/services/wallet/router/bridge" + pathprocessor "github.com/status-im/status-go/services/wallet/router/pathprocessor" ) -// MockBridge is a mock of Bridge interface. -type MockBridge struct { +// MockPathProcessor is a mock of PathProcessor interface. +type MockPathProcessor struct { ctrl *gomock.Controller - recorder *MockBridgeMockRecorder + recorder *MockPathProcessorMockRecorder } -// MockBridgeMockRecorder is the mock recorder for MockBridge. -type MockBridgeMockRecorder struct { - mock *MockBridge +// MockPathProcessorMockRecorder is the mock recorder for MockPathProcessor. +type MockPathProcessorMockRecorder struct { + mock *MockPathProcessor } -// NewMockBridge creates a new mock instance. -func NewMockBridge(ctrl *gomock.Controller) *MockBridge { - mock := &MockBridge{ctrl: ctrl} - mock.recorder = &MockBridgeMockRecorder{mock} +// NewMockPathProcessor creates a new mock instance. +func NewMockPathProcessor(ctrl *gomock.Controller) *MockPathProcessor { + mock := &MockPathProcessor{ctrl: ctrl} + mock.recorder = &MockPathProcessorMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBridge) EXPECT() *MockBridgeMockRecorder { +func (m *MockPathProcessor) EXPECT() *MockPathProcessorMockRecorder { return m.recorder } // AvailableFor mocks base method. -func (m *MockBridge) AvailableFor(params bridge.BridgeParams) (bool, error) { +func (m *MockPathProcessor) AvailableFor(params pathprocessor.ProcessorInputParams) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AvailableFor", params) ret0, _ := ret[0].(bool) @@ -50,13 +49,13 @@ func (m *MockBridge) AvailableFor(params bridge.BridgeParams) (bool, error) { } // AvailableFor indicates an expected call of AvailableFor. -func (mr *MockBridgeMockRecorder) AvailableFor(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) AvailableFor(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AvailableFor", reflect.TypeOf((*MockBridge)(nil).AvailableFor), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AvailableFor", reflect.TypeOf((*MockPathProcessor)(nil).AvailableFor), params) } // BuildTransaction mocks base method. -func (m *MockBridge) BuildTransaction(sendArgs *bridge.TransactionBridge) (*types.Transaction, error) { +func (m *MockPathProcessor) BuildTransaction(sendArgs *pathprocessor.MultipathProcessorTxArgs) (*types.Transaction, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildTransaction", sendArgs) ret0, _ := ret[0].(*types.Transaction) @@ -65,13 +64,13 @@ func (m *MockBridge) BuildTransaction(sendArgs *bridge.TransactionBridge) (*type } // BuildTransaction indicates an expected call of BuildTransaction. -func (mr *MockBridgeMockRecorder) BuildTransaction(sendArgs interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) BuildTransaction(sendArgs interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildTransaction", reflect.TypeOf((*MockBridge)(nil).BuildTransaction), sendArgs) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildTransaction", reflect.TypeOf((*MockPathProcessor)(nil).BuildTransaction), sendArgs) } // BuildTx mocks base method. -func (m *MockBridge) BuildTx(params bridge.BridgeParams) (*types.Transaction, error) { +func (m *MockPathProcessor) BuildTx(params pathprocessor.ProcessorInputParams) (*types.Transaction, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildTx", params) ret0, _ := ret[0].(*types.Transaction) @@ -80,13 +79,13 @@ func (m *MockBridge) BuildTx(params bridge.BridgeParams) (*types.Transaction, er } // BuildTx indicates an expected call of BuildTx. -func (mr *MockBridgeMockRecorder) BuildTx(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) BuildTx(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildTx", reflect.TypeOf((*MockBridge)(nil).BuildTx), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildTx", reflect.TypeOf((*MockPathProcessor)(nil).BuildTx), params) } // CalculateAmountOut mocks base method. -func (m *MockBridge) CalculateAmountOut(params bridge.BridgeParams) (*big.Int, error) { +func (m *MockPathProcessor) CalculateAmountOut(params pathprocessor.ProcessorInputParams) (*big.Int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CalculateAmountOut", params) ret0, _ := ret[0].(*big.Int) @@ -95,13 +94,13 @@ func (m *MockBridge) CalculateAmountOut(params bridge.BridgeParams) (*big.Int, e } // CalculateAmountOut indicates an expected call of CalculateAmountOut. -func (mr *MockBridgeMockRecorder) CalculateAmountOut(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) CalculateAmountOut(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateAmountOut", reflect.TypeOf((*MockBridge)(nil).CalculateAmountOut), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateAmountOut", reflect.TypeOf((*MockPathProcessor)(nil).CalculateAmountOut), params) } // CalculateFees mocks base method. -func (m *MockBridge) CalculateFees(params bridge.BridgeParams) (*big.Int, *big.Int, error) { +func (m *MockPathProcessor) CalculateFees(params pathprocessor.ProcessorInputParams) (*big.Int, *big.Int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CalculateFees", params) ret0, _ := ret[0].(*big.Int) @@ -111,13 +110,13 @@ func (m *MockBridge) CalculateFees(params bridge.BridgeParams) (*big.Int, *big.I } // CalculateFees indicates an expected call of CalculateFees. -func (mr *MockBridgeMockRecorder) CalculateFees(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) CalculateFees(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateFees", reflect.TypeOf((*MockBridge)(nil).CalculateFees), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateFees", reflect.TypeOf((*MockPathProcessor)(nil).CalculateFees), params) } // EstimateGas mocks base method. -func (m *MockBridge) EstimateGas(params bridge.BridgeParams) (uint64, error) { +func (m *MockPathProcessor) EstimateGas(params pathprocessor.ProcessorInputParams) (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EstimateGas", params) ret0, _ := ret[0].(uint64) @@ -126,13 +125,13 @@ func (m *MockBridge) EstimateGas(params bridge.BridgeParams) (uint64, error) { } // EstimateGas indicates an expected call of EstimateGas. -func (mr *MockBridgeMockRecorder) EstimateGas(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) EstimateGas(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateGas", reflect.TypeOf((*MockBridge)(nil).EstimateGas), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateGas", reflect.TypeOf((*MockPathProcessor)(nil).EstimateGas), params) } // GetContractAddress mocks base method. -func (m *MockBridge) GetContractAddress(params bridge.BridgeParams) (common.Address, error) { +func (m *MockPathProcessor) GetContractAddress(params pathprocessor.ProcessorInputParams) (common.Address, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetContractAddress", params) ret0, _ := ret[0].(common.Address) @@ -141,13 +140,13 @@ func (m *MockBridge) GetContractAddress(params bridge.BridgeParams) (common.Addr } // GetContractAddress indicates an expected call of GetContractAddress. -func (mr *MockBridgeMockRecorder) GetContractAddress(params interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) GetContractAddress(params interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetContractAddress", reflect.TypeOf((*MockBridge)(nil).GetContractAddress), params) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetContractAddress", reflect.TypeOf((*MockPathProcessor)(nil).GetContractAddress), params) } // Name mocks base method. -func (m *MockBridge) Name() string { +func (m *MockPathProcessor) Name() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Name") ret0, _ := ret[0].(string) @@ -155,13 +154,13 @@ func (m *MockBridge) Name() string { } // Name indicates an expected call of Name. -func (mr *MockBridgeMockRecorder) Name() *gomock.Call { +func (mr *MockPathProcessorMockRecorder) Name() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockBridge)(nil).Name)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockPathProcessor)(nil).Name)) } // PackTxInputData mocks base method. -func (m *MockBridge) PackTxInputData(params bridge.BridgeParams, contractType string) ([]byte, error) { +func (m *MockPathProcessor) PackTxInputData(params pathprocessor.ProcessorInputParams, contractType string) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PackTxInputData", params, contractType) ret0, _ := ret[0].([]byte) @@ -170,13 +169,13 @@ func (m *MockBridge) PackTxInputData(params bridge.BridgeParams, contractType st } // PackTxInputData indicates an expected call of PackTxInputData. -func (mr *MockBridgeMockRecorder) PackTxInputData(params, contractType interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) PackTxInputData(params, contractType interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PackTxInputData", reflect.TypeOf((*MockBridge)(nil).PackTxInputData), params, contractType) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PackTxInputData", reflect.TypeOf((*MockPathProcessor)(nil).PackTxInputData), params, contractType) } // Send mocks base method. -func (m *MockBridge) Send(sendArgs *bridge.TransactionBridge, verifiedAccount *account.SelectedExtKey) (types0.Hash, error) { +func (m *MockPathProcessor) Send(sendArgs *pathprocessor.MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (types0.Hash, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Send", sendArgs, verifiedAccount) ret0, _ := ret[0].(types0.Hash) @@ -185,7 +184,7 @@ func (m *MockBridge) Send(sendArgs *bridge.TransactionBridge, verifiedAccount *a } // Send indicates an expected call of Send. -func (mr *MockBridgeMockRecorder) Send(sendArgs, verifiedAccount interface{}) *gomock.Call { +func (mr *MockPathProcessorMockRecorder) Send(sendArgs, verifiedAccount interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockBridge)(nil).Send), sendArgs, verifiedAccount) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockPathProcessor)(nil).Send), sendArgs, verifiedAccount) } diff --git a/services/wallet/router/pathprocessor/multipath_processor.go b/services/wallet/router/pathprocessor/multipath_processor.go new file mode 100644 index 000000000..35a5c13a4 --- /dev/null +++ b/services/wallet/router/pathprocessor/multipath_processor.go @@ -0,0 +1,83 @@ +package pathprocessor + +import ( + "math/big" + + "github.com/status-im/status-go/eth-node/types" + "github.com/status-im/status-go/transactions" +) + +type MultipathProcessorTxArgs struct { + Name string + ChainID uint64 + TransferTx *transactions.SendTxArgs + HopTx *HopBridgeTxArgs + CbridgeTx *CelerBridgeTxArgs + ERC721TransferTx *ERC721TxArgs + ERC1155TransferTx *ERC1155TxArgs + SwapTx *SwapParaswapTxArgs +} + +func (t *MultipathProcessorTxArgs) Value() *big.Int { + if t.TransferTx != nil && t.TransferTx.To != nil { + return t.TransferTx.Value.ToInt() + } else if t.HopTx != nil { + return t.HopTx.Amount.ToInt() + } else if t.CbridgeTx != nil { + return t.CbridgeTx.Amount.ToInt() + } else if t.ERC721TransferTx != nil { + return big.NewInt(1) + } else if t.ERC1155TransferTx != nil { + return t.ERC1155TransferTx.Amount.ToInt() + } + + return ZeroBigIntValue +} + +func (t *MultipathProcessorTxArgs) From() types.Address { + if t.TransferTx != nil && t.TransferTx.To != nil { + return t.TransferTx.From + } else if t.HopTx != nil { + return t.HopTx.From + } else if t.CbridgeTx != nil { + return t.CbridgeTx.From + } else if t.ERC721TransferTx != nil { + return t.ERC721TransferTx.From + } else if t.ERC1155TransferTx != nil { + return t.ERC1155TransferTx.From + } + + return types.HexToAddress("0x0") +} + +func (t *MultipathProcessorTxArgs) To() types.Address { + if t.TransferTx != nil && t.TransferTx.To != nil { + return *t.TransferTx.To + } else if t.HopTx != nil { + return types.Address(t.HopTx.Recipient) + } else if t.CbridgeTx != nil { + return types.Address(t.HopTx.Recipient) + } else if t.ERC721TransferTx != nil { + return types.Address(t.ERC721TransferTx.Recipient) + } else if t.ERC1155TransferTx != nil { + return types.Address(t.ERC1155TransferTx.Recipient) + } + + return types.HexToAddress("0x0") +} + +func (t *MultipathProcessorTxArgs) Data() types.HexBytes { + if t.TransferTx != nil && t.TransferTx.To != nil { + return t.TransferTx.Data + } else if t.HopTx != nil { + return types.HexBytes("") + } else if t.CbridgeTx != nil { + return types.HexBytes("") + } else if t.ERC721TransferTx != nil { + return types.HexBytes("") + } else if t.ERC1155TransferTx != nil { + return types.HexBytes("") + } + + return types.HexBytes("") +} diff --git a/services/wallet/router/pathprocessor/processor.go b/services/wallet/router/pathprocessor/processor.go new file mode 100644 index 000000000..b9821f819 --- /dev/null +++ b/services/wallet/router/pathprocessor/processor.go @@ -0,0 +1,45 @@ +package pathprocessor + +import ( + "math/big" + + ethTypes "github.com/ethereum/go-ethereum/core/types" + + "github.com/ethereum/go-ethereum/common" + "github.com/status-im/status-go/account" + "github.com/status-im/status-go/eth-node/types" + "github.com/status-im/status-go/params" + "github.com/status-im/status-go/services/wallet/token" +) + +type PathProcessor interface { + // returns the name of the bridge + Name() string + // checks if the bridge is available for the given networks/tokens + AvailableFor(params ProcessorInputParams) (bool, error) + // calculates the fees for the bridge and returns the amount BonderFee and TokenFee (used for bridges) + CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) + // Pack the method for sending tx and method call's data + PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) + EstimateGas(params ProcessorInputParams) (uint64, error) + CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) + Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (types.Hash, error) + GetContractAddress(params ProcessorInputParams) (common.Address, error) + BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) + BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) +} + +type ProcessorInputParams struct { + FromChain *params.Network + ToChain *params.Network + FromAddr common.Address + ToAddr common.Address + FromToken *token.Token + ToToken *token.Token + AmountIn *big.Int + + // extra params + BonderFee *big.Int + Username string + PublicKey string +} diff --git a/services/wallet/router/bridge/cbridge.go b/services/wallet/router/pathprocessor/processor_bridge_celar.go similarity index 81% rename from services/wallet/router/bridge/cbridge.go rename to services/wallet/router/pathprocessor/processor_bridge_celar.go index a7cd33c04..0f064e3ea 100644 --- a/services/wallet/router/bridge/cbridge.go +++ b/services/wallet/router/pathprocessor/processor_bridge_celar.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -23,7 +23,7 @@ import ( "github.com/status-im/status-go/rpc" "github.com/status-im/status-go/params" - "github.com/status-im/status-go/services/wallet/router/bridge/cbridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor/cbridge" "github.com/status-im/status-go/services/wallet/thirdparty" "github.com/status-im/status-go/services/wallet/token" "github.com/status-im/status-go/transactions" @@ -36,7 +36,7 @@ const ( maxSlippage = uint32(1000) ) -type CBridgeTxArgs struct { +type CelerBridgeTxArgs struct { transactions.SendTxArgs ChainID uint64 `json:"chainId"` Symbol string `json:"symbol"` @@ -44,7 +44,7 @@ type CBridgeTxArgs struct { Amount *hexutil.Big `json:"amount"` } -type CBridge struct { +type CelerBridgeProcessor struct { rpcClient *rpc.Client httpClient *thirdparty.HTTPClient transactor transactions.TransactorIface @@ -53,8 +53,8 @@ type CBridge struct { testTransferConfig *cbridge.GetTransferConfigsResponse } -func NewCbridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *token.Manager) *CBridge { - return &CBridge{ +func NewCelerBridgeProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *token.Manager) *CelerBridgeProcessor { + return &CelerBridgeProcessor{ rpcClient: rpcClient, httpClient: thirdparty.NewHTTPClient(), transactor: transactor, @@ -62,11 +62,11 @@ func NewCbridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, } } -func (s *CBridge) Name() string { - return CBridgeName +func (s *CelerBridgeProcessor) Name() string { + return ProcessorBridgeCelerName } -func (s *CBridge) estimateAmt(from, to *params.Network, amountIn *big.Int, symbol string) (*cbridge.EstimateAmtResponse, error) { +func (s *CelerBridgeProcessor) estimateAmt(from, to *params.Network, amountIn *big.Int, symbol string) (*cbridge.EstimateAmtResponse, error) { base := baseURL if from.IsTest { base = testBaseURL @@ -94,7 +94,7 @@ func (s *CBridge) estimateAmt(from, to *params.Network, amountIn *big.Int, symbo return &res, nil } -func (s *CBridge) getTransferConfig(isTest bool) (*cbridge.GetTransferConfigsResponse, error) { +func (s *CelerBridgeProcessor) getTransferConfig(isTest bool) (*cbridge.GetTransferConfigsResponse, error) { if !isTest && s.prodTransferConfig != nil { return s.prodTransferConfig, nil } @@ -126,7 +126,7 @@ func (s *CBridge) getTransferConfig(isTest bool) (*cbridge.GetTransferConfigsRes return &res, nil } -func (s *CBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *CelerBridgeProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { if params.FromChain.ChainID == params.ToChain.ChainID || params.ToToken != nil { return false, nil } @@ -185,7 +185,7 @@ func (s *CBridge) AvailableFor(params BridgeParams) (bool, error) { return true, nil } -func (s *CBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { +func (s *CelerBridgeProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { amt, err := s.estimateAmt(params.FromChain, params.ToChain, params.AmountIn, params.FromToken.Symbol) if err != nil { return nil, nil, err @@ -199,10 +199,10 @@ func (s *CBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) return nil, nil, errors.New("failed to parse percentage fee") } - return big.NewInt(0), new(big.Int).Add(baseFee, percFee), nil + return ZeroBigIntValue, new(big.Int).Add(baseFee, percFee), nil } -func (c *CBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (c *CelerBridgeProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { abi, err := abi.JSON(strings.NewReader(celer.CelerABI)) if err != nil { return []byte{}, err @@ -228,7 +228,7 @@ func (c *CBridge) PackTxInputData(params BridgeParams, contractType string) ([]b } } -func (s *CBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *CelerBridgeProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { value := new(big.Int) input, err := s.PackTxInputData(params, "") @@ -270,10 +270,10 @@ func (s *CBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (s *CBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *CelerBridgeProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) - sendArgs := &TransactionBridge{ - CbridgeTx: &CBridgeTxArgs{ + sendArgs := &MultipathProcessorTxArgs{ + CbridgeTx: &CelerBridgeTxArgs{ SendTxArgs: transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -291,7 +291,7 @@ func (s *CBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { return s.BuildTransaction(sendArgs) } -func (s *CBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *CelerBridgeProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { transferConfig, err := s.getTransferConfig(params.FromChain.IsTest) if err != nil { return common.Address{}, err @@ -309,7 +309,7 @@ func (s *CBridge) GetContractAddress(params BridgeParams) (common.Address, error return common.Address{}, errors.New("contract not found") } -func (s *CBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerFn) (*ethTypes.Transaction, error) { +func (s *CelerBridgeProcessor) sendOrBuild(sendArgs *MultipathProcessorTxArgs, signerFn bind.SignerFn) (*ethTypes.Transaction, error) { fromChain := s.rpcClient.NetworkManager.Find(sendArgs.ChainID) if fromChain == nil { return nil, errors.New("network not found") @@ -318,7 +318,7 @@ func (s *CBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerF if token == nil { return nil, errors.New("token not found") } - addrs, err := s.GetContractAddress(BridgeParams{ + addrs, err := s.GetContractAddress(ProcessorInputParams{ FromChain: fromChain, }) if err != nil { @@ -357,7 +357,7 @@ func (s *CBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerF ) } -func (s *CBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { +func (s *CelerBridgeProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { tx, err := s.sendOrBuild(sendArgs, getSigner(sendArgs.ChainID, sendArgs.CbridgeTx.From, verifiedAccount)) if err != nil { return types.HexToHash(""), err @@ -366,11 +366,11 @@ func (s *CBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.Sel return types.Hash(tx.Hash()), nil } -func (s *CBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *CelerBridgeProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.sendOrBuild(sendArgs, nil) } -func (s *CBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *CelerBridgeProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { amt, err := s.estimateAmt(params.FromChain, params.ToChain, params.AmountIn, params.FromToken.Symbol) if err != nil { return nil, err diff --git a/services/wallet/router/bridge/hop.go b/services/wallet/router/pathprocessor/processor_bridge_hop.go similarity index 81% rename from services/wallet/router/bridge/hop.go rename to services/wallet/router/pathprocessor/processor_bridge_hop.go index 3881e80e7..883d6276c 100644 --- a/services/wallet/router/bridge/hop.go +++ b/services/wallet/router/pathprocessor/processor_bridge_hop.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -41,7 +41,7 @@ const ( hopSymbol = "HOP" ) -type HopTxArgs struct { +type HopBridgeTxArgs struct { transactions.SendTxArgs ChainID uint64 `json:"chainId"` Symbol string `json:"symbol"` @@ -105,7 +105,7 @@ func (bf *BonderFee) UnmarshalJSON(data []byte) error { return nil } -type HopBridge struct { +type HopBridgeProcessor struct { transactor transactions.TransactorIface httpClient *thirdparty.HTTPClient tokenManager *token.Manager @@ -113,8 +113,8 @@ type HopBridge struct { bonderFee *BonderFee } -func NewHopBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *token.Manager) *HopBridge { - return &HopBridge{ +func NewHopBridgeProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *token.Manager) *HopBridgeProcessor { + return &HopBridgeProcessor{ contractMaker: &contracts.ContractMaker{RPCClient: rpcClient}, httpClient: thirdparty.NewHTTPClient(), transactor: transactor, @@ -122,18 +122,18 @@ func NewHopBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface } } -func (h *HopBridge) Name() string { - return HopName +func (h *HopBridgeProcessor) Name() string { + return ProcessorBridgeHopName } -func (h *HopBridge) AvailableFor(params BridgeParams) (bool, error) { +func (h *HopBridgeProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { // We chcek if the contract is available on the network for the token _, err := h.GetContractAddress(params) // toToken is not nil only if the send type is Swap return err == nil && params.ToToken == nil, nil } -func (c *HopBridge) getAppropriateABI(contractType string, chainID uint64, token *token.Token) (abi.ABI, error) { +func (c *HopBridgeProcessor) getAppropriateABI(contractType string, chainID uint64, token *token.Token) (abi.ABI, error) { switch contractType { case hop.CctpL1Bridge: return abi.JSON(strings.NewReader(hopL1CctpImplementation.HopL1CctpImplementationABI)) @@ -163,7 +163,7 @@ func (c *HopBridge) getAppropriateABI(contractType string, chainID uint64, token return abi.ABI{}, errors.New("not available for contract type") } -func (h *HopBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (h *HopBridgeProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { abi, err := h.getAppropriateABI(contractType, params.FromChain.ChainID, params.FromToken) if err != nil { return []byte{}, err @@ -185,7 +185,7 @@ func (h *HopBridge) PackTxInputData(params BridgeParams, contractType string) ([ return []byte{}, errors.New("contract type not supported yet") } -func (h *HopBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (h *HopBridgeProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { value := big.NewInt(0) if params.FromToken.IsNative() { value = params.AmountIn @@ -229,10 +229,10 @@ func (h *HopBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (h *HopBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (h *HopBridgeProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) - sendArgs := &TransactionBridge{ - HopTx: &HopTxArgs{ + sendArgs := &MultipathProcessorTxArgs{ + HopTx: &HopBridgeTxArgs{ SendTxArgs: transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -251,12 +251,12 @@ func (h *HopBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) return h.BuildTransaction(sendArgs) } -func (h *HopBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (h *HopBridgeProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { address, _, err := hop.GetContractAddress(params.FromChain.ChainID, params.FromToken.Symbol) return address, err } -func (h *HopBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendOrBuild(sendArgs *MultipathProcessorTxArgs, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { fromChain := h.contractMaker.RPCClient.NetworkManager.Find(sendArgs.ChainID) if fromChain == nil { return tx, fmt.Errorf("ChainID not supported %d", sendArgs.ChainID) @@ -303,7 +303,7 @@ func (h *HopBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.Signe return tx, err } -func (h *HopBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (h *HopBridgeProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { tx, err := h.sendOrBuild(sendArgs, getSigner(sendArgs.ChainID, sendArgs.HopTx.From, verifiedAccount)) if err != nil { return types.Hash{}, err @@ -311,11 +311,11 @@ func (h *HopBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.S return types.Hash(tx.Hash()), nil } -func (h *HopBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (h *HopBridgeProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return h.sendOrBuild(sendArgs, nil) } -func (h *HopBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { +func (h *HopBridgeProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { hopChainsMap := map[uint64]string{ walletCommon.EthereumMainnet: "ethereum", walletCommon.OptimismMainnet: "optimism", @@ -354,16 +354,16 @@ func (h *HopBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, erro // Remove token fee from bonder fee as said here: // https://docs.hop.exchange/v/developer-docs/api/api#get-v1-quote // `bonderFee` - The suggested bonder fee for the amount in. The bonder fee also includes the cost of the destination transaction fee. - tokenFee := big.NewInt(0) //new(big.Int).Sub(h.bonderFee.AmountIn.Int, h.bonderFee.EstimatedRecieved.Int) + tokenFee := ZeroBigIntValue //new(big.Int).Sub(h.bonderFee.AmountIn.Int, h.bonderFee.EstimatedRecieved.Int) return h.bonderFee.BonderFee.Int, tokenFee, nil } -func (h *HopBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (h *HopBridgeProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return h.bonderFee.EstimatedRecieved.Int, nil } -func (h *HopBridge) packCctpL1BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { +func (h *HopBridgeProcessor) packCctpL1BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { return abi.Pack("send", big.NewInt(int64(toChainID)), to, @@ -371,7 +371,7 @@ func (h *HopBridge) packCctpL1BridgeTx(abi abi.ABI, toChainID uint64, to common. h.bonderFee.BonderFee.Int) } -func (h *HopBridge) sendCctpL1BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendCctpL1BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { contractInstance, err := hopL1CctpImplementation.NewHopL1CctpImplementation( contractAddress, ethClient, @@ -388,7 +388,7 @@ func (h *HopBridge) sendCctpL1BridgeTx(contractAddress common.Address, ethClient h.bonderFee.BonderFee.Int) } -func (h *HopBridge) packL1BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { +func (h *HopBridgeProcessor) packL1BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { return abi.Pack("sendToL2", big.NewInt(int64(toChainID)), to, @@ -396,10 +396,10 @@ func (h *HopBridge) packL1BridgeTx(abi abi.ABI, toChainID uint64, to common.Addr h.bonderFee.AmountOutMin.Int, big.NewInt(h.bonderFee.Deadline), common.Address{}, - big.NewInt(0)) + ZeroBigIntValue) } -func (h *HopBridge) sendL1BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts, token *token.Token) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendL1BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts, token *token.Token) (tx *ethTypes.Transaction, err error) { if token.IsNative() { contractInstance, err := hopL1EthBridge.NewHopL1EthBridge( contractAddress, @@ -417,7 +417,7 @@ func (h *HopBridge) sendL1BridgeTx(contractAddress common.Address, ethClient cha h.bonderFee.AmountOutMin.Int, big.NewInt(h.bonderFee.Deadline), common.Address{}, - big.NewInt(0)) + ZeroBigIntValue) } if token.Symbol == hopSymbol { @@ -437,7 +437,7 @@ func (h *HopBridge) sendL1BridgeTx(contractAddress common.Address, ethClient cha h.bonderFee.AmountOutMin.Int, big.NewInt(h.bonderFee.Deadline), common.Address{}, - big.NewInt(0)) + ZeroBigIntValue) } contractInstance, err := hopL1Erc20Bridge.NewHopL1Erc20Bridge( @@ -456,11 +456,11 @@ func (h *HopBridge) sendL1BridgeTx(contractAddress common.Address, ethClient cha h.bonderFee.AmountOutMin.Int, big.NewInt(h.bonderFee.Deadline), common.Address{}, - big.NewInt(0)) + ZeroBigIntValue) } -func (h *HopBridge) packCctpL2BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { +func (h *HopBridgeProcessor) packCctpL2BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { return abi.Pack("send", big.NewInt(int64(toChainID)), to, @@ -468,7 +468,7 @@ func (h *HopBridge) packCctpL2BridgeTx(abi abi.ABI, toChainID uint64, to common. h.bonderFee.BonderFee.Int) } -func (h *HopBridge) sendCctpL2BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendCctpL2BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { contractInstance, err := hopL2CctpImplementation.NewHopL2CctpImplementation( contractAddress, ethClient, @@ -486,7 +486,7 @@ func (h *HopBridge) sendCctpL2BridgeTx(contractAddress common.Address, ethClient ) } -func (h *HopBridge) packL2AmmWrapperTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { +func (h *HopBridgeProcessor) packL2AmmWrapperTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { return abi.Pack("swapAndSend", big.NewInt(int64(toChainID)), to, @@ -498,7 +498,7 @@ func (h *HopBridge) packL2AmmWrapperTx(abi abi.ABI, toChainID uint64, to common. big.NewInt(h.bonderFee.DestinationDeadline)) } -func (h *HopBridge) sendL2AmmWrapperTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendL2AmmWrapperTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { contractInstance, err := hopL2AmmWrapper.NewHopL2AmmWrapper( contractAddress, ethClient, @@ -519,7 +519,7 @@ func (h *HopBridge) sendL2AmmWrapperTx(contractAddress common.Address, ethClient big.NewInt(h.bonderFee.DestinationDeadline)) } -func (h *HopBridge) packL2BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { +func (h *HopBridgeProcessor) packL2BridgeTx(abi abi.ABI, toChainID uint64, to common.Address) ([]byte, error) { return abi.Pack("send", big.NewInt(int64(toChainID)), to, @@ -529,7 +529,7 @@ func (h *HopBridge) packL2BridgeTx(abi abi.ABI, toChainID uint64, to common.Addr big.NewInt(h.bonderFee.Deadline)) } -func (h *HopBridge) sendL2BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { +func (h *HopBridgeProcessor) sendL2BridgeTx(contractAddress common.Address, ethClient chain.ClientInterface, toChainID uint64, to common.Address, txOpts *bind.TransactOpts) (tx *ethTypes.Transaction, err error) { fromChainID := ethClient.NetworkID() if fromChainID == walletCommon.OptimismMainnet || fromChainID == walletCommon.OptimismSepolia { diff --git a/services/wallet/router/bridge/ens_public_key.go b/services/wallet/router/pathprocessor/processor_ens_public_key.go similarity index 65% rename from services/wallet/router/bridge/ens_public_key.go rename to services/wallet/router/pathprocessor/processor_ens_public_key.go index d62e40bb7..d948aa0f2 100644 --- a/services/wallet/router/bridge/ens_public_key.go +++ b/services/wallet/router/pathprocessor/processor_ens_public_key.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -21,14 +21,14 @@ import ( "github.com/status-im/status-go/transactions" ) -type ENSPublicKeyBridge struct { +type ENSPublicKeyProcessor struct { contractMaker *contracts.ContractMaker transactor transactions.TransactorIface ensService *ens.Service } -func NewENSPublicKeyBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSPublicKeyBridge { - return &ENSPublicKeyBridge{ +func NewENSPublicKeyProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSPublicKeyProcessor { + return &ENSPublicKeyProcessor{ contractMaker: &contracts.ContractMaker{ RPCClient: rpcClient, }, @@ -37,29 +37,29 @@ func NewENSPublicKeyBridge(rpcClient *rpc.Client, transactor transactions.Transa } } -func (s *ENSPublicKeyBridge) Name() string { - return ENSPublicKeyName +func (s *ENSPublicKeyProcessor) Name() string { + return ProcessorENSPublicKeyName } -func (s *ENSPublicKeyBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *ENSPublicKeyProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == walletCommon.EthereumMainnet || params.FromChain.ChainID == walletCommon.EthereumSepolia, nil } -func (s *ENSPublicKeyBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { +func (s *ENSPublicKeyProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *ENSPublicKeyBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *ENSPublicKeyProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { resolverABI, err := abi.JSON(strings.NewReader(resolver.PublicResolverABI)) if err != nil { return []byte{}, err } - x, y := extractCoordinates(params.PublicKey) - return resolverABI.Pack("setPubkey", nameHash(params.Username), x, y) + x, y := ens.ExtractCoordinates(params.PublicKey) + return resolverABI.Pack("setPubkey", ens.NameHash(params.Username), x, y) } -func (s *ENSPublicKeyBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *ENSPublicKeyProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { contractAddress, err := s.GetContractAddress(params) if err != nil { return 0, err @@ -92,14 +92,14 @@ func (s *ENSPublicKeyBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (s *ENSPublicKeyBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *ENSPublicKeyProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) inputData, err := s.PackTxInputData(params, "") if err != nil { return nil, err } - sendArgs := &TransactionBridge{ + sendArgs := &MultipathProcessorTxArgs{ TransferTx: &transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -112,19 +112,19 @@ func (s *ENSPublicKeyBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction return s.BuildTransaction(sendArgs) } -func (s *ENSPublicKeyBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (s *ENSPublicKeyProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { return s.transactor.SendTransactionWithChainID(sendArgs.ChainID, *sendArgs.TransferTx, verifiedAccount) } -func (s *ENSPublicKeyBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *ENSPublicKeyProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.transactor.ValidateAndBuildTransaction(sendArgs.ChainID, *sendArgs.TransferTx) } -func (s *ENSPublicKeyBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *ENSPublicKeyProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *ENSPublicKeyBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *ENSPublicKeyProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { addr, err := s.ensService.API().Resolver(context.Background(), params.FromChain.ChainID, params.Username) if err != nil { return common.Address{}, err diff --git a/services/wallet/router/bridge/ens_register.go b/services/wallet/router/pathprocessor/processor_ens_register.go similarity index 67% rename from services/wallet/router/bridge/ens_register.go rename to services/wallet/router/pathprocessor/processor_ens_register.go index c7042d2a3..3e6758f34 100644 --- a/services/wallet/router/bridge/ens_register.go +++ b/services/wallet/router/pathprocessor/processor_ens_register.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -22,14 +22,14 @@ import ( "github.com/status-im/status-go/transactions" ) -type ENSRegisterBridge struct { +type ENSRegisterProcessor struct { contractMaker *contracts.ContractMaker transactor transactions.TransactorIface ensService *ens.Service } -func NewENSRegisterBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSRegisterBridge { - return &ENSRegisterBridge{ +func NewENSRegisterProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSRegisterProcessor { + return &ENSRegisterProcessor{ contractMaker: &contracts.ContractMaker{ RPCClient: rpcClient, }, @@ -39,11 +39,11 @@ func NewENSRegisterBridge(rpcClient *rpc.Client, transactor transactions.Transac } } -func (s *ENSRegisterBridge) Name() string { - return ENSRegisterName +func (s *ENSRegisterProcessor) Name() string { + return ProcessorENSRegisterName } -func (s *ENSRegisterBridge) GetPriceForRegisteringEnsName(chainID uint64) (*big.Int, error) { +func (s *ENSRegisterProcessor) GetPriceForRegisteringEnsName(chainID uint64) (*big.Int, error) { registryAddr, err := s.ensService.API().GetRegistrarAddress(context.Background(), chainID) if err != nil { return nil, err @@ -57,15 +57,15 @@ func (s *ENSRegisterBridge) GetPriceForRegisteringEnsName(chainID uint64) (*big. return registrar.GetPrice(callOpts) } -func (s *ENSRegisterBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *ENSRegisterProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == walletCommon.EthereumMainnet || params.FromChain.ChainID == walletCommon.EthereumSepolia, nil } -func (s *ENSRegisterBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil +func (s *ENSRegisterProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { + return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *ENSRegisterBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *ENSRegisterProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { price, err := s.GetPriceForRegisteringEnsName(params.FromChain.ChainID) if err != nil { return []byte{}, err @@ -76,8 +76,8 @@ func (s *ENSRegisterBridge) PackTxInputData(params BridgeParams, contractType st return []byte{}, err } - x, y := extractCoordinates(params.PublicKey) - extraData, err := registrarABI.Pack("register", usernameToLabel(params.Username), params.FromAddr, x, y) + x, y := ens.ExtractCoordinates(params.PublicKey) + extraData, err := registrarABI.Pack("register", ens.UsernameToLabel(params.Username), params.FromAddr, x, y) if err != nil { return []byte{}, err } @@ -95,7 +95,7 @@ func (s *ENSRegisterBridge) PackTxInputData(params BridgeParams, contractType st return sntABI.Pack("approveAndCall", registryAddr, price, extraData) } -func (s *ENSRegisterBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *ENSRegisterProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { contractAddress, err := s.GetContractAddress(params) if err != nil { return 0, err @@ -114,7 +114,7 @@ func (s *ENSRegisterBridge) EstimateGas(params BridgeParams) (uint64, error) { msg := ethereum.CallMsg{ From: params.FromAddr, To: &contractAddress, - Value: big.NewInt(0), + Value: ZeroBigIntValue, Data: input, } @@ -128,14 +128,14 @@ func (s *ENSRegisterBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (s *ENSRegisterBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *ENSRegisterProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) inputData, err := s.PackTxInputData(params, "") if err != nil { return nil, err } - sendArgs := &TransactionBridge{ + sendArgs := &MultipathProcessorTxArgs{ TransferTx: &transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -148,18 +148,18 @@ func (s *ENSRegisterBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, return s.BuildTransaction(sendArgs) } -func (s *ENSRegisterBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (s *ENSRegisterProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { return s.transactor.SendTransactionWithChainID(sendArgs.ChainID, *sendArgs.TransferTx, verifiedAccount) } -func (s *ENSRegisterBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *ENSRegisterProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.transactor.ValidateAndBuildTransaction(sendArgs.ChainID, *sendArgs.TransferTx) } -func (s *ENSRegisterBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *ENSRegisterProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *ENSRegisterBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *ENSRegisterProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { return snt.ContractAddress(params.FromChain.ChainID) } diff --git a/services/wallet/router/bridge/ens_release.go b/services/wallet/router/pathprocessor/processor_ens_release.go similarity index 60% rename from services/wallet/router/bridge/ens_release.go rename to services/wallet/router/pathprocessor/processor_ens_release.go index 1859f2b23..03f712223 100644 --- a/services/wallet/router/bridge/ens_release.go +++ b/services/wallet/router/pathprocessor/processor_ens_release.go @@ -1,7 +1,8 @@ -package bridge +package pathprocessor import ( "context" + "errors" "math/big" "strings" @@ -20,14 +21,14 @@ import ( "github.com/status-im/status-go/transactions" ) -type ENSReleaseBridge struct { +type ENSReleaseProcessor struct { contractMaker *contracts.ContractMaker transactor transactions.TransactorIface ensService *ens.Service } -func NewENSReleaseBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSReleaseBridge { - return &ENSReleaseBridge{ +func NewENSReleaseProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, ensService *ens.Service) *ENSReleaseProcessor { + return &ENSReleaseProcessor{ contractMaker: &contracts.ContractMaker{ RPCClient: rpcClient, }, @@ -36,28 +37,28 @@ func NewENSReleaseBridge(rpcClient *rpc.Client, transactor transactions.Transact } } -func (s *ENSReleaseBridge) Name() string { - return ENSReleaseName +func (s *ENSReleaseProcessor) Name() string { + return ProcessorENSReleaseName } -func (s *ENSReleaseBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *ENSReleaseProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == walletCommon.EthereumMainnet || params.FromChain.ChainID == walletCommon.EthereumSepolia, nil } -func (s *ENSReleaseBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { +func (s *ENSReleaseProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *ENSReleaseBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *ENSReleaseProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { registrarABI, err := abi.JSON(strings.NewReader(registrar.UsernameRegistrarABI)) if err != nil { return []byte{}, err } - return registrarABI.Pack("release", usernameToLabel(params.Username)) + return registrarABI.Pack("release", ens.UsernameToLabel(params.Username)) } -func (s *ENSReleaseBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *ENSReleaseProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { contractAddress, err := s.GetContractAddress(params) if err != nil { return 0, err @@ -90,14 +91,14 @@ func (s *ENSReleaseBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (s *ENSReleaseBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *ENSReleaseProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) inputData, err := s.PackTxInputData(params, "") if err != nil { return nil, err } - sendArgs := &TransactionBridge{ + sendArgs := &MultipathProcessorTxArgs{ TransferTx: &transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -110,18 +111,25 @@ func (s *ENSReleaseBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, return s.BuildTransaction(sendArgs) } -func (s *ENSReleaseBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (s *ENSReleaseProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { return s.transactor.SendTransactionWithChainID(sendArgs.ChainID, *sendArgs.TransferTx, verifiedAccount) } -func (s *ENSReleaseBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *ENSReleaseProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.transactor.ValidateAndBuildTransaction(sendArgs.ChainID, *sendArgs.TransferTx) } -func (s *ENSReleaseBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *ENSReleaseProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *ENSReleaseBridge) GetContractAddress(params BridgeParams) (common.Address, error) { - return s.ensService.API().GetRegistrarAddress(context.Background(), params.FromChain.ChainID) +func (s *ENSReleaseProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { + addr, err := s.ensService.API().GetRegistrarAddress(context.Background(), params.FromChain.ChainID) + if err != nil { + return common.Address{}, err + } + if addr == ZeroAddress { + return common.Address{}, errors.New("ENS registar not found") + } + return addr, nil } diff --git a/services/wallet/router/bridge/erc1155_transfer.go b/services/wallet/router/pathprocessor/processor_erc1155.go similarity index 70% rename from services/wallet/router/bridge/erc1155_transfer.go rename to services/wallet/router/pathprocessor/processor_erc1155.go index 3c530c4dd..9aea3531a 100644 --- a/services/wallet/router/bridge/erc1155_transfer.go +++ b/services/wallet/router/pathprocessor/processor_erc1155.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -19,35 +19,35 @@ import ( "github.com/status-im/status-go/transactions" ) -type ERC1155TransferTxArgs struct { +type ERC1155TxArgs struct { transactions.SendTxArgs TokenID *hexutil.Big `json:"tokenId"` Recipient common.Address `json:"recipient"` Amount *hexutil.Big `json:"amount"` } -type ERC1155TransferBridge struct { +type ERC1155Processor struct { rpcClient *rpc.Client transactor transactions.TransactorIface } -func NewERC1155TransferBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface) *ERC1155TransferBridge { - return &ERC1155TransferBridge{rpcClient: rpcClient, transactor: transactor} +func NewERC1155Processor(rpcClient *rpc.Client, transactor transactions.TransactorIface) *ERC1155Processor { + return &ERC1155Processor{rpcClient: rpcClient, transactor: transactor} } -func (s *ERC1155TransferBridge) Name() string { - return ERC1155TransferName +func (s *ERC1155Processor) Name() string { + return ProcessorERC1155Name } -func (s *ERC1155TransferBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *ERC1155Processor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == params.ToChain.ChainID && params.ToToken == nil, nil } -func (s *ERC1155TransferBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil +func (s *ERC1155Processor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { + return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *ERC1155TransferBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *ERC1155Processor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { abi, err := abi.JSON(strings.NewReader(ierc1155.Ierc1155ABI)) if err != nil { return []byte{}, err @@ -67,7 +67,7 @@ func (s *ERC1155TransferBridge) PackTxInputData(params BridgeParams, contractTyp ) } -func (s *ERC1155TransferBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *ERC1155Processor) EstimateGas(params ProcessorInputParams) (uint64, error) { ethClient, err := s.rpcClient.EthClient(params.FromChain.ChainID) if err != nil { return 0, err @@ -95,7 +95,7 @@ func (s *ERC1155TransferBridge) EstimateGas(params BridgeParams) (uint64, error) return uint64(increasedEstimation), nil } -func (s *ERC1155TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *ERC1155Processor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { contractAddress := types.Address(params.FromToken.Address) // We store ERC1155 Token ID using big.Int.String() in token.Symbol @@ -104,8 +104,8 @@ func (s *ERC1155TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transact return nil, fmt.Errorf("failed to convert ERC1155's Symbol %s to big.Int", params.FromToken.Symbol) } - sendArgs := &TransactionBridge{ - ERC1155TransferTx: &ERC1155TransferTxArgs{ + sendArgs := &MultipathProcessorTxArgs{ + ERC1155TransferTx: &ERC1155TxArgs{ SendTxArgs: transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &contractAddress, @@ -122,7 +122,7 @@ func (s *ERC1155TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transact return s.BuildTransaction(sendArgs) } -func (s *ERC1155TransferBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { +func (s *ERC1155Processor) sendOrBuild(sendArgs *MultipathProcessorTxArgs, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { ethClient, err := s.rpcClient.EthClient(sendArgs.ChainID) if err != nil { return tx, err @@ -151,7 +151,7 @@ func (s *ERC1155TransferBridge) sendOrBuild(sendArgs *TransactionBridge, signerF return tx, err } -func (s *ERC1155TransferBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (s *ERC1155Processor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { tx, err := s.sendOrBuild(sendArgs, getSigner(sendArgs.ChainID, sendArgs.ERC1155TransferTx.From, verifiedAccount)) if err != nil { return hash, err @@ -159,14 +159,14 @@ func (s *ERC1155TransferBridge) Send(sendArgs *TransactionBridge, verifiedAccoun return types.Hash(tx.Hash()), nil } -func (s *ERC1155TransferBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *ERC1155Processor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.sendOrBuild(sendArgs, nil) } -func (s *ERC1155TransferBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *ERC1155Processor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *ERC1155TransferBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *ERC1155Processor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { return params.FromToken.Address, nil } diff --git a/services/wallet/router/bridge/erc721_transfer.go b/services/wallet/router/pathprocessor/processor_erc721.go similarity index 69% rename from services/wallet/router/bridge/erc721_transfer.go rename to services/wallet/router/pathprocessor/processor_erc721.go index fca811e72..ae95fef6c 100644 --- a/services/wallet/router/bridge/erc721_transfer.go +++ b/services/wallet/router/pathprocessor/processor_erc721.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -19,34 +19,34 @@ import ( "github.com/status-im/status-go/transactions" ) -type ERC721TransferTxArgs struct { +type ERC721TxArgs struct { transactions.SendTxArgs TokenID *hexutil.Big `json:"tokenId"` Recipient common.Address `json:"recipient"` } -type ERC721TransferBridge struct { +type ERC721Processor struct { rpcClient *rpc.Client transactor transactions.TransactorIface } -func NewERC721TransferBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface) *ERC721TransferBridge { - return &ERC721TransferBridge{rpcClient: rpcClient, transactor: transactor} +func NewERC721Processor(rpcClient *rpc.Client, transactor transactions.TransactorIface) *ERC721Processor { + return &ERC721Processor{rpcClient: rpcClient, transactor: transactor} } -func (s *ERC721TransferBridge) Name() string { - return ERC721TransferName +func (s *ERC721Processor) Name() string { + return ProcessorERC721Name } -func (s *ERC721TransferBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *ERC721Processor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == params.ToChain.ChainID && params.ToToken == nil, nil } -func (s *ERC721TransferBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil +func (s *ERC721Processor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { + return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *ERC721TransferBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *ERC721Processor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { abi, err := abi.JSON(strings.NewReader(collectibles.CollectiblesMetaData.ABI)) if err != nil { return []byte{}, err @@ -64,7 +64,7 @@ func (s *ERC721TransferBridge) PackTxInputData(params BridgeParams, contractType ) } -func (s *ERC721TransferBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *ERC721Processor) EstimateGas(params ProcessorInputParams) (uint64, error) { ethClient, err := s.rpcClient.EthClient(params.FromChain.ChainID) if err != nil { return 0, err @@ -93,7 +93,7 @@ func (s *ERC721TransferBridge) EstimateGas(params BridgeParams) (uint64, error) return uint64(increasedEstimation), nil } -func (s *ERC721TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *ERC721Processor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { contractAddress := types.Address(params.FromToken.Address) // We store ERC721 Token ID using big.Int.String() in token.Symbol @@ -102,8 +102,8 @@ func (s *ERC721TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transacti return nil, fmt.Errorf("failed to convert ERC721's Symbol %s to big.Int", params.FromToken.Symbol) } - sendArgs := &TransactionBridge{ - ERC721TransferTx: &ERC721TransferTxArgs{ + sendArgs := &MultipathProcessorTxArgs{ + ERC721TransferTx: &ERC721TxArgs{ SendTxArgs: transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &contractAddress, @@ -119,7 +119,7 @@ func (s *ERC721TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transacti return s.BuildTransaction(sendArgs) } -func (s *ERC721TransferBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { +func (s *ERC721Processor) sendOrBuild(sendArgs *MultipathProcessorTxArgs, signerFn bind.SignerFn) (tx *ethTypes.Transaction, err error) { ethClient, err := s.rpcClient.EthClient(sendArgs.ChainID) if err != nil { return tx, err @@ -145,7 +145,7 @@ func (s *ERC721TransferBridge) sendOrBuild(sendArgs *TransactionBridge, signerFn return tx, err } -func (s *ERC721TransferBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { +func (s *ERC721Processor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (hash types.Hash, err error) { tx, err := s.sendOrBuild(sendArgs, getSigner(sendArgs.ChainID, sendArgs.ERC721TransferTx.From, verifiedAccount)) if err != nil { return hash, err @@ -153,14 +153,14 @@ func (s *ERC721TransferBridge) Send(sendArgs *TransactionBridge, verifiedAccount return types.Hash(tx.Hash()), nil } -func (s *ERC721TransferBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *ERC721Processor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.sendOrBuild(sendArgs, nil) } -func (s *ERC721TransferBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *ERC721Processor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *ERC721TransferBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *ERC721Processor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { return params.FromToken.Address, nil } diff --git a/services/wallet/router/bridge/swap_paraswap.go b/services/wallet/router/pathprocessor/processor_swap_paraswap.go similarity index 76% rename from services/wallet/router/bridge/swap_paraswap.go rename to services/wallet/router/pathprocessor/processor_swap_paraswap.go index efe4e8d49..71ee36358 100644 --- a/services/wallet/router/bridge/swap_paraswap.go +++ b/services/wallet/router/pathprocessor/processor_swap_paraswap.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -18,29 +18,29 @@ import ( "github.com/status-im/status-go/transactions" ) -type SwapTxArgs struct { +type SwapParaswapTxArgs struct { transactions.SendTxArgs ChainID uint64 `json:"chainId"` } -type SwapParaswap struct { +type SwapParaswapProcessor struct { paraswapClient *paraswap.ClientV5 priceRoute paraswap.Route transactor transactions.TransactorIface } -func NewSwapParaswap(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *walletToken.Manager) *SwapParaswap { - return &SwapParaswap{ +func NewSwapParaswapProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface, tokenManager *walletToken.Manager) *SwapParaswapProcessor { + return &SwapParaswapProcessor{ paraswapClient: paraswap.NewClientV5(walletCommon.EthereumMainnet), transactor: transactor, } } -func (s *SwapParaswap) Name() string { - return SwapParaswapName +func (s *SwapParaswapProcessor) Name() string { + return ProcessorSwapParaswapName } -func (s *SwapParaswap) AvailableFor(params BridgeParams) (bool, error) { +func (s *SwapParaswapProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { if params.FromToken == nil || params.ToToken == nil { return false, errors.New("token and toToken cannot be nil") } @@ -85,16 +85,16 @@ func (s *SwapParaswap) AvailableFor(params BridgeParams) (bool, error) { return true, nil } -func (s *SwapParaswap) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil +func (s *SwapParaswapProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { + return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *SwapParaswap) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *SwapParaswapProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { // not sure what we can do here since we're using the api to build the transaction return []byte{}, nil } -func (s *SwapParaswap) EstimateGas(params BridgeParams) (uint64, error) { +func (s *SwapParaswapProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { priceRoute, err := s.paraswapClient.FetchPriceRoute(context.Background(), params.FromToken.Address, params.FromToken.Decimals, params.ToToken.Address, params.ToToken.Decimals, params.AmountIn, params.FromAddr, params.ToAddr) if err != nil { @@ -106,7 +106,7 @@ func (s *SwapParaswap) EstimateGas(params BridgeParams) (uint64, error) { return priceRoute.GasCost.Uint64(), nil } -func (s *SwapParaswap) GetContractAddress(params BridgeParams) (address common.Address, err error) { +func (s *SwapParaswapProcessor) GetContractAddress(params ProcessorInputParams) (address common.Address, err error) { if params.FromChain.ChainID == walletCommon.EthereumMainnet { address = common.HexToAddress("0x216b4b4ba9f3e719726886d34a177484278bfcae") } else if params.FromChain.ChainID == walletCommon.ArbitrumMainnet { @@ -119,10 +119,10 @@ func (s *SwapParaswap) GetContractAddress(params BridgeParams) (address common.A return } -func (s *SwapParaswap) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *SwapParaswapProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) - sendArgs := &TransactionBridge{ - SwapTx: &SwapTxArgs{ + sendArgs := &MultipathProcessorTxArgs{ + SwapTx: &SwapParaswapTxArgs{ SendTxArgs: transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -137,7 +137,7 @@ func (s *SwapParaswap) BuildTx(params BridgeParams) (*ethTypes.Transaction, erro return s.BuildTransaction(sendArgs) } -func (s *SwapParaswap) prepareTransaction(sendArgs *TransactionBridge) error { +func (s *SwapParaswapProcessor) prepareTransaction(sendArgs *MultipathProcessorTxArgs) error { tx, err := s.paraswapClient.BuildTransaction(context.Background(), s.priceRoute.SrcTokenAddress, s.priceRoute.SrcTokenDecimals, s.priceRoute.SrcAmount.Int, s.priceRoute.DestTokenAddress, s.priceRoute.DestTokenDecimals, s.priceRoute.DestAmount.Int, common.Address(sendArgs.SwapTx.From), common.Address(*sendArgs.SwapTx.To), s.priceRoute.RawPriceRoute) if err != nil { @@ -172,7 +172,7 @@ func (s *SwapParaswap) prepareTransaction(sendArgs *TransactionBridge) error { return nil } -func (s *SwapParaswap) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *SwapParaswapProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { err := s.prepareTransaction(sendArgs) if err != nil { return nil, err @@ -180,10 +180,10 @@ func (s *SwapParaswap) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes. return s.transactor.ValidateAndBuildTransaction(sendArgs.ChainID, sendArgs.SwapTx.SendTxArgs) } -func (s *SwapParaswap) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { +func (s *SwapParaswapProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { - txBridgeArgs := &TransactionBridge{ - SwapTx: &SwapTxArgs{ + txBridgeArgs := &MultipathProcessorTxArgs{ + SwapTx: &SwapParaswapTxArgs{ SendTxArgs: transactions.SendTxArgs{ From: sendArgs.SwapTx.From, To: sendArgs.SwapTx.To, @@ -201,6 +201,6 @@ func (s *SwapParaswap) Send(sendArgs *TransactionBridge, verifiedAccount *accoun return s.transactor.SendTransactionWithChainID(txBridgeArgs.ChainID, txBridgeArgs.SwapTx.SendTxArgs, verifiedAccount) } -func (s *SwapParaswap) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *SwapParaswapProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return s.priceRoute.DestAmount.Int, nil } diff --git a/services/wallet/router/bridge/transfer.go b/services/wallet/router/pathprocessor/processor_transfer.go similarity index 66% rename from services/wallet/router/bridge/transfer.go rename to services/wallet/router/pathprocessor/processor_transfer.go index 452035e98..839ddc6c0 100644 --- a/services/wallet/router/bridge/transfer.go +++ b/services/wallet/router/pathprocessor/processor_transfer.go @@ -1,4 +1,4 @@ -package bridge +package pathprocessor import ( "context" @@ -17,28 +17,28 @@ import ( "github.com/status-im/status-go/transactions" ) -type TransferBridge struct { +type TransferProcessor struct { rpcClient *rpc.Client transactor transactions.TransactorIface } -func NewTransferBridge(rpcClient *rpc.Client, transactor transactions.TransactorIface) *TransferBridge { - return &TransferBridge{rpcClient: rpcClient, transactor: transactor} +func NewTransferProcessor(rpcClient *rpc.Client, transactor transactions.TransactorIface) *TransferProcessor { + return &TransferProcessor{rpcClient: rpcClient, transactor: transactor} } -func (s *TransferBridge) Name() string { - return TransferName +func (s *TransferProcessor) Name() string { + return ProcessorTransferName } -func (s *TransferBridge) AvailableFor(params BridgeParams) (bool, error) { +func (s *TransferProcessor) AvailableFor(params ProcessorInputParams) (bool, error) { return params.FromChain.ChainID == params.ToChain.ChainID && params.FromToken != nil && params.ToToken == nil, nil } -func (s *TransferBridge) CalculateFees(params BridgeParams) (*big.Int, *big.Int, error) { - return big.NewInt(0), big.NewInt(0), nil +func (s *TransferProcessor) CalculateFees(params ProcessorInputParams) (*big.Int, *big.Int, error) { + return ZeroBigIntValue, ZeroBigIntValue, nil } -func (s *TransferBridge) PackTxInputData(params BridgeParams, contractType string) ([]byte, error) { +func (s *TransferProcessor) PackTxInputData(params ProcessorInputParams, contractType string) ([]byte, error) { if params.FromToken.IsNative() { return []byte("eth_sendRawTransaction"), nil } else { @@ -53,7 +53,7 @@ func (s *TransferBridge) PackTxInputData(params BridgeParams, contractType strin } } -func (s *TransferBridge) EstimateGas(params BridgeParams) (uint64, error) { +func (s *TransferProcessor) EstimateGas(params ProcessorInputParams) (uint64, error) { estimation := uint64(0) var err error @@ -92,10 +92,10 @@ func (s *TransferBridge) EstimateGas(params BridgeParams) (uint64, error) { return uint64(increasedEstimation), nil } -func (s *TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, error) { +func (s *TransferProcessor) BuildTx(params ProcessorInputParams) (*ethTypes.Transaction, error) { toAddr := types.Address(params.ToAddr) if params.FromToken.IsNative() { - sendArgs := &TransactionBridge{ + sendArgs := &MultipathProcessorTxArgs{ TransferTx: &transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, @@ -118,11 +118,11 @@ func (s *TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, er if err != nil { return nil, err } - sendArgs := &TransactionBridge{ + sendArgs := &MultipathProcessorTxArgs{ TransferTx: &transactions.SendTxArgs{ From: types.Address(params.FromAddr), To: &toAddr, - Value: (*hexutil.Big)(big.NewInt(0)), + Value: (*hexutil.Big)(ZeroBigIntValue), Data: input, }, ChainID: params.FromChain.ChainID, @@ -131,18 +131,18 @@ func (s *TransferBridge) BuildTx(params BridgeParams) (*ethTypes.Transaction, er return s.BuildTransaction(sendArgs) } -func (s *TransferBridge) Send(sendArgs *TransactionBridge, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { +func (s *TransferProcessor) Send(sendArgs *MultipathProcessorTxArgs, verifiedAccount *account.SelectedExtKey) (types.Hash, error) { return s.transactor.SendTransactionWithChainID(sendArgs.ChainID, *sendArgs.TransferTx, verifiedAccount) } -func (s *TransferBridge) BuildTransaction(sendArgs *TransactionBridge) (*ethTypes.Transaction, error) { +func (s *TransferProcessor) BuildTransaction(sendArgs *MultipathProcessorTxArgs) (*ethTypes.Transaction, error) { return s.transactor.ValidateAndBuildTransaction(sendArgs.ChainID, *sendArgs.TransferTx) } -func (s *TransferBridge) CalculateAmountOut(params BridgeParams) (*big.Int, error) { +func (s *TransferProcessor) CalculateAmountOut(params ProcessorInputParams) (*big.Int, error) { return params.AmountIn, nil } -func (s *TransferBridge) GetContractAddress(params BridgeParams) (common.Address, error) { +func (s *TransferProcessor) GetContractAddress(params ProcessorInputParams) (common.Address, error) { return common.Address{}, nil } diff --git a/services/wallet/router/bridge/proto_cbridge/cbridge.proto b/services/wallet/router/pathprocessor/proto_cbridge/cbridge.proto similarity index 100% rename from services/wallet/router/bridge/proto_cbridge/cbridge.proto rename to services/wallet/router/pathprocessor/proto_cbridge/cbridge.proto diff --git a/services/wallet/router/bridge/proto_cbridge/gateway.proto b/services/wallet/router/pathprocessor/proto_cbridge/gateway.proto similarity index 100% rename from services/wallet/router/bridge/proto_cbridge/gateway.proto rename to services/wallet/router/pathprocessor/proto_cbridge/gateway.proto diff --git a/services/wallet/router/bridge/proto_cbridge/generate.go b/services/wallet/router/pathprocessor/proto_cbridge/generate.go similarity index 100% rename from services/wallet/router/bridge/proto_cbridge/generate.go rename to services/wallet/router/pathprocessor/proto_cbridge/generate.go diff --git a/services/wallet/router/bridge/proto_cbridge/query.proto b/services/wallet/router/pathprocessor/proto_cbridge/query.proto similarity index 100% rename from services/wallet/router/bridge/proto_cbridge/query.proto rename to services/wallet/router/pathprocessor/proto_cbridge/query.proto diff --git a/services/wallet/router/router.go b/services/wallet/router/router.go index a2e2cb31e..a68fcffe9 100644 --- a/services/wallet/router/router.go +++ b/services/wallet/router/router.go @@ -26,7 +26,7 @@ import ( "github.com/status-im/status-go/services/wallet/collectibles" walletCommon "github.com/status-im/status-go/services/wallet/common" "github.com/status-im/status-go/services/wallet/market" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/status-im/status-go/services/wallet/token" walletToken "github.com/status-im/status-go/services/wallet/token" "github.com/status-im/status-go/transactions" @@ -148,7 +148,7 @@ func filterRoutes(routes [][]*Path, amountIn *big.Int, fromLockedAmount map[uint fromIncluded := make(map[uint64]bool) fromExcluded := make(map[uint64]bool) for chainID, amount := range fromLockedAmount { - if amount.ToInt().Cmp(bridge.ZeroBigIntValue) == 0 { + if amount.ToInt().Cmp(pathprocessor.ZeroBigIntValue) == 0 { fromExcluded[chainID] = false } else { fromIncluded[chainID] = false @@ -259,7 +259,7 @@ func newSuggestedRoutes( rest := new(big.Int).Set(amountIn) for _, path := range best { diff := new(big.Int).Sub(rest, path.MaxAmountIn.ToInt()) - if diff.Cmp(bridge.ZeroBigIntValue) >= 0 { + if diff.Cmp(pathprocessor.ZeroBigIntValue) >= 0 { path.AmountIn = (*hexutil.Big)(path.MaxAmountIn.ToInt()) } else { path.AmountIn = (*hexutil.Big)(new(big.Int).Set(rest)) @@ -276,26 +276,26 @@ func newSuggestedRoutes( func NewRouter(rpcClient *rpc.Client, transactor *transactions.Transactor, tokenManager *token.Manager, marketManager *market.Manager, collectibles *collectibles.Service, collectiblesManager *collectibles.Manager, ensService *ens.Service, stickersService *stickers.Service) *Router { - bridges := make(map[string]bridge.Bridge) - transfer := bridge.NewTransferBridge(rpcClient, transactor) - erc721Transfer := bridge.NewERC721TransferBridge(rpcClient, transactor) - erc1155Transfer := bridge.NewERC1155TransferBridge(rpcClient, transactor) - cbridge := bridge.NewCbridge(rpcClient, transactor, tokenManager) - hop := bridge.NewHopBridge(rpcClient, transactor, tokenManager) - paraswap := bridge.NewSwapParaswap(rpcClient, transactor, tokenManager) - ensRegister := bridge.NewENSRegisterBridge(rpcClient, transactor, ensService) - ensRelease := bridge.NewENSReleaseBridge(rpcClient, transactor, ensService) - ensPublicKey := bridge.NewENSPublicKeyBridge(rpcClient, transactor, ensService) + processors := make(map[string]pathprocessor.PathProcessor) + transfer := pathprocessor.NewTransferProcessor(rpcClient, transactor) + erc721Transfer := pathprocessor.NewERC721Processor(rpcClient, transactor) + erc1155Transfer := pathprocessor.NewERC1155Processor(rpcClient, transactor) + cbridge := pathprocessor.NewCelerBridgeProcessor(rpcClient, transactor, tokenManager) + hop := pathprocessor.NewHopBridgeProcessor(rpcClient, transactor, tokenManager) + paraswap := pathprocessor.NewSwapParaswapProcessor(rpcClient, transactor, tokenManager) + ensRegister := pathprocessor.NewENSRegisterProcessor(rpcClient, transactor, ensService) + ensRelease := pathprocessor.NewENSReleaseProcessor(rpcClient, transactor, ensService) + ensPublicKey := pathprocessor.NewENSPublicKeyProcessor(rpcClient, transactor, ensService) - bridges[transfer.Name()] = transfer - bridges[erc721Transfer.Name()] = erc721Transfer - bridges[hop.Name()] = hop - bridges[cbridge.Name()] = cbridge - bridges[erc1155Transfer.Name()] = erc1155Transfer - bridges[paraswap.Name()] = paraswap - bridges[ensRegister.Name()] = ensRegister - bridges[ensRelease.Name()] = ensRelease - bridges[ensPublicKey.Name()] = ensPublicKey + processors[transfer.Name()] = transfer + processors[erc721Transfer.Name()] = erc721Transfer + processors[hop.Name()] = hop + processors[cbridge.Name()] = cbridge + processors[erc1155Transfer.Name()] = erc1155Transfer + processors[paraswap.Name()] = paraswap + processors[ensRegister.Name()] = ensRegister + processors[ensRelease.Name()] = ensRelease + processors[ensPublicKey.Name()] = ensPublicKey return &Router{ rpcClient: rpcClient, @@ -306,7 +306,7 @@ func NewRouter(rpcClient *rpc.Client, transactor *transactions.Transactor, token ensService: ensService, stickersService: stickersService, feesManager: &FeeManager{rpcClient}, - bridges: bridges, + pathProcessors: processors, } } @@ -314,8 +314,8 @@ func (r *Router) GetFeesManager() *FeeManager { return r.feesManager } -func (r *Router) GetBridges() map[string]bridge.Bridge { - return r.bridges +func (r *Router) GetPathProcessors() map[string]pathprocessor.PathProcessor { + return r.pathProcessors } func containsNetworkChainID(network *params.Network, chainIDs []uint64) bool { @@ -337,7 +337,7 @@ type Router struct { ensService *ens.Service stickersService *stickers.Service feesManager *FeeManager - bridges map[string]bridge.Bridge + pathProcessors map[string]pathprocessor.PathProcessor } func (r *Router) requireApproval(ctx context.Context, sendType SendType, approvalContractAddress *common.Address, account common.Address, network *params.Network, token *token.Token, amountIn *big.Int) ( @@ -359,7 +359,7 @@ func (r *Router) requireApproval(ctx context.Context, sendType SendType, approva return false, nil, 0, 0, err } - if approvalContractAddress == nil || *approvalContractAddress == bridge.ZeroAddress { + if approvalContractAddress == nil || *approvalContractAddress == pathprocessor.ZeroAddress { return false, nil, 0, 0, nil } @@ -393,7 +393,7 @@ func (r *Router) requireApproval(ctx context.Context, sendType SendType, approva estimate, err := ethClient.EstimateGas(context.Background(), ethereum.CallMsg{ From: account, To: &token.Address, - Value: big.NewInt(0), + Value: pathprocessor.ZeroBigIntValue, Data: data, }) if err != nil { @@ -546,13 +546,15 @@ func (r *Router) SuggestedRoutes( maxFees := gasFees.feeFor(gasFeeMode) estimatedTime := r.feesManager.TransactionEstimatedTime(ctx, network.ChainID, maxFees) - for _, brdg := range r.bridges { - // Skip bridges that are added because of the Router V2, to not break the current functionality - if brdg.Name() == bridge.ENSRegisterName || brdg.Name() == bridge.ENSReleaseName || brdg.Name() == bridge.ENSPublicKeyName { + for _, pProcessor := range r.pathProcessors { + // Skip processors that are added because of the Router V2, to not break the current functionality + if pProcessor.Name() == pathprocessor.ProcessorENSRegisterName || + pProcessor.Name() == pathprocessor.ProcessorENSReleaseName || + pProcessor.Name() == pathprocessor.ProcessorENSPublicKeyName { continue } - if !sendType.canUseBridge(brdg) { + if !sendType.canUseProcessor(pProcessor) { continue } @@ -576,7 +578,7 @@ func (r *Router) SuggestedRoutes( continue } - bridgeParams := bridge.BridgeParams{ + ProcessorInputParams := pathprocessor.ProcessorInputParams{ FromChain: network, ToChain: dest, FromToken: token, @@ -586,19 +588,19 @@ func (r *Router) SuggestedRoutes( AmountIn: amountIn, } - can, err := brdg.AvailableFor(bridgeParams) + can, err := pProcessor.AvailableFor(ProcessorInputParams) if err != nil || !can { continue } - if maxAmountIn.ToInt().Cmp(big.NewInt(0)) == 0 { + if maxAmountIn.ToInt().Cmp(pathprocessor.ZeroBigIntValue) == 0 { continue } - bonderFees, tokenFees, err := brdg.CalculateFees(bridgeParams) + bonderFees, tokenFees, err := pProcessor.CalculateFees(ProcessorInputParams) if err != nil { continue } - if bonderFees.Cmp(bridge.ZeroBigIntValue) != 0 { + if bonderFees.Cmp(pathprocessor.ZeroBigIntValue) != 0 { if maxAmountIn.ToInt().Cmp(amountIn) >= 0 { if bonderFees.Cmp(amountIn) >= 0 { continue @@ -611,7 +613,7 @@ func (r *Router) SuggestedRoutes( } gasLimit := uint64(0) if sendType.isTransfer(false) { - gasLimit, err = brdg.EstimateGas(bridgeParams) + gasLimit, err = pProcessor.EstimateGas(ProcessorInputParams) if err != nil { continue } @@ -619,7 +621,7 @@ func (r *Router) SuggestedRoutes( gasLimit = sendType.EstimateGas(r.ensService, r.stickersService, network, addrFrom, tokenID) } - approvalContractAddress, err := brdg.GetContractAddress(bridgeParams) + approvalContractAddress, err := pProcessor.GetContractAddress(ProcessorInputParams) if err != nil { continue } @@ -630,7 +632,7 @@ func (r *Router) SuggestedRoutes( var l1GasFeeWei uint64 if sendType.needL1Fee() { - txInputData, err := brdg.PackTxInputData(bridgeParams, "") + txInputData, err := pProcessor.PackTxInputData(ProcessorInputParams, "") if err != nil { continue } @@ -680,12 +682,12 @@ func (r *Router) SuggestedRoutes( cost.Add(cost, l1GasCost) mu.Lock() candidates = append(candidates, &Path{ - BridgeName: brdg.Name(), + BridgeName: pProcessor.Name(), From: network, To: dest, MaxAmountIn: maxAmountIn, - AmountIn: (*hexutil.Big)(bridge.ZeroBigIntValue), - AmountOut: (*hexutil.Big)(bridge.ZeroBigIntValue), + AmountIn: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), + AmountOut: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), GasAmount: gasLimit, GasFees: gasFees, BonderFees: (*hexutil.Big)(bonderFees), @@ -710,7 +712,7 @@ func (r *Router) SuggestedRoutes( suggestedRoutes.TokenPrice = prices[tokenID] suggestedRoutes.NativeChainTokenPrice = prices["ETH"] for _, path := range suggestedRoutes.Best { - bridgeParams := bridge.BridgeParams{ + ProcessorInputParams := pathprocessor.ProcessorInputParams{ FromChain: path.From, ToChain: path.To, AmountIn: path.AmountIn.ToInt(), @@ -719,7 +721,7 @@ func (r *Router) SuggestedRoutes( }, } - amountOut, err := r.bridges[path.BridgeName].CalculateAmountOut(bridgeParams) + amountOut, err := r.pathProcessors[path.BridgeName].CalculateAmountOut(ProcessorInputParams) if err != nil { continue } diff --git a/services/wallet/router/router_send_type.go b/services/wallet/router/router_send_type.go index b7602fcd8..459dad84a 100644 --- a/services/wallet/router/router_send_type.go +++ b/services/wallet/router/router_send_type.go @@ -16,7 +16,7 @@ import ( "github.com/status-im/status-go/services/wallet/collectibles" walletCommon "github.com/status-im/status-go/services/wallet/common" "github.com/status-im/status-go/services/wallet/market" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/status-im/status-go/services/wallet/token" "github.com/status-im/status-go/transactions" ) @@ -99,19 +99,19 @@ func (s SendType) needL1Fee() bool { return s != ENSRegister && s != ENSRelease && s != ENSSetPubKey && s != StickersBuy } -func (s SendType) canUseBridge(b bridge.Bridge) bool { - bridgeName := b.Name() +func (s SendType) canUseProcessor(p pathprocessor.PathProcessor) bool { + pathProcessorName := p.Name() switch s { case ERC721Transfer: - return bridgeName == bridge.ERC721TransferName + return pathProcessorName == pathprocessor.ProcessorERC721Name case ERC1155Transfer: - return bridgeName == bridge.ERC1155TransferName + return pathProcessorName == pathprocessor.ProcessorERC1155Name case ENSRegister: - return bridgeName == bridge.ENSRegisterName + return pathProcessorName == pathprocessor.ProcessorENSRegisterName case ENSRelease: - return bridgeName == bridge.ENSReleaseName + return pathProcessorName == pathprocessor.ProcessorENSReleaseName case ENSSetPubKey: - return bridgeName == bridge.ENSPublicKeyName + return pathProcessorName == pathprocessor.ProcessorENSPublicKeyName default: return true } @@ -169,7 +169,7 @@ func (s SendType) isAvailableFor(network *params.Network) bool { func (s SendType) EstimateGas(ensService *ens.Service, stickersService *stickers.Service, network *params.Network, from common.Address, tokenID string) uint64 { tx := transactions.SendTxArgs{ From: (types.Address)(from), - Value: (*hexutil.Big)(bridge.ZeroBigIntValue), + Value: (*hexutil.Big)(pathprocessor.ZeroBigIntValue), } switch s { case ENSRegister: diff --git a/services/wallet/router/router_v2.go b/services/wallet/router/router_v2.go index 7de8166bb..aae9cfcfb 100644 --- a/services/wallet/router/router_v2.go +++ b/services/wallet/router/router_v2.go @@ -11,9 +11,10 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/status-im/status-go/params" + "github.com/status-im/status-go/services/ens" "github.com/status-im/status-go/services/wallet/async" walletCommon "github.com/status-im/status-go/services/wallet/common" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" walletToken "github.com/status-im/status-go/services/wallet/token" ) @@ -51,7 +52,7 @@ type RouteInputParams struct { } type PathV2 struct { - BridgeName string + ProcessorName string FromChain *params.Network // Source chain ToChain *params.Network // Destination chain FromToken *walletToken.Token // Token on the source chain @@ -132,7 +133,7 @@ func newSuggestedRoutesV2( rest := new(big.Int).Set(amountIn) for _, path := range best { diff := new(big.Int).Sub(rest, path.AmountIn.ToInt()) - if diff.Cmp(bridge.ZeroBigIntValue) >= 0 { + if diff.Cmp(pathprocessor.ZeroBigIntValue) >= 0 { path.AmountIn = (*hexutil.Big)(path.AmountIn.ToInt()) } else { path.AmountIn = (*hexutil.Big)(new(big.Int).Set(rest)) @@ -234,7 +235,7 @@ func findBestV2(routes [][]*PathV2, tokenPrice float64, nativeChainTokenPrice fl pathCost = new(big.Float).Mul(txFeeInEth, nativeTokenPrice) } - if path.TxBonderFees != nil && path.TxBonderFees.ToInt().Cmp(bridge.ZeroBigIntValue) > 0 { + if path.TxBonderFees != nil && path.TxBonderFees.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 { path.requiredTokenBalance.Add(path.requiredTokenBalance, path.TxBonderFees.ToInt()) pathCost.Add(pathCost, new(big.Float).Mul( new(big.Float).Quo(new(big.Float).SetInt(path.TxBonderFees.ToInt()), tokenDenominator), @@ -242,7 +243,7 @@ func findBestV2(routes [][]*PathV2, tokenPrice float64, nativeChainTokenPrice fl } - if path.TxL1Fee != nil && path.TxL1Fee.ToInt().Cmp(bridge.ZeroBigIntValue) > 0 { + if path.TxL1Fee != nil && path.TxL1Fee.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 { l1FeeInWei := path.TxL1Fee.ToInt() l1FeeInEth := gweiToEth(weiToGwei(l1FeeInWei)) @@ -250,7 +251,7 @@ func findBestV2(routes [][]*PathV2, tokenPrice float64, nativeChainTokenPrice fl pathCost.Add(pathCost, new(big.Float).Mul(l1FeeInEth, nativeTokenPrice)) } - if path.TxTokenFees != nil && path.TxTokenFees.ToInt().Cmp(bridge.ZeroBigIntValue) > 0 && path.FromToken != nil { + if path.TxTokenFees != nil && path.TxTokenFees.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 && path.FromToken != nil { path.requiredTokenBalance.Add(path.requiredTokenBalance, path.TxTokenFees.ToInt()) pathCost.Add(pathCost, new(big.Float).Mul( new(big.Float).Quo(new(big.Float).SetInt(path.TxTokenFees.ToInt()), tokenDenominator), @@ -294,11 +295,11 @@ func validateInputData(input *RouteInputParams) error { return errors.New("username and public key are required for ENSRegister") } if input.TestnetMode { - if input.TokenID != bridge.SttSymbol { + if input.TokenID != pathprocessor.SttSymbol { return errors.New("only STT is supported for ENSRegister on testnet") } } else { - if input.TokenID != bridge.SntSymbol { + if input.TokenID != pathprocessor.SntSymbol { return errors.New("only SNT is supported for ENSRegister") } } @@ -311,6 +312,12 @@ func validateInputData(input *RouteInputParams) error { } } + if input.SendType == ENSSetPubKey { + if input.Username == "" || input.PublicKey == "" || ens.ValidateENSUsername(input.Username) != nil { + return errors.New("username and public key are required for ENSSetPubKey") + } + } + if input.FromLockedAmount != nil && len(input.FromLockedAmount) > 0 { for chainID, amount := range input.FromLockedAmount { if input.TestnetMode { @@ -398,8 +405,8 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) return err } - for _, brdg := range r.bridges { - if !input.SendType.canUseBridge(brdg) { + for _, pProcessor := range r.pathProcessors { + if !input.SendType.canUseProcessor(pProcessor) { continue } @@ -424,7 +431,7 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) continue } - bridgeParams := bridge.BridgeParams{ + ProcessorInputParams := pathprocessor.ProcessorInputParams{ FromChain: network, ToChain: dest, FromToken: token, @@ -437,22 +444,22 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) PublicKey: input.PublicKey, } - can, err := brdg.AvailableFor(bridgeParams) + can, err := pProcessor.AvailableFor(ProcessorInputParams) if err != nil || !can { continue } - bonderFees, tokenFees, err := brdg.CalculateFees(bridgeParams) + bonderFees, tokenFees, err := pProcessor.CalculateFees(ProcessorInputParams) if err != nil { continue } - gasLimit, err := brdg.EstimateGas(bridgeParams) + gasLimit, err := pProcessor.EstimateGas(ProcessorInputParams) if err != nil { continue } - approvalContractAddress, err := brdg.GetContractAddress(bridgeParams) + approvalContractAddress, err := pProcessor.GetContractAddress(ProcessorInputParams) if err != nil { continue } @@ -464,7 +471,7 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) var l1FeeWei uint64 if input.SendType.needL1Fee() { - txInputData, err := brdg.PackTxInputData(bridgeParams, "") + txInputData, err := pProcessor.PackTxInputData(ProcessorInputParams, "") if err != nil { continue } @@ -488,7 +495,7 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) selctedPriorityFee = priorityFees.Low } - amountOut, err := brdg.CalculateAmountOut(bridgeParams) + amountOut, err := pProcessor.CalculateAmountOut(ProcessorInputParams) if err != nil { continue } @@ -502,7 +509,7 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) mu.Lock() candidates = append(candidates, &PathV2{ - BridgeName: brdg.Name(), + ProcessorName: pProcessor.Name(), FromChain: network, ToChain: network, FromToken: token, @@ -549,7 +556,7 @@ func (r *Router) SuggestedRoutesV2(ctx context.Context, input *RouteInputParams) // check the best route for the required balances for _, path := range suggestedRoutes.Best { - if path.requiredTokenBalance != nil && path.requiredTokenBalance.Cmp(big.NewInt(0)) > 0 { + if path.requiredTokenBalance != nil && path.requiredTokenBalance.Cmp(pathprocessor.ZeroBigIntValue) > 0 { tokenBalance := big.NewInt(1) if input.SendType == ERC1155Transfer { tokenBalance, err = r.getERC1155Balance(ctx, path.FromChain, path.FromToken, input.AddrFrom) diff --git a/services/wallet/transfer/helpers.go b/services/wallet/transfer/helpers.go index 970219bc0..6d7f10f7b 100644 --- a/services/wallet/transfer/helpers.go +++ b/services/wallet/transfer/helpers.go @@ -15,7 +15,7 @@ import ( "github.com/status-im/status-go/eth-node/crypto" "github.com/status-im/status-go/eth-node/types" wallet_common "github.com/status-im/status-go/services/wallet/common" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" ) func rowsToMultiTransactions(rows *sql.Rows) ([]*MultiTransaction, error) { @@ -121,7 +121,7 @@ func multiTransactionFromCommand(command *MultiTransactionCommand) *MultiTransac return multiTransaction } -func updateDataFromMultiTx(data []*bridge.TransactionBridge, multiTransaction *MultiTransaction) { +func updateDataFromMultiTx(data []*pathprocessor.MultipathProcessorTxArgs, multiTransaction *MultiTransaction) { for _, tx := range data { if tx.TransferTx != nil { tx.TransferTx.MultiTransactionID = multiTransaction.ID @@ -150,12 +150,12 @@ func updateDataFromMultiTx(data []*bridge.TransactionBridge, multiTransaction *M } } -func sendTransactions(data []*bridge.TransactionBridge, bridges map[string]bridge.Bridge, account *account.SelectedExtKey) ( +func sendTransactions(data []*pathprocessor.MultipathProcessorTxArgs, pathProcessors map[string]pathprocessor.PathProcessor, account *account.SelectedExtKey) ( map[uint64][]types.Hash, error) { hashes := make(map[uint64][]types.Hash) for _, tx := range data { - hash, err := bridges[tx.BridgeName].Send(tx, account) + hash, err := pathProcessors[tx.Name].Send(tx, account) if err != nil { return nil, err // TODO: One of transfers within transaction could have been sent. Need to notify user about it } diff --git a/services/wallet/transfer/transaction_manager.go b/services/wallet/transfer/transaction_manager.go index bdcc2b1e0..d58fb3577 100644 --- a/services/wallet/transfer/transaction_manager.go +++ b/services/wallet/transfer/transaction_manager.go @@ -16,7 +16,7 @@ import ( "github.com/status-im/status-go/multiaccounts/accounts" "github.com/status-im/status-go/params" wallet_common "github.com/status-im/status-go/services/wallet/common" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/status-im/status-go/transactions" ) @@ -43,7 +43,7 @@ type TransactionManager struct { eventFeed *event.Feed multiTransactionForKeycardSigning *MultiTransaction - transactionsBridgeData []*bridge.TransactionBridge + multipathTransactionsData []*pathprocessor.MultipathProcessorTxArgs transactionsForKeycardSigning map[common.Hash]*TransactionDescription } diff --git a/services/wallet/transfer/transaction_manager_internal.go b/services/wallet/transfer/transaction_manager_internal.go index 5f4e56406..507283af6 100644 --- a/services/wallet/transfer/transaction_manager_internal.go +++ b/services/wallet/transfer/transaction_manager_internal.go @@ -5,14 +5,14 @@ import ( "github.com/ethereum/go-ethereum/common" ethTypes "github.com/ethereum/go-ethereum/core/types" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" ) -func (tm *TransactionManager) buildTransactions(bridges map[string]bridge.Bridge) ([]string, error) { +func (tm *TransactionManager) buildTransactions(pathProcessors map[string]pathprocessor.PathProcessor) ([]string, error) { tm.transactionsForKeycardSigning = make(map[common.Hash]*TransactionDescription) var hashes []string - for _, bridgeTx := range tm.transactionsBridgeData { - builtTx, err := bridges[bridgeTx.BridgeName].BuildTransaction(bridgeTx) + for _, bridgeTx := range tm.multipathTransactionsData { + builtTx, err := pathProcessors[bridgeTx.Name].BuildTransaction(bridgeTx) if err != nil { return hashes, err } diff --git a/services/wallet/transfer/transaction_manager_multitransaction.go b/services/wallet/transfer/transaction_manager_multitransaction.go index a9f9c2bb5..62593e06b 100644 --- a/services/wallet/transfer/transaction_manager_multitransaction.go +++ b/services/wallet/transfer/transaction_manager_multitransaction.go @@ -13,7 +13,7 @@ import ( "github.com/status-im/status-go/account" "github.com/status-im/status-go/eth-node/types" wallet_common "github.com/status-im/status-go/services/wallet/common" - "github.com/status-im/status-go/services/wallet/router/bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" "github.com/status-im/status-go/services/wallet/walletevent" "github.com/status-im/status-go/signal" "github.com/status-im/status-go/transactions" @@ -35,7 +35,7 @@ func (tm *TransactionManager) UpdateMultiTransaction(multiTransaction *MultiTran } func (tm *TransactionManager) CreateMultiTransactionFromCommand(command *MultiTransactionCommand, - data []*bridge.TransactionBridge) (*MultiTransaction, error) { + data []*pathprocessor.MultipathProcessorTxArgs) (*MultiTransaction, error) { multiTransaction := multiTransactionFromCommand(command) @@ -46,7 +46,7 @@ func (tm *TransactionManager) CreateMultiTransactionFromCommand(command *MultiTr return multiTransaction, nil } -func (tm *TransactionManager) SendTransactionForSigningToKeycard(ctx context.Context, multiTransaction *MultiTransaction, data []*bridge.TransactionBridge, bridges map[string]bridge.Bridge) error { +func (tm *TransactionManager) SendTransactionForSigningToKeycard(ctx context.Context, multiTransaction *MultiTransaction, data []*pathprocessor.MultipathProcessorTxArgs, pathProcessors map[string]pathprocessor.PathProcessor) error { acc, err := tm.accountsDB.GetAccountByAddress(types.Address(multiTransaction.FromAddress)) if err != nil { return err @@ -62,8 +62,8 @@ func (tm *TransactionManager) SendTransactionForSigningToKeycard(ctx context.Con } tm.multiTransactionForKeycardSigning = multiTransaction - tm.transactionsBridgeData = data - hashes, err := tm.buildTransactions(bridges) + tm.multipathTransactionsData = data + hashes, err := tm.buildTransactions(pathProcessors) if err != nil { return err } @@ -73,9 +73,9 @@ func (tm *TransactionManager) SendTransactionForSigningToKeycard(ctx context.Con return nil } -func (tm *TransactionManager) SendTransactions(ctx context.Context, multiTransaction *MultiTransaction, data []*bridge.TransactionBridge, bridges map[string]bridge.Bridge, account *account.SelectedExtKey) (*MultiTransactionCommandResult, error) { +func (tm *TransactionManager) SendTransactions(ctx context.Context, multiTransaction *MultiTransaction, data []*pathprocessor.MultipathProcessorTxArgs, pathProcessors map[string]pathprocessor.PathProcessor, account *account.SelectedExtKey) (*MultiTransactionCommandResult, error) { updateDataFromMultiTx(data, multiTransaction) - hashes, err := sendTransactions(data, bridges, account) + hashes, err := sendTransactions(data, pathProcessors, account) if err != nil { return nil, err } diff --git a/services/wallet/transfer/transaction_manager_multitransaction_test.go b/services/wallet/transfer/transaction_manager_multitransaction_test.go index 689159c43..be7f0c998 100644 --- a/services/wallet/transfer/transaction_manager_multitransaction_test.go +++ b/services/wallet/transfer/transaction_manager_multitransaction_test.go @@ -17,8 +17,8 @@ import ( "github.com/status-im/status-go/eth-node/types" "github.com/status-im/status-go/rpc" wallet_common "github.com/status-im/status-go/services/wallet/common" - "github.com/status-im/status-go/services/wallet/router/bridge" - "github.com/status-im/status-go/services/wallet/router/bridge/mock_bridge" + "github.com/status-im/status-go/services/wallet/router/pathprocessor" + "github.com/status-im/status-go/services/wallet/router/pathprocessor/mock_pathprocessor" "github.com/status-im/status-go/services/wallet/walletevent" "github.com/status-im/status-go/t/helpers" "github.com/status-im/status-go/transactions" @@ -35,9 +35,9 @@ func deepCopy(tx *transactions.SendTxArgs) *transactions.SendTxArgs { } } -func deepCopyTransactionBridgeWithTransferTx(tx *bridge.TransactionBridge) *bridge.TransactionBridge { - return &bridge.TransactionBridge{ - BridgeName: tx.BridgeName, +func deepCopyTransactionBridgeWithTransferTx(tx *pathprocessor.MultipathProcessorTxArgs) *pathprocessor.MultipathProcessorTxArgs { + return &pathprocessor.MultipathProcessorTxArgs{ + Name: tx.Name, ChainID: tx.ChainID, TransferTx: deepCopy(tx.TransferTx), HopTx: tx.HopTx, @@ -68,7 +68,7 @@ func setupAccount(_ *testing.T, address common.Address) *account.SelectedExtKey } } -func setupTransactionData(_ *testing.T, transactor transactions.TransactorIface) (*MultiTransaction, []*bridge.TransactionBridge, map[string]bridge.Bridge, []*bridge.TransactionBridge) { +func setupTransactionData(_ *testing.T, transactor transactions.TransactorIface) (*MultiTransaction, []*pathprocessor.MultipathProcessorTxArgs, map[string]pathprocessor.PathProcessor, []*pathprocessor.MultipathProcessorTxArgs) { SetMultiTransactionIDGenerator(StaticIDCounter()) // Create mock data for the test @@ -77,14 +77,14 @@ func setupTransactionData(_ *testing.T, transactor transactions.TransactorIface) // Initialize the bridges var rpcClient *rpc.Client = nil - bridges := make(map[string]bridge.Bridge) - transferBridge := bridge.NewTransferBridge(rpcClient, transactor) + bridges := make(map[string]pathprocessor.PathProcessor) + transferBridge := pathprocessor.NewTransferProcessor(rpcClient, transactor) bridges[transferBridge.Name()] = transferBridge - data := []*bridge.TransactionBridge{ + data := []*pathprocessor.MultipathProcessorTxArgs{ { - ChainID: 1, - BridgeName: transferBridge.Name(), + ChainID: 1, + Name: transferBridge.Name(), TransferTx: &transactions.SendTxArgs{ From: types.Address(ethTransfer.From), To: (*types.Address)(ðTransfer.To), @@ -95,8 +95,8 @@ func setupTransactionData(_ *testing.T, transactor transactions.TransactorIface) }, }, { - ChainID: 420, - BridgeName: transferBridge.Name(), + ChainID: 420, + Name: transferBridge.Name(), TransferTx: &transactions.SendTxArgs{ From: types.Address(ethTransfer.From), To: (*types.Address)(ðTransfer.To), @@ -108,10 +108,10 @@ func setupTransactionData(_ *testing.T, transactor transactions.TransactorIface) }, } - expectedData := make([]*bridge.TransactionBridge, 0) + expectedData := make([]*pathprocessor.MultipathProcessorTxArgs, 0) for _, tx := range data { txCopy := deepCopyTransactionBridgeWithTransferTx(tx) - updateDataFromMultiTx([]*bridge.TransactionBridge{txCopy}, &multiTransaction) + updateDataFromMultiTx([]*pathprocessor.MultipathProcessorTxArgs{txCopy}, &multiTransaction) expectedData = append(expectedData, txCopy) } @@ -140,11 +140,11 @@ func TestSendTransactionsETHFailOnBridge(t *testing.T) { multiTransaction, data, _, _ := setupTransactionData(t, transactor) // Initialize the bridges - bridges := make(map[string]bridge.Bridge) - transferBridge := mock_bridge.NewMockBridge(ctrl) + bridges := make(map[string]pathprocessor.PathProcessor) + transferBridge := mock_pathprocessor.NewMockPathProcessor(ctrl) // Set bridge name for the mock to the one used in data - transferBridge.EXPECT().Name().Return(data[0].BridgeName).AnyTimes() + transferBridge.EXPECT().Name().Return(data[0].Name).AnyTimes() bridges[transferBridge.Name()] = transferBridge expectedErr := transactions.ErrInvalidTxSender // Any error to verify