client

package module
v1.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 14, 2024 License: MIT Imports: 23 Imported by: 4

README

fiber-go

Go client package for interacting with Fiber Network.

Installation

go get github.com/chainbound/fiber-go

Usage

Connecting
import (
    "context"
    "log"
    "time"

    fiber "github.com/chainbound/fiber-go"
)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }
}
Subscriptions

You can find some examples on how to subscribe below. fiber-go uses the familiar go-ethereum core types where possible, making it easy to integrate with existing applications.

Transactions

Transactions are returned as *fiber.TransactionWithSender which is a wrapper around go-ethereum *types.Transaction plus the sender's address. The sender address is included in the message to avoid having to recompute it from ECDSA signature recovery in the client, which can be slow.

import (
    "context"
    "log"
    "time"

    fiber "github.com/chainbound/fiber-go"
    "github.com/chainbound/fiber-go/filter"
    "github.com/chainbound/fiber-go/protobuf/api"
)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    ch := make(chan *fiber.TransactionWithSender)
    go func() {
        if err := client.SubscribeNewTxs(nil, ch); err != nil {
            log.Fatal(err)
        }
    }()

    for message := range ch {
        handleTransaction(message.Transaction)
    }
}
Filtering

The first argument to SubscribeNewTxs is a filter, which can be nil if you want to get all transactions. A filter can be built with the filter package:

import (
    ...
    "github.com/chainbound/fiber-go/filter"
)

func main() {
    ...

    // Construct filter
    // example 1: all transactions with either of these addresses as the receiver
    f := filter.New(filter.Or(
        filter.To("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
        filter.To("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"),
    ))

    // example 2: all transactions with a value greater than or equal to 1 ETH
    f := filter.New(filter.ValueGte(big.NewInt(1) * big.NewInt(1e18)))

    // example 3: all transactions with a value equal to 1 ETH
    f := filter.New(filter.ValueEq(big.NewInt(1) * big.NewInt(1e18)))

    // example 4: all transactions with a value less than or equal to 1 ETH
    f := filter.New(filter.ValueLte(big.NewInt(1) * big.NewInt(1e18)))

    // example 5: all ERC20 transfers on the 2 tokens below
    f := filter.New(filter.And(
        filter.MethodID("0xa9059cbb"),
        filter.Or(
            filter.To("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            filter.To("0xdAC17F958D2ee523a2206206994597C13D831ec7"),
        ),
    ))

    ch := make(chan *fiber.TransactionWithSender)
    go func() {
        // apply filter
        if err := client.SubscribeNewTxs(f, ch); err != nil {
            log.Fatal(err)
        }
    }()

    ...
}

You can currently filter the following properties

  • To
  • From
  • MethodID
  • Value (greater than, less than, equal to)
Execution Payloads (new blocks with transactions)

Execution payloads are returned as *fiber.Block which is a wrapper around go-ethereum native types such as Header, Transaction and Withdrawal.

import (
    ...
    fiber "github.com/chainbound/fiber-go"
)

func main() {
    ...

    ch := make(chan *fiber.Block)

    go func() {
        if err := client.SubscribeNewExecutionPayloads(ch); err != nil {
            log.Fatal(err)
        }
    }()

    for block := range ch {
        handlePayload(block)
    }
}
Beacon Blocks

Beacon blocks follow the Consensus specs. The returned items are *fiber.BeaconBlock which is a wrapper around go-eth-2 SignedBeaconBlock depending on the hardfork version:

Each *fiber.BeaconBlock contains the DataVersion field which indicates the hardfork version of the beacon block. The returned type will contain either a Bellatrix (3), Capella (4) or Deneb (5) hardfork block depending on the specified DataVersion.

import (
    ...
    fiber "github.com/chainbound/fiber-go"
)

func main() {
    ...

    ch := make(chan *fiber.BeaconBlock)

    go func() {
        if err := client.SubscribeNewBeaconBlocks(ch); err != nil {
            log.Fatal(err)
        }
    }()

    for block := range ch {
        handleBeaconBlock(block)
    }
}
Raw Beacon Blocks

Raw beacon blocks are raw, SSZ-encoded bytes that you can manually decode into SignedBeaconBlocks in your application.

import (
    ...
    fiber "github.com/chainbound/fiber-go"
)

func main() {
    ...

    ch := make(chan []byte)

    go func() {
        if err := client.SubscribeNewRawBeaconBlocks(ch); err != nil {
            log.Fatal(err)
        }
    }()

    for block := range ch {
        handleRawBeaconBlock(block)
    }
}
Sending Transactions
SendTransaction

This method supports sending a single go-ethereum *types.Transaction object to the Fiber Network.

import (
    "context"
    "log"
    "math/big"
    "time"

    fiber "github.com/chainbound/fiber-go"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"

)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    // Example transaction
    tx := types.NewTx(&types.DynamicFeeTx{
        Nonce:     nonce,
        To:        common.HexToAddress("0x...."),
        Value:     big.NewInt(100),
        Gas:       21000,
        GasFeeCap: big.NewInt(x),
        GasTipCap: big.NewInt(y),
        Data:      nil,
    })

    pk, _ := crypto.HexToECDSA("PRIVATE_KEY")
    signer := types.NewLondonSigner(common.Big1)

    signed, err := types.SignTx(tx, signer, pk)
    if err != nil {
        log.Fatal(err)
    }

    hash, timestamp, err := client.SendTransaction(ctx, signed)
    if err != nil {
        log.Fatal(err)
    }

    doSomething(hash, timestamp)
}
SendTransactionSequence

This method supports sending a sequence of transactions to the Fiber Network.

import (
    "context"
    "log"
    "math/big"
    "time"

    fiber "github.com/chainbound/fiber-go"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"

)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    // Example transaction
    tx := types.NewTx(&types.DynamicFeeTx{
        Nonce:     nonce,
        To:        common.HexToAddress("0x...."),
        Value:     big.NewInt(100),
        Gas:       21000,
        GasFeeCap: big.NewInt(x),
        GasTipCap: big.NewInt(y),
        Data:      nil,
    })

    pk, _ := crypto.HexToECDSA("PRIVATE_KEY")
    signer := types.NewLondonSigner(common.Big1)

    signed, err := types.SignTx(tx, signer, pk)
    if err != nil {
        log.Fatal(err)
    }

    // type should be *types.Transaction (but signed, e.g. v,r,s fields filled in)
    target := someTargetTransaction

    hashes, timestamp, err := client.SendTransactionSequence(ctx, target, signed)
    if err != nil {
        log.Fatal(err)
    }

    doSomething(hashes, timestamp)
}
SendRawTransaction

This method supports sending a single raw, RLP-encoded transaction to the Fiber Network.

import (
    "context"
    "log"
    "math/big"
    "time"

    fiber "github.com/chainbound/fiber-go"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"

)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    // Example transaction
    tx := types.NewTx(&types.DynamicFeeTx{
        Nonce:     nonce,
        To:        common.HexToAddress("0x...."),
        Value:     big.NewInt(100),
        Gas:       21000,
        GasFeeCap: big.NewInt(x),
        GasTipCap: big.NewInt(y),
        Data:      nil,
    })

    pk, _ := crypto.HexToECDSA("PRIVATE_KEY")
    signer := types.NewLondonSigner(common.Big1)

    signed, err := types.SignTx(tx, signer, pk)
    if err != nil {
        log.Fatal(err)
    }

    bytes, err := signed.MarshalBinary()
    if err != nil {
        log.Fatal(err)
    }

    hash, timestamp, err := client.SendRawTransaction(ctx, bytes)
    if err != nil {
        log.Fatal(err)
    }

    doSomething(hash, timestamp)
}
SendRawTransactionSequence

This method supports sending a sequence of raw, RLP-encoded transactions to the Fiber Network.

import (
    "context"
    "log"
    "math/big"
    "time"

    fiber "github.com/chainbound/fiber-go"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"

)

func main() {
    endpoint := "fiber.example.io"
    apiKey := "YOUR_API_KEY"
    client := fiber.NewClient(endpoint, apiKey)
    defer client.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    // Example transaction
    tx := types.NewTx(&types.DynamicFeeTx{
        Nonce:     nonce,
        To:        common.HexToAddress("0x...."),
        Value:     big.NewInt(100),
        Gas:       21000,
        GasFeeCap: big.NewInt(x),
        GasTipCap: big.NewInt(y),
        Data:      nil,
    })

    pk, _ := crypto.HexToECDSA("PRIVATE_KEY")
    signer := types.NewLondonSigner(common.Big1)

    signed, err := types.SignTx(tx, signer, pk)
    if err != nil {
        log.Fatal(err)
    }

    bytes, err := signed.MarshalBinary()
    if err != nil {
        log.Fatal(err)
    }

    // Type should be []byte
    targetTransaction := someTargetTransaction

    hashes, timestamp, err := client.SendRawTransactionSequence(ctx, targetTransaction, bytes)
    if err != nil {
        log.Fatal(err)
    }

    doSomething(hashes, timestamp)
}

Documentation

Overview

package client is responsible for easily interacting with the protobuf API in Go. It contains wrappers for all the rpc methods that accept standard go-ethereum objects.

Index

Constants

View Source
const DataVersionBellatrix uint32 = 3
View Source
const DataVersionCapella uint32 = 4
View Source
const DataVersionDeneb uint32 = 5
View Source
const Name = "gzip"

Name is the name registered for the gzip compressor.

View Source
const Version string = "fiber-go/1.9.1"

Client version string that is appended to each stream request.

Variables

This section is empty.

Functions

func SetLevel added in v1.8.2

func SetLevel(level int) error

SetLevel updates the registered gzip compressor to use the compression level specified (gzip.HuffmanOnly is not supported). NOTE: this function must only be called during initialization time (i.e. in an init() function), and is not thread-safe.

The error returned will be nil if the specified level is valid.

Types

type Block added in v1.5.0

type Block struct {
	Hash         common.Hash
	Header       *types.Header
	Transactions []*types.Transaction
	Withdrawals  []*types.Withdrawal
}

Helper type that wraps go-ethereum core primitives for an Ethereum block, such as Header, Transactions and Withdrawals.

func DecodeBellatrixExecutionPayload added in v1.9.0

func DecodeBellatrixExecutionPayload(input *api.ExecutionPayloadMsg) (*Block, error)

func DecodeCapellaExecutionPayload added in v1.9.0

func DecodeCapellaExecutionPayload(input *api.ExecutionPayloadMsg) (*Block, error)

func DecodeDenebExecutionPayload added in v1.9.0

func DecodeDenebExecutionPayload(input *api.ExecutionPayloadMsg) (*Block, error)

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(target, apiKey string) *Client

func NewClientWithConfig added in v1.8.2

func NewClientWithConfig(target, apiKey string, config *ClientConfig) *Client

NewClientWithConfig creates a new client with the given config.

func (*Client) Close

func (c *Client) Close() error

Close closes all the streams and then the underlying connection. IMPORTANT: you should call this to ensure correct API accounting.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connects sets up the gRPC channel and creates the stub. It blocks until connected or the given context expires. Always use a context with timeout.

func (*Client) SendRawTransaction

func (c *Client) SendRawTransaction(ctx context.Context, rawTx []byte) (string, int64, error)

SendRawTransaction sends the RLP-encoded transaction to Fibernet and returns the hash and a timestamp (us).

func (*Client) SendRawTransactionSequence added in v1.5.0

func (c *Client) SendRawTransactionSequence(ctx context.Context, rawTransactions ...[]byte) ([]string, int64, error)

SendRawTransactionSequence sends a sequence of RLP-encoded transactions to Fibernet and returns the hashes and a timestamp (us).

func (*Client) SendTransaction

func (c *Client) SendTransaction(ctx context.Context, tx *types.Transaction) (string, int64, error)

SendTransaction sends the (signed) transaction to Fibernet and returns the hash and a timestamp (us). It blocks until the transaction was sent.

func (*Client) SendTransactionSequence added in v1.5.0

func (c *Client) SendTransactionSequence(ctx context.Context, transactions ...*types.Transaction) ([]string, int64, error)

SendTransactionSequence sends a sequence of transactions to Fibernet and returns the hashes and a timestamp (us).

func (*Client) SubmitBlock added in v1.8.0

func (c *Client) SubmitBlock(ctx context.Context, sszBlock []byte) (uint64, []byte, uint64, error)

SubmitBlock submits an SSZ encoded signed block to Fiber and returns the slot, state root and timestamp (us).

func (*Client) SubscribeNewBeaconBlocks added in v1.6.0

func (c *Client) SubscribeNewBeaconBlocks(ch chan<- *SignedBeaconBlock) error

SubscribeNewBeaconBlocks subscribes to new beacon blocks, and sends blocks on the given channel. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error.

func (*Client) SubscribeNewBlobTxs added in v1.9.1

func (c *Client) SubscribeNewBlobTxs(ch chan<- *TransactionWithSender) error

func (*Client) SubscribeNewExecutionPayloads added in v1.6.0

func (c *Client) SubscribeNewExecutionPayloads(ch chan<- *Block) error

SubscribeNewBlocks subscribes to new execution payloads, and sends blocks on the given channel. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error.

func (*Client) SubscribeNewRawBeaconBlocks added in v1.9.0

func (c *Client) SubscribeNewRawBeaconBlocks(ch chan<- []byte) error

SubscribeNewRawBeaconBlocks subscribes to new SSZ-encoded raw signed beacon blocks, and sends blocks on the given channel. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error.

func (*Client) SubscribeNewRawTxs added in v1.9.0

func (c *Client) SubscribeNewRawTxs(filter *filter.Filter, ch chan<- *RawTransactionWithSender) error

SubscribeNewRawTxs subscribes to new RLP-encoded transaction bytes, and sends transactions on the given channel according to the filter. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error.

func (*Client) SubscribeNewTxs

func (c *Client) SubscribeNewTxs(filter *filter.Filter, ch chan<- *TransactionWithSender) error

SubscribeNewTxs subscribes to new transactions, and sends transactions on the given channel according to the filter. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error.

type ClientConfig added in v1.8.2

type ClientConfig struct {
	// contains filtered or unexported fields
}

func NewConfig added in v1.8.2

func NewConfig() *ClientConfig

NewConfig creates a new config with sensible default values.

func (*ClientConfig) EnableCompression added in v1.8.2

func (c *ClientConfig) EnableCompression() *ClientConfig

func (*ClientConfig) SetConnWindowSize added in v1.8.2

func (c *ClientConfig) SetConnWindowSize(size int32) *ClientConfig

func (*ClientConfig) SetReadBufferSize added in v1.8.2

func (c *ClientConfig) SetReadBufferSize(size int) *ClientConfig

func (*ClientConfig) SetWindowSize added in v1.8.2

func (c *ClientConfig) SetWindowSize(size int32) *ClientConfig

func (*ClientConfig) SetWriteBufferSize added in v1.8.2

func (c *ClientConfig) SetWriteBufferSize(size int) *ClientConfig

type MultiplexClient added in v1.7.3

type MultiplexClient struct {
	// contains filtered or unexported fields
}

func NewMultiplexClient added in v1.7.3

func NewMultiplexClient(targets []string, apiKey string) *MultiplexClient

Returns a new multiplex client with the given targets.

func (*MultiplexClient) Close added in v1.7.3

func (mc *MultiplexClient) Close() error

func (*MultiplexClient) Connect added in v1.7.3

func (mc *MultiplexClient) Connect(ctx context.Context) error

Connects all the underlying clients concurrently. It blocks until the connection succeeds / fails, or the given context expires.

func (*MultiplexClient) SendRawTransaction added in v1.7.3

func (mc *MultiplexClient) SendRawTransaction(ctx context.Context, rawTx []byte) (string, int64, error)

SendRawTransaction sends the RLP encoded, signed transaction on all clients, and returns the first response it receives.

func (*MultiplexClient) SendRawTransactionSequence added in v1.7.3

func (mc *MultiplexClient) SendRawTransactionSequence(ctx context.Context, transactions ...[]byte) ([]string, int64, error)

func (*MultiplexClient) SendTransaction added in v1.7.3

func (mc *MultiplexClient) SendTransaction(ctx context.Context, tx *types.Transaction) (string, int64, error)

SendTransaction sends the (signed) transaction on all clients, and returns the first response it receives.

func (*MultiplexClient) SendTransactionSequence added in v1.7.3

func (mc *MultiplexClient) SendTransactionSequence(ctx context.Context, transactions ...*types.Transaction) ([]string, int64, error)

func (*MultiplexClient) SubscribeNewBeaconBlocks added in v1.7.3

func (mc *MultiplexClient) SubscribeNewBeaconBlocks(ch chan<- *SignedBeaconBlock) error

SubscribeNewBeaconHeaders subscribes to new beacon headers, and sends headers on the given channel. This function blocks and should be called in a goroutine. It multiplexes the subscription across all clients.

func (*MultiplexClient) SubscribeNewExecutionPayloads added in v1.7.3

func (mc *MultiplexClient) SubscribeNewExecutionPayloads(ch chan<- *Block) error

SubscribeNewBeaconHeaders subscribes to new beacon headers, and sends headers on the given channel. This function blocks and should be called in a goroutine. It multiplexes the subscription across all clients.

func (*MultiplexClient) SubscribeNewTxs added in v1.7.3

func (mc *MultiplexClient) SubscribeNewTxs(filter *filter.Filter, ch chan<- *TransactionWithSender) error

SubscribeNewTxs subscribes to new transactions, and sends transactions on the given channel according to the filter. This function blocks and should be called in a goroutine. If there's an error receiving the new message it will close the channel and return the error. It multiplexes the subscription across all clients.

type RawTransactionWithSender added in v1.9.0

type RawTransactionWithSender struct {
	Sender *common.Address
	Rlp    []byte
}

Helper type that wraps a raw, RLP-encoded transaction and its sender.

The sender address is included separately even though it could be calculated via ECDSA recovery from the raw RLP transaction bytes. The reason for this is that the recovery process is CPU-bound and takes time (order of magnitude of ~200 μs)

type SignedBeaconBlock added in v1.9.0

type SignedBeaconBlock struct {
	DataVersion uint32
	Bellatrix   *bellatrix.SignedBeaconBlock
	Capella     *capella.SignedBeaconBlock
	Deneb       *deneb.SignedBeaconBlock
}

Helper type that wraps a signed beacon block from any of the supported hard-forks.

This type will either contain a Bellatrix, Capella, or Deneb signed beacon block.

DataVersion is used to indicate which type of payload is contained in the struct: 3: Bellatrix, 4: Capella, 5: Deneb

func (*SignedBeaconBlock) BlockHash added in v1.9.0

func (bb *SignedBeaconBlock) BlockHash() []byte

func (*SignedBeaconBlock) Slot added in v1.9.0

func (bb *SignedBeaconBlock) Slot() phase0.Slot

func (*SignedBeaconBlock) StateRoot added in v1.9.0

func (bb *SignedBeaconBlock) StateRoot() common.Hash

type TransactionWithSender added in v1.9.0

type TransactionWithSender struct {
	Sender      *common.Address
	Transaction *types.Transaction
}

Helper type that wraps a transaction and its sender.

The sender address is included separately even though it could be calculated via ECDSA recovery from the raw RLP transaction bytes. The reason for this is that the recovery process is CPU-bound and takes time (order of magnitude of ~200 μs)

Directories

Path Synopsis
protobuf
api
eth

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL