klayfw

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2020 License: MIT Imports: 23 Imported by: 0

README

klayfw gopher peb

KlayFramework for Go is a collection of stable and tested tools to use along with official Klaytn packages like github.com/klaytn/klaytn. This is not just a lib of functions, but a very illustrative set of examples of how to interact with Klayton API from Go programming language.

The framework has been used heavily in the klaybook CLI tool, it's an utility for Klaytn BApp deployments using static YAML specs. Or, in other words, a tool for working with Klaytn blockchain programmatically without writing any code.

Installation

$ go get github.com/kompose-app/klayfw

Reference

Working with Keystore
github.com/kompose-app/klayfw/keystore
type KlayKeyStore interface {
    PrivateKey(account common.Address, password string) (key *ecdsa.PrivateKey, ok bool)
    SignerFn(account common.Address, password string) bind.SignerFn
    UnsetKey(account common.Address, password string)
    Accounts() []common.Address
    AddPath(keybase string) error
    RemovePath(keybase string)
    Paths() []string
}

keystore.KlayKeyStore abstracts away all complexity of working with filesytem-based keystore that contains encrypted json files as per Web3 Secret Storage Definition standard. It implements live reload routine, allowing to detect newly placed wallet keys and notify about them. It also implements caching of keys using klayfw.KeyCache, see details later in this document.

Wallet and Client Manager
github.com/kompose-app/klayfw/manager
type KlayManager interface {
    Balance(ctx context.Context, account common.Address) (*klayfw.Peb, error)
    BalanceAt(ctx context.Context, account common.Address, blockNum uint64) (*klayfw.Peb, error)
    PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
    PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
    EstimateGas(ctx context.Context, msg klaytn.CallMsg) (uint64, error)
    SuggestGasPrice(ctx context.Context) (*big.Int, error)
    TransactionByHash(ctx context.Context, txHex string) (*TxInfo, error)
    TransactionReceiptByHash(ctx context.Context, txHex string) (*TxReceipt, error)
    SendTransaction(ctx context.Context, tx *types.Transaction) error

    ChainID() uint64
    GasLimit() uint64

    Nodes() []string
    Close() error
}

manager.KlayManager allows to know balances, nonce, estimate gas and send transactions. But what's more important, it implements client-side load balancing for Klayn client.Client from github.com/klaytn/klaytn/client! Based on experience with Geth, there is a chance that Ken nodes will become unresponsive and may drop anytime, so it will be cool if a series of failed requests could trigger a node switch to fallback option. The balancer implements session affinity when nodes in the pool are healthly.

Solidity Compiler Abstraction
github.com/kompose-app/klayfw/sol

type Contract struct {
    Name            string
    SourcePath      string
    CompilerVersion string
    Address         common.Address

    ABI []byte
    Bin string
}

type Compiler interface {
    SetAllowPaths(paths []string) Compiler
    Compile(prefix, path string, optimize int) (map[string]*Contract, error)
}

sol.Contract model holds everything about Solidity contract. A map of contracts can be obtained by invoking solc using sol.Compiler.Compile, which also accepts params such as prefix of contract tree, count of optimization runs, a set of allowed paths for includes (allows to use relative includes) and delivers cross-platform compatibility between macOS, Linux and even Windows. Yes, thanks to klayfw, klaybook also supports all major desktop platforms out of the box.

Amounts
github.com/kompose-app/klayfw
  • klayfw.Peb type and conversions to KLAY and Ston denominations, also big.Int and decimal.Decimal;
  • klayfw.SplitEqual splits the amount of pebs into n-1 equal amounts and one remainder;
  • klayfw.DecimalToPeb backs interoperability with github.com/shopspring/decimal;
  • klayfw.Ston allows to quickly specify gas prices in human-readable form (e.g. klayfw.Ston(25).ToInt());
  • big.Int ops on pebs: Add, Sub, Div, Mul, etc.
Contract
github.com/kompose-app/klayfw

There are helpers on top of sol.Contract that are basically implementing BoundContract using new types of transactions, because Klaytn's bind.BoundContract is only generates legacy transactions. Also there is an option to pass your own transactFunc that will handle nonces and tx signing key in more efficient ways.

type TransactFunc func(
    opts *bind.TransactOpts,
    contract *common.Address,
    input []byte,
) (*types.Transaction, error)

defaultTransactFn inside BoundContract implements optimistic transactFn that is able to generate TxTypeSmartContractDeploy and TxTypeSmartContractExecution transaction types.

Fee Delegation for Contract
github.com/kompose-app/klayfw
func NewFeeDelegatedTransactFunc(
    chainID int,
    klayClient *client.Client,
    klayFeeClient klayfee.FeeDelegationClient,
) TransactFunc

klayfw.NewFeeDelegatedTransactFunc helps you to create a transactFn for BoundContract that is capable of signing TxTypeFeeDelegatedSmartContractDeploy and TxTypeFeeDelegatedSmartContractExecution, yay! It also sends them to a fee delegation service (compatible with https://klayfee.com) using the provided client.

Key Cache
github.com/kompose-app/klayfw
type KeyCache interface {
    SetPath(account common.Address, path string) bool
    UnsetPath(account common.Address, path string)
    PrivateKey(account common.Address, password string) (key *ecdsa.PrivateKey, ok bool)
    SetPrivateKey(account common.Address, pk *ecdsa.PrivateKey)
    UnsetKey(account common.Address, password string)
    SignerFn(account common.Address, password string) bind.SignerFn
}

klayfw.KeyCache implements a cache (without protected memory, yet) of private keys, so it can be used in tight loops and won't waste 1-5s of your CPU time on decryption each time. It exposes SignerFn method that will return bind.SignerFn with pre-decrypted private key. It also allows to manually invalidate and remove private keys.

Nonce Cache
github.com/kompose-app/klayfw
type NonceCache interface {
    Serialize(account common.Address, fn func() error) error
    Sync(account common.Address, syncFn func() (uint64, error))

    Set(account common.Address, nonce uint64)
    Get(account common.Address) uint64
    Incr(account common.Address) uint64
    Decr(account common.Address) uint64
}

klayfw.NonceCache implements syncing primitives to access account's nonce from different goroutines concurrently, allowing to borrow next nonce, and in case of pre-submission failure put it back, so next routine that tries to get next nonce for the same account could take it instead. Klaytn doesn't allow gaps in nonces, also you need an offline nonce counter for better performance and race condition prevention.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoKeyStore = errors.New("no keystore or file for account")
	ErrKeyDecrypt = errors.New("private key decryption failed")
)
View Source
var ErrNoCode = bind.ErrNoCode

Functions

func NewErrFeeDelegated added in v1.2.1

func NewErrFeeDelegated(receipt *klayfee.Receipt, err error) error

Types

type BoundContract

type BoundContract struct {
	*bind.BoundContract
	// contains filtered or unexported fields
}

func BindContract

func BindContract(client *client.Client, contract *sol.Contract) (*BoundContract, error)

func (*BoundContract) ABI

func (c *BoundContract) ABI() abi.ABI

func (*BoundContract) Address

func (c *BoundContract) Address() common.Address

func (*BoundContract) Client

func (c *BoundContract) Client() *client.Client

func (*BoundContract) DeployContract

func (c *BoundContract) DeployContract(opts *bind.TransactOpts, params ...interface{}) (common.Address, *types.Transaction, error)

DeployContract deploys a contract onto the Ethereum blockchain and binds the deployment address with a Go wrapper.

func (*BoundContract) SetAddress

func (c *BoundContract) SetAddress(address common.Address)

func (*BoundContract) SetClient

func (c *BoundContract) SetClient(client *client.Client)

func (*BoundContract) SetTransact

func (c *BoundContract) SetTransact(fn TransactFunc)

func (*BoundContract) Source

func (c *BoundContract) Source() *sol.Contract

func (*BoundContract) Transact

func (c *BoundContract) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error)

Transact invokes the (paid) contract method with params as input values.

func (*BoundContract) Transfer

func (c *BoundContract) Transfer(opts *bind.TransactOpts) (*types.Transaction, error)

Transfer initiates a plain transaction to move funds to the contract, calling its default method if one is available.

type ErrFeeDelegated added in v1.2.1

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

func (*ErrFeeDelegated) Cause added in v1.2.2

func (e *ErrFeeDelegated) Cause() error

func (*ErrFeeDelegated) Error added in v1.2.1

func (e *ErrFeeDelegated) Error() string

func (*ErrFeeDelegated) Receipt added in v1.2.2

func (e *ErrFeeDelegated) Receipt() *klayfee.Receipt

type KeyCache

type KeyCache interface {
	SetPath(account common.Address, path string) bool
	UnsetPath(account common.Address, path string)
	PrivateKey(account common.Address, password string) (key *ecdsa.PrivateKey, ok bool)
	SetPrivateKey(account common.Address, pk *ecdsa.PrivateKey)
	UnsetKey(account common.Address, password string)
	SignerFn(account common.Address, password string) bind.SignerFn
}

func NewKeyCache

func NewKeyCache() KeyCache

type NonceCache

type NonceCache interface {
	Serialize(account common.Address, fn func() error) error
	Sync(account common.Address, syncFn func() (uint64, error))

	Set(account common.Address, nonce uint64)
	Get(account common.Address) uint64
	Incr(account common.Address) uint64
	Decr(account common.Address) uint64
}

func NewNonceCache

func NewNonceCache() NonceCache

type Peb

type Peb decimal.Decimal

func BigPeb

func BigPeb(p *big.Int) *Peb

func DecimalPeb

func DecimalPeb(d decimal.Decimal) *Peb

func DecimalToPeb

func DecimalToPeb(d decimal.Decimal) *Peb

func Ston

func Ston(ston uint64) *Peb

func StringPeb

func StringPeb(str string) *Peb

func ToPeb

func ToPeb(amount float64) *Peb

ToPeb converts Klay or tokens amount into Peb amount.

func (*Peb) Add

func (p *Peb) Add(amount *Peb) *Peb

Add adds two amounts togKlay and returns a new amount.

func (Peb) Bytes

func (p Peb) Bytes() []byte

func (*Peb) Div

func (p *Peb) Div(m int64) *Peb

func (*Peb) Klay

func (p *Peb) Klay() float64

func (*Peb) Mul

func (p *Peb) Mul(m int64) *Peb

func (*Peb) Scan

func (p *Peb) Scan(v interface{}) error

func (*Peb) SplitEqual

func (p *Peb) SplitEqual(parts int) []*Peb

SplitEqual splits the amount into n-1 equal amounts and one remainder. Example: (1000).SplitEqual(7) yields [142 142 142 142 142 142 148]

func (*Peb) Ston

func (p *Peb) Ston() uint64

Ston is an unsafe way to represent Peb as uint64, used for gas price reporting and should not be used for math.

func (Peb) String

func (p Peb) String() string

func (Peb) StringSton

func (p Peb) StringSton() string

func (*Peb) Sub

func (p *Peb) Sub(amount *Peb) *Peb

Sub substracts two amounts and returns a new amount.

func (*Peb) ToInt

func (p *Peb) ToInt() *big.Int

func (*Peb) Tokens

func (p *Peb) Tokens() float64

type TransactFunc

type TransactFunc func(opts *bind.TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error)

func NewFeeDelegatedTransactFunc

func NewFeeDelegatedTransactFunc(
	chainID int,
	klayClient *client.Client,
	klayFeeClient klayfee.FeeDelegationClient,
	dryRun bool,
) TransactFunc

type Uniquify

type Uniquify interface {
	// Call executes only one callable with same id at a time.
	// Multilpe asynchronous calls with same id will be executed sequentally.
	Call(id string, callable func() error) error
}

Uniquify is a type of advanced mutex. It allows to create named resource locks.

func NewUniquify

func NewUniquify() Uniquify

NewUniquify returns a new thread-safe uniquify object.

Directories

Path Synopsis
Package sol provides a convenient interface for calling the 'solc' Solidity Compiler from Go.
Package sol provides a convenient interface for calling the 'solc' Solidity Compiler from Go.

Jump to

Keyboard shortcuts

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