Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ jobs:
needs:
- prepare
steps:
- name: Add git config for Go private module
run: git config --global url."https://${{ secrets.GH_PAT }}:[email protected]/".insteadOf https://github.com/
- name: Checkout
uses: actions/checkout@v4
- name: Install Go
Expand Down Expand Up @@ -61,6 +63,8 @@ jobs:
needs:
- prepare
steps:
- name: Add git config for Go private module
run: git config --global url."https://${{ secrets.GH_PAT }}:[email protected]/".insteadOf https://github.com/
- name: Checkout
uses: actions/checkout@v4
- name: Install Go
Expand Down
73 changes: 73 additions & 0 deletions pkg/mev/base_chain_sender.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package mev

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"

"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
)

type BaseChainSender struct {
c *http.Client
endpoint string
senderType BundleSenderType
}

func NewBaseChainSender(
c *http.Client,
endpoint string,
senderType BundleSenderType,
) *BaseChainSender {
return &BaseChainSender{
c: c,
endpoint: endpoint,
senderType: senderType,
}
}

func (s *BaseChainSender) GetSenderType() BundleSenderType {
return s.senderType
}

func (s *BaseChainSender) SendRawTransaction(
ctx context.Context,
tx *types.Transaction,
) (SendRawTransactionResponse, error) {
txBin, err := tx.MarshalBinary()
if err != nil {
return SendRawTransactionResponse{}, fmt.Errorf("marshal tx binary: %w", err)
}

req := SendRequest{
ID: SendBundleID,
JSONRPC: JSONRPC2,
Method: ETHSendRawTransaction,
Params: []any{hexutil.Encode(txBin)},
}

reqBody, err := json.Marshal(req)
if err != nil {
return SendRawTransactionResponse{}, fmt.Errorf("marshal json error: %w", err)
}

httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewBuffer(reqBody))
if err != nil {
return SendRawTransactionResponse{}, fmt.Errorf("new http request error: %w", err)
}

resp, err := doRequest[SendRawTransactionResponse](s.c, httpReq)
if err != nil {
return SendRawTransactionResponse{}, err
}

if len(resp.Error.Messange) != 0 {
return SendRawTransactionResponse{}, fmt.Errorf("response error, code: [%d], message: [%s]",
resp.Error.Code, resp.Error.Messange)
}

return resp, nil
}
150 changes: 150 additions & 0 deletions pkg/mev/base_chain_sender_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package mev_test

import (
"context"
"math/big"
"net/http"
"testing"
"time"

"github.com/KyberNetwork/tradinglib/pkg/mev"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/stretchr/testify/require"
)

func TestBaseChainSender_SendRawTransaction(t *testing.T) {
t.Skip("Skip by default - uncomment to run actual test against Base mainnet")

// Create HTTP client
httpClient := &http.Client{Timeout: time.Second * 30}

// Initialize BaseChainSender with Base mainnet RPC
sender := mev.NewBaseChainSender(
httpClient,
"https://mainnet.base.org",
mev.BundleSenderTypeBaseMainnet,
)

// Verify sender type
require.Equal(t, mev.BundleSenderTypeBaseMainnet, sender.GetSenderType())

// Create a test transaction (this is a dummy transaction that will likely fail)
// In a real scenario, you would use proper private key, nonce, gas price, etc.
privateKey, err := crypto.GenerateKey()
require.NoError(t, err)

// Connect to Base mainnet to get current gas price and nonce
ethClient, err := ethclient.Dial("https://mainnet.base.org")
require.NoError(t, err)

fromAddress := crypto.PubkeyToAddress(privateKey.PublicKey)
nonce, err := ethClient.PendingNonceAt(context.Background(), fromAddress)
require.NoError(t, err)

gasPrice, err := ethClient.SuggestGasPrice(context.Background())
require.NoError(t, err)

// Create a simple ETH transfer transaction
toAddress := common.HexToAddress("0x0000000000000000000000000000000000000001") // Burn address
value := big.NewInt(1) // 1 wei
gasLimit := uint64(21000) // Standard ETH transfer gas

// Get chain ID for Base mainnet (8453)
chainID, err := ethClient.ChainID(context.Background())
require.NoError(t, err)
require.Equal(t, int64(8453), chainID.Int64()) // Base mainnet chain ID

// Create transaction
tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil)

// Sign transaction
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)
require.NoError(t, err)

// Send transaction using BaseChainSender
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()

resp, err := sender.SendRawTransaction(ctx, signedTx)

// Log the response for debugging
t.Logf("Response: %+v", resp)
t.Logf("Error: %v", err)

// The transaction will likely fail due to insufficient funds, but we should get a proper response
// We expect either a successful response with transaction hash or a proper error response
if err != nil {
// Check if it's a proper RPC error (not a network/parsing error)
t.Logf("Expected error due to insufficient funds or other RPC error: %v", err)
} else {
// If successful, verify response structure
require.Equal(t, "2.0", resp.Jsonrpc)
require.Equal(t, 1, resp.ID)
require.NotEmpty(t, resp.Result)
t.Logf("Transaction hash: %s", resp.Result)
}
}

func TestBaseChainSender_SendRawTransaction_InvalidTx(t *testing.T) {
t.Skip("Skip by default - uncomment to run actual test against Base mainnet")
// Create HTTP client
httpClient := &http.Client{Timeout: time.Second * 10}

// Initialize BaseChainSender with Base mainnet RPC
sender := mev.NewBaseChainSender(
httpClient,
"https://mainnet.base.org",
mev.BundleSenderTypeBaseMainnet,
)

// Create an invalid transaction (unsigned)
toAddress := common.HexToAddress("0x0000000000000000000000000000000000000001")
value := big.NewInt(1)
gasLimit := uint64(21000)
gasPrice := big.NewInt(1000000000) // 1 gwei

// Create unsigned transaction
tx := types.NewTransaction(0, toAddress, value, gasLimit, gasPrice, nil)

// Try to send unsigned transaction (should fail)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()

resp, err := sender.SendRawTransaction(ctx, tx)

// Should get an error due to invalid transaction
t.Logf("Response: %+v", resp)
t.Logf("Error: %v", err)

// We expect an error here
require.Error(t, err)
}

func TestBaseChainSender_Interface_Compliance(t *testing.T) {
t.Skip("Skip by default - uncomment to run actual test against Base mainnet")
// Test that BaseChainSender implements ISendRawTransaction interface
httpClient := &http.Client{Timeout: time.Second * 10}
sender := mev.NewBaseChainSender(
httpClient,
"https://mainnet.base.org",
mev.BundleSenderTypeBaseMainnet,
)

// Verify it implements the interface
var _ mev.ISendRawTransaction = sender
}

func TestNewBaseChainSender(t *testing.T) {
t.Skip("Skip by default - uncomment to run actual test against Base mainnet")
httpClient := &http.Client{Timeout: time.Second * 10}
endpoint := "https://mainnet.base.org"
senderType := mev.BundleSenderTypeBaseMainnet

sender := mev.NewBaseChainSender(httpClient, endpoint, senderType)

require.NotNil(t, sender)
require.Equal(t, senderType, sender.GetSenderType())
}
12 changes: 8 additions & 4 deletions pkg/mev/bundlesendertype_enumer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions pkg/mev/pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const (
BundleSenderTypeQuasar
BundleSenderTypeBuilderNet
BundleSenderTypeBTCS
BundleSenderTypeBaseMainnet
)

const (
Expand All @@ -58,10 +59,25 @@ const (
FlashbotGetUserStats = "flashbots_getUserStats"
FlashbotGetUserStatsV2 = "flashbots_getUserStatsV2"
TitanGetUserStats = "titan_getUserStats"
ETHSendRawTransaction = "eth_sendRawTransaction"

MaxBlockFromTarget = 3
)

type ISendRawTransaction interface {
SendRawTransaction(
ctx context.Context,
tx *types.Transaction,
) (SendRawTransactionResponse, error)
}

type SendRawTransactionResponse struct {
Jsonrpc string `json:"jsonrpc"`
ID int `json:"id"`
Result string `json:"result"`
Error ErrorResponse `json:"error,omitempty"`
}

type IBackrunSender interface {
SendBackrunBundle(
ctx context.Context,
Expand Down
Loading