client

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2023 License: MIT Imports: 13 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 it's own Transaction struct, which you can convert to a go-ethereum transaction using tx.ToNative().

Transactions
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.Transaction)
    go func() {
        if err := client.SubscribeNewTxs(nil, ch); err != nil {
            log.Fatal(err)
        }
    }()

    for tx := range ch {
        handleTransaction(tx)
    }
}
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.Transaction)
    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 Headers (new block headers)
import (
    ...
    fiber "github.com/chainbound/fiber-go"
)

func main() {
    ...

    ch := make(chan *fiber.ExecutionPayloadHeader)

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

    for header := range ch {
        handleHeader(block)        
    }
}
Execution Payloads (new blocks with transactions)
import (
    ...
    fiber "github.com/chainbound/fiber-go"
)

func main() {
    ...

    ch := make(chan *fiber.ExecutionPayload)

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

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

Beacon blocks follow the Consensus specs, with the exception of the ExecutionPayload, which is not included to allow for a smaller payload size. Please use the SubscribeNewExecutionPayloads stream if you need it.

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)
    }
}
Sending Transactions
SendTransaction
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
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
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
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

This section is empty.

Variables

This section is empty.

Functions

func TxToProto

func TxToProto(tx *types.Transaction) (*eth.Transaction, error)

TxToProto converts a go-ethereum transaction to a protobuf transaction.

Types

type Attestation added in v1.6.0

type Attestation struct {
	AggregationBits common.Hash
	Data            *AttestationData
	Signature       common.Hash
}

type AttestationData added in v1.6.0

type AttestationData struct {
	Slot            uint64
	Index           uint64
	BeaconBlockRoot common.Hash
	Source          *Checkpoint
	Target          *Checkpoint
}

type AttesterSlashing added in v1.6.0

type AttesterSlashing struct {
	Attestation1 *IndexedAttestation
	Attestation2 *IndexedAttestation
}

type BeaconBlock added in v1.6.0

type BeaconBlock struct {
	Slot          uint64
	ProposerIndex uint64
	ParentRoot    common.Hash
	StateRoot     common.Hash
	Body          *BeaconBlockBody
}

func ProtoToBeaconBlock added in v1.6.0

func ProtoToBeaconBlock(block *eth.CompactBeaconBlock) *BeaconBlock

type BeaconBlockBody added in v1.6.0

type BeaconBlockBody struct {
	RandaoReveal              common.Hash
	Eth1Data                  *Eth1Data
	Graffiti                  common.Hash
	ProposerSlashingsList     []ProposerSlashing
	AttesterSlashingsList     []AttesterSlashing
	AttestationsList          []Attestation
	DepositsList              []Deposit
	VoluntaryExitsList        []VoluntaryExit
	SyncAggregate             *SyncAggregate
	BlsToExecutionChangesList []ExecutionChange
}

type BeaconBlockHeader added in v1.6.0

type BeaconBlockHeader struct {
	Slot          uint64
	ProposerIndex uint64
	ParentRoot    common.Hash
	StateRoot     common.Hash
	BodyRoot      common.Hash
}

type Checkpoint added in v1.6.0

type Checkpoint struct {
	Epoch uint64
	Root  common.Hash
}

type Client

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

func NewClient

func NewClient(target, apiKey string) *Client

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)

func (*Client) SendRawTransactionSequence added in v1.5.0

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

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)

func (*Client) SubscribeNewBeaconBlocks added in v1.6.0

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

func (*Client) SubscribeNewExecutionPayloadHeaders added in v1.6.0

func (c *Client) SubscribeNewExecutionPayloadHeaders(ch chan<- *ExecutionPayloadHeader) error

func (*Client) SubscribeNewExecutionPayloads added in v1.6.0

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

func (*Client) SubscribeNewTxs

func (c *Client) SubscribeNewTxs(filter *filter.Filter, ch chan<- *Transaction) 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 Deposit added in v1.6.0

type Deposit struct {
	ProofList []common.Hash
	Data      *DepositData
}

type DepositData added in v1.6.0

type DepositData struct {
	Pubkey                common.Hash
	WithdrawalCredentials common.Hash
	Amount                uint64
	Signature             common.Hash
}

type Eth1Data added in v1.6.0

type Eth1Data struct {
	DepositRoot  common.Hash
	DepositCount uint64
	BlockHash    common.Hash
}

type ExecutionChange added in v1.6.0

type ExecutionChange struct {
	Message   *ExecutionChangeMessage
	Signature common.Hash
}

type ExecutionChangeMessage added in v1.6.0

type ExecutionChangeMessage struct {
	ValidatorIndex     uint64
	FromBlsPubkey      common.Hash
	ToExecutionAddress common.Hash
}

type ExecutionPayload added in v1.6.0

type ExecutionPayload struct {
	Header       *ExecutionPayloadHeader
	Transactions []*Transaction
}

func ProtoToBlock added in v1.5.0

func ProtoToBlock(proto *eth.ExecutionPayload) *ExecutionPayload

type ExecutionPayloadHeader added in v1.6.0

type ExecutionPayloadHeader struct {
	Number        uint64
	Hash          common.Hash
	ParentHash    common.Hash
	PrevRandao    common.Hash
	StateRoot     common.Hash
	ReceiptRoot   common.Hash
	FeeRecipient  common.Address
	ExtraData     []byte
	GasLimit      uint64
	GasUsed       uint64
	Timestamp     uint64
	LogsBloom     types.Bloom
	BaseFeePerGas *big.Int
}

func ProtoToHeader added in v1.5.0

func ProtoToHeader(proto *eth.ExecutionPayloadHeader) *ExecutionPayloadHeader

type IndexedAttestation added in v1.6.0

type IndexedAttestation struct {
	AttestingIndicesList []uint64
	Data                 *AttestationData
	Signature            common.Hash
}

type ProposerSlashing added in v1.6.0

type ProposerSlashing struct {
	Header1 *SignedBeaconBlockHeader
	Header2 *SignedBeaconBlockHeader
}

type SignedBeaconBlockHeader added in v1.6.0

type SignedBeaconBlockHeader struct {
	Message   *BeaconBlockHeader
	Signature common.Hash
}

type SyncAggregate added in v1.6.0

type SyncAggregate struct {
	SyncCommitteeBits      common.Hash
	SyncCommitteeSignature common.Hash
}

type Transaction added in v1.2.5

type Transaction struct {
	ChainID     uint32
	To          *common.Address
	From        common.Address
	Gas         uint64
	GasPrice    *big.Int
	Hash        common.Hash
	Input       []byte
	Value       *big.Int
	Nonce       uint64
	Type        uint32
	MaxFee      *big.Int
	PriorityFee *big.Int
	V           uint64
	R           []byte
	S           []byte
	AccessList  types.AccessList
}

func ProtoToTx

func ProtoToTx(proto *eth.Transaction) *Transaction

ProtoToTx converts a protobuf transaction to a go-ethereum transaction.

func (*Transaction) ToNative added in v1.2.5

func (tx *Transaction) ToNative() *types.Transaction

type VoluntaryExit added in v1.6.0

type VoluntaryExit struct {
	Message   *VoluntaryExitMessage
	Signature common.Hash
}

type VoluntaryExitMessage added in v1.6.0

type VoluntaryExitMessage struct {
	Epoch          uint64
	ValidatorIndex uint64
}

Directories

Path Synopsis
protobuf
api
eth

Jump to

Keyboard shortcuts

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