crosschain

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2023 License: Apache-2.0 Imports: 7 Imported by: 0

README

Crosschain

Go Reference Coverage Status

A Go library to interact with multiple blockchains.

Crosschain main design principle is to isolate network Client, Signer and tx Builder. This way you can build applications or micro services using just what you need and with the convenience of a unified interface.

Complete Example

See examples/transfer/main.go

Or run:

go run ./examples/transfer/main.go

Features

Blockchains
  • Bitcoin
  • Bitcoin derived: Bitcoin Cash, Dogecoin
  • Ethereum
  • EVMs: Polygon, Binance Smart Chain, ...
  • Solana
  • Cosmos
  • Cosmos derived: Terra, Injective, XPLA, ...
  • Polkadot
  • Aptos
  • Sui
Assets
  • Native assets
  • Tokens
  • NFTs
  • Liquidity pools
Operations
  • Balances (native asset, tokens)
  • Transfers (native transfers, token transfers)
  • Wraps/unwraps: ETH, SOL, ...
  • Swaps
  • Crosschain transfers (via bridge): Wormhole
  • Tasks (generic smart contract calls, single tx): EVM
  • Pipelines (generic smart contract calls, multiple tx): EVM

Contribute

We welcome contribution, whether in form of bug fixed, documentation, new chains, new functionality.

Just open an issue to discuss what you'd like to contribute and then submit a PR.

Disclaimer. This alpha software has been open sourced. All software and code are provided “as is,” without any warranty of any kind, and should be used at your own risk.

Documentation

Overview

Package crosschain is a Go library to interact with multiple blockchains.

Crosschain main design principle is to isolate network Client, Signer and tx Builder. This way you can build applications or micro services using just what you need and with the convenience of a unified interface.

Index

Constants

View Source
const (
	AssetTypeNative = AssetType("native")
	AssetTypeToken  = AssetType("token")
	AssetTypeTask   = AssetType("task")
)

List of supported AssetType

View Source
const (
	ChainTypeUnknown = ChainType("unknown")
	ChainTypeUTXO    = ChainType("utxo")
	ChainTypeAccount = ChainType("account")
)

List of supported ChainType

View Source
const (
	// UTXO
	BCH  = NativeAsset("BCH")  // Bitcoin Cash
	BTC  = NativeAsset("BTC")  // Bitcoin
	DOGE = NativeAsset("DOGE") // Dogecoin
	LTC  = NativeAsset("LTC")  // Litecoin

	// Account-based
	ACA       = NativeAsset("ACA")       // Acala
	APTOS     = NativeAsset("APTOS")     // APTOS
	ArbETH    = NativeAsset("ArbETH")    // Arbitrum
	ATOM      = NativeAsset("ATOM")      // Cosmos
	AurETH    = NativeAsset("AurETH")    // Aurora
	AVAX      = NativeAsset("AVAX")      // Avalanche
	BNB       = NativeAsset("BNB")       // Binance Coin
	CELO      = NativeAsset("CELO")      // Celo
	CHZ       = NativeAsset("CHZ")       // Chiliz
	ETC       = NativeAsset("ETC")       // Ethereum Classic
	ETH       = NativeAsset("ETH")       // Ethereum
	ETHW      = NativeAsset("ETHW")      // Ethereum PoW
	FTM       = NativeAsset("FTM")       // Fantom
	INJ       = NativeAsset("INJ")       // Injective
	LUNA      = NativeAsset("LUNA")      // Terra V2
	LUNC      = NativeAsset("LUNC")      // Terra Classic
	KAR       = NativeAsset("KAR")       // Karura
	KLAY      = NativeAsset("KLAY")      // Klaytn
	XDC       = NativeAsset("XDC")       // XinFin
	MATIC     = NativeAsset("MATIC")     // Polygon
	OAS       = NativeAsset("OAS")       // Oasys (not Oasis!)
	OasisROSE = NativeAsset("OasisROSE") // Rose (Oasis = main chain)
	OptETH    = NativeAsset("OptETH")    // Optimism
	ROSE      = NativeAsset("ROSE")      // Rose (Oasis Emerald parachain)
	SOL       = NativeAsset("SOL")       // Solana
	XPLA      = NativeAsset("XPLA")      // XPLA
)

List of supported NativeAsset

View Source
const (
	DriverAptos       = Driver("aptos")
	DriverBitcoin     = Driver("bitcoin")
	DriverCosmos      = Driver("cosmos")
	DriverCosmosEvmos = Driver("evmos")
	DriverEVM         = Driver("evm")
	DriverEVMLegacy   = Driver("evm-legacy")
	DriverSolana      = Driver("solana")
)

List of supported Driver

View Source
const FLOAT_PRECISION = 6

Variables

Functions

This section is empty.

Types

type Address

type Address string

Address is an address on the blockchain, either sender or recipient

type AddressBuilder

type AddressBuilder interface {
	GetAddressFromPublicKey(publicKeyBytes []byte) (Address, error)
	GetAllPossibleAddressesFromPublicKey(publicKeyBytes []byte) ([]PossibleAddress, error)
}

AddressBuilder is the interface for building addresses

type AddressType

type AddressType string

AddressType represents the type of an address, for discovery purposes

const (
	AddressTypeSegwit    AddressType = AddressType("Segwit")
	AddressTypeP2SH      AddressType = AddressType("P2SH")
	AddressTypeP2PKH     AddressType = AddressType("P2PKH")
	AddressTypeP2WPKH    AddressType = AddressType("P2WPKH")
	AddressTypeP2TR      AddressType = AddressType("P2TR")
	AddressTypeETHKeccak AddressType = AddressType("ETHKeccak")
	AddressTypeDefault   AddressType = AddressType("Default")
)

List of known AddressType

type AllowEntry added in v0.3.0

type AllowEntry struct {
	Src AssetID
	Dst AssetID
}

type AmountBlockchain

type AmountBlockchain big.Int

AmountBlockchain is a big integer amount as blockchain expects it for tx.

func NewAmountBlockchainFromStr added in v0.2.0

func NewAmountBlockchainFromStr(str string) AmountBlockchain

NewAmountBlockchainFromStr creates a new AmountBlockchain from a string

func NewAmountBlockchainFromUint64

func NewAmountBlockchainFromUint64(u64 uint64) AmountBlockchain

NewAmountBlockchainFromUint64 creates a new AmountBlockchain from a uint64

func NewAmountBlockchainToMaskFloat64 added in v0.3.0

func NewAmountBlockchainToMaskFloat64(f64 float64) AmountBlockchain

NewAmountBlockchainToMaskFloat64 creates a new AmountBlockchain as a float64 times 10^FLOAT_PRECISION

func (*AmountBlockchain) Add added in v0.3.0

Use the underlying big.Int.Add()

func (*AmountBlockchain) Cmp added in v0.3.0

func (amount *AmountBlockchain) Cmp(other *AmountBlockchain) int

Use the underlying big.Int.Cmp()

func (*AmountBlockchain) Div added in v0.3.0

Use the underlying big.Int.Div()

func (AmountBlockchain) Int added in v0.3.0

func (amount AmountBlockchain) Int() *big.Int

Int converts an AmountBlockchain into *bit.Int

func (*AmountBlockchain) MarshalJSON added in v0.3.0

func (b *AmountBlockchain) MarshalJSON() ([]byte, error)

func (*AmountBlockchain) Mul added in v0.3.0

Use the underlying big.Int.Mul()

func (AmountBlockchain) String

func (amount AmountBlockchain) String() string

func (*AmountBlockchain) Sub added in v0.3.0

Use the underlying big.Int.Sub()

func (*AmountBlockchain) ToHuman added in v0.3.0

func (amount *AmountBlockchain) ToHuman(decimals int32) AmountHumanReadable

func (AmountBlockchain) Uint64

func (amount AmountBlockchain) Uint64() uint64

Uint64 converts an AmountBlockchain into uint64

func (*AmountBlockchain) UnmarshalJSON added in v0.3.0

func (b *AmountBlockchain) UnmarshalJSON(p []byte) error

func (AmountBlockchain) UnmaskFloat64 added in v0.3.0

func (amount AmountBlockchain) UnmaskFloat64() float64

UnmaskFloat64 converts an AmountBlockchain into float64 given the number of decimals

type AmountHumanReadable

type AmountHumanReadable decimal.Decimal

AmountHumanReadable is a decimal amount as a human expects it for readability.

func (AmountHumanReadable) String

func (amount AmountHumanReadable) String() string

func (AmountHumanReadable) ToBlockchain added in v0.3.0

func (amount AmountHumanReadable) ToBlockchain(decimals int32) AmountBlockchain

type Asset

type Asset string

Asset is an asset on a blockchain. It can be a token or native asset.

func (Asset) AssetType

func (asset Asset) AssetType() AssetType

AssetType returns the type of an Asset

type AssetConfig

type AssetConfig struct {
	// 	[[silochain.beta.chains]]
	//     asset = "eth"
	//     net = "mainnet"
	//     url = "http://7.125.36.22:8089"
	//
	//   [[silochain.beta.chains]]
	//     asset = "usdc"
	//     chain = "eth"
	//     net = "mainnet"
	//     contract = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
	//     decimals = 6
	Asset                string  `yaml:"asset"`
	Driver               string  `yaml:"driver"`
	Net                  string  `yaml:"net"`
	URL                  string  `yaml:"url"`
	FcdURL               string  `yaml:"fcd_url"`
	Auth                 string  `yaml:"auth"`
	Provider             string  `yaml:"provider"`
	ChainID              int64   `yaml:"chain_id"`
	ChainIDStr           string  `yaml:"chain_id_str"`
	ChainName            string  `yaml:"chain_name"`
	ChainPrefix          string  `yaml:"chain_prefix"`
	ChainCoin            string  `yaml:"chain_coin"`
	ChainCoinHDPath      uint32  `yaml:"chain_coin_hd_path"`
	ChainGasPriceDefault float64 `yaml:"chain_gas_price_default"`
	ChainGasMultiplier   float64 `yaml:"chain_gas_multiplier"`
	ExplorerURL          string  `yaml:"explorer_url"`
	Decimals             int32   `yaml:"decimals"`
	Name                 string  `yaml:"name"`
	IndexerUrl           string  `yaml:"indexer_url"`
	IndexerType          string  `yaml:"indexer_type"`

	// Tokens
	Chain    string `yaml:"chain"`
	Contract string `yaml:"contract"`

	// Internal
	AuthSecret  string      `yaml:"-"`
	Type        AssetType   `yaml:"-"`
	NativeAsset NativeAsset `yaml:"-"`
}

AssetConfig is the model used to represent an asset read from config file or db

type AssetID

type AssetID string

AssetID is an internal identifier for each asset Examples: ETH, USDC, USDC.SOL - see tests for details

func GetAssetIDFromAsset

func GetAssetIDFromAsset(asset string, nativeAsset string) AssetID

GetAssetIDFromAsset return the canonical AssetID given two input strings asset, nativeAsset. Input can come from user input. Examples: - GetAssetIDFromAsset("USDC", "") -> "USDC.ETH" - GetAssetIDFromAsset("USDC", "ETH") -> "USDC.ETH" - GetAssetIDFromAsset("USDC", "SOL") -> "USDC.SOL" - GetAssetIDFromAsset("USDC.SOL", "") -> "USDC.SOL" See tests for more examples.

type AssetType

type AssetType string

AssetType is the type of an asset, either native or token

type ChainType

type ChainType string

ChainType is the type of a chain

type Client

type Client interface {
	FetchTxInput(ctx context.Context, from Address, to Address) (TxInput, error)
	FetchTxInfo(ctx context.Context, txHash TxHash) (TxInfo, error)
	SubmitTx(ctx context.Context, tx Tx) error
}

Client is a client that can fetch data and submit tx to a public blockchain

type ClientBalance added in v0.2.0

type ClientBalance interface {
	// Fetch the balance of the asset that this client is configured for
	FetchBalance(ctx context.Context, address Address) (AmountBlockchain, error)
	FetchNativeBalance(ctx context.Context, address Address) (AmountBlockchain, error)
}

ClientBalance is a specific Client that can fetch balances

type ClientError added in v0.3.0

type ClientError string
const NetworkError ClientError = "NetworkError"

A network error occured -- there may be nothing wrong with the transaction

const NoBalance ClientError = "NoBalance"

A transaction terminally failed due to no balance

const NoBalanceForGas ClientError = "NoBalanceForGas"

A transaction terminally failed due to no balance after accounting for gas cost

const TransactionExists ClientError = "TransactionExists"

A transaction failed to submit because it already exists

const TransactionFailure ClientError = "TransactionFailure"

A transaction terminally failed due to another reason

const UnknownError ClientError = "UnknownError"

No outcome for this error known

type Config

type Config struct {
	Chains       []*NativeAssetConfig `yaml:"chains"`
	Tokens       []*TokenAssetConfig  `yaml:"tokens"`
	AllPipelines []*PipelineConfig    `yaml:"pipelines"`
	AllTasks     []*TaskConfig        `yaml:"tasks"`
	AllAssets    []ITask              `yaml:"-"`
}

Config is the full config containing all Assets

type ContractAddress

type ContractAddress Address

ContractAddress is a smart contract address

type Driver added in v0.3.0

type Driver string

Driver is the type of a chain

type EstimateGasFunc added in v0.3.0

type EstimateGasFunc func(native NativeAsset) (AmountBlockchain, error)

type FullClient added in v0.3.0

type FullClient interface {
	Client
	ClientBalance
}

type FullClientWithGas added in v0.3.0

type FullClientWithGas interface {
	Client
	ClientBalance
	GasEstimator
}

type GasEstimator

type GasEstimator interface {
	EstimateGas(ctx context.Context) (AmountBlockchain, error)
	RegisterEstimateGasCallback(fn EstimateGasFunc)
}

GasEstimator is a specific Client that can estimate gas - not implemented yet

type ITask added in v0.3.0

type ITask interface {
	ID() AssetID
	GetDriver() string
	GetAssetConfig() *AssetConfig
	GetNativeAsset() *NativeAssetConfig
	GetTask() *TaskConfig
}

type NativeAsset

type NativeAsset Asset

NativeAsset is an asset on a blockchain used to pay gas fees. In Crosschain, for simplicity, a NativeAsset represents a chain.

func (NativeAsset) ChainType

func (native NativeAsset) ChainType() ChainType

ChainType returns the type of a chain, represented as its NativeAsset

type NativeAssetConfig added in v0.3.0

type NativeAssetConfig = AssetConfig

func (NativeAssetConfig) GetAssetConfig added in v0.3.0

func (asset NativeAssetConfig) GetAssetConfig() *AssetConfig

func (NativeAssetConfig) GetDriver added in v0.3.0

func (asset NativeAssetConfig) GetDriver() string

func (NativeAssetConfig) GetNativeAsset added in v0.3.0

func (asset NativeAssetConfig) GetNativeAsset() *NativeAssetConfig

func (NativeAssetConfig) GetTask added in v0.3.0

func (asset NativeAssetConfig) GetTask() *TaskConfig

func (*NativeAssetConfig) ID added in v0.3.0

func (asset *NativeAssetConfig) ID() AssetID

func (NativeAssetConfig) String added in v0.3.0

func (c NativeAssetConfig) String() string

type PipelineConfig added in v0.3.0

type PipelineConfig struct {
	ID    string   `yaml:"name"`
	Allow []string `yaml:"allow"`
	Tasks []string `yaml:"tasks"`

	// internal
	AllowList []*AllowEntry `yaml:"-"`
}

PipelineConfig is the model used to represent a pipeline (list of tasks) read from config file or db

func (PipelineConfig) String added in v0.3.0

func (p PipelineConfig) String() string

type PossibleAddress

type PossibleAddress struct {
	Address Address
	Type    AddressType
}

PossibleAddress is a pair of (Address, AddressType) used to derive all possible addresses from a public key

type PrivateKey

type PrivateKey []byte

PrivateKey is a private key or reference to private key

type PublicKey added in v0.3.0

type PublicKey []byte

PublicKey is a public key

type Signer

type Signer interface {
	ImportPrivateKey(privateKey string) (PrivateKey, error)
	Sign(privateKey PrivateKey, data TxDataToSign) (TxSignature, error)
}

Signer is signer that can sign tx

type Task added in v0.3.0

type Task string

Task represents a tx, e.g. smart contract function call, on a blockchain.

type TaskConfig added in v0.3.0

type TaskConfig struct {
	Name  string   `yaml:"name"`
	Code  string   `yaml:"code"`
	Chain string   `yaml:"chain"`
	Allow []string `yaml:"allow"`
	// Contract   string                `yaml:"contract"`
	Operations []TaskConfigOperation `yaml:"operations"`

	// internal
	AllowList []*AllowEntry `yaml:"-"`
	SrcAsset  ITask         `yaml:"-"`
	DstAsset  ITask         `yaml:"-"`
}

TaskConfig is the model used to represent a task read from config file or db

func (TaskConfig) GetAsset added in v0.3.0

func (task TaskConfig) GetAsset() string

func (TaskConfig) GetAssetConfig added in v0.3.0

func (task TaskConfig) GetAssetConfig() *AssetConfig

func (TaskConfig) GetDriver added in v0.3.0

func (task TaskConfig) GetDriver() string

func (TaskConfig) GetNativeAsset added in v0.3.0

func (task TaskConfig) GetNativeAsset() *NativeAssetConfig

func (TaskConfig) GetTask added in v0.3.0

func (task TaskConfig) GetTask() *TaskConfig

func (*TaskConfig) ID added in v0.3.0

func (task *TaskConfig) ID() AssetID

func (TaskConfig) String added in v0.3.0

func (task TaskConfig) String() string

type TaskConfigOperation added in v0.3.0

type TaskConfigOperation struct {
	Function  string                     `yaml:"function"`
	Signature string                     `yaml:"signature"`
	Contract  string                     `yaml:"contract"`
	Payable   bool                       `yaml:"payable"`
	Params    []TaskConfigOperationParam `yaml:"params"`
}

type TaskConfigOperationParam added in v0.3.0

type TaskConfigOperationParam struct {
	Name     string                             `yaml:"name"`
	Type     string                             `yaml:"type"`
	Bind     string                             `yaml:"bind"`
	Defaults []TaskConfigOperationParamDefaults `yaml:"defaults"`
}

type TaskConfigOperationParamDefaults added in v0.3.0

type TaskConfigOperationParamDefaults struct {
	Match string `yaml:"match"`
	Value string `yaml:"value"`
}

type TokenAssetConfig added in v0.3.0

type TokenAssetConfig struct {
	Asset    string    `yaml:"asset"`
	Chain    string    `yaml:"chain"`
	Net      string    `yaml:"net"`
	Decimals int32     `yaml:"decimals"`
	Contract string    `yaml:"contract"`
	Type     AssetType `yaml:"type"`

	AssetConfig       `yaml:"-"`
	NativeAssetConfig *NativeAssetConfig `yaml:"-"`
}

func (TokenAssetConfig) GetAssetConfig added in v0.3.0

func (asset TokenAssetConfig) GetAssetConfig() *AssetConfig

func (TokenAssetConfig) GetDriver added in v0.3.0

func (asset TokenAssetConfig) GetDriver() string

func (TokenAssetConfig) GetNativeAsset added in v0.3.0

func (asset TokenAssetConfig) GetNativeAsset() *NativeAssetConfig

func (TokenAssetConfig) GetTask added in v0.3.0

func (asset TokenAssetConfig) GetTask() *TaskConfig

func (*TokenAssetConfig) ID added in v0.3.0

func (asset *TokenAssetConfig) ID() AssetID

func (TokenAssetConfig) String added in v0.3.0

func (c TokenAssetConfig) String() string

type Tx

type Tx interface {
	Hash() TxHash
	Sighashes() ([]TxDataToSign, error)
	AddSignatures(...TxSignature) error
	Serialize() ([]byte, error)
}

Tx is a transaction

type TxBuilder

type TxBuilder interface {
	NewTransfer(from Address, to Address, amount AmountBlockchain, input TxInput) (Tx, error)
}

TxBuilder is a Builder that can transfer assets

type TxDataToSign

type TxDataToSign []byte

TxDataToSign is the payload that Signer needs to sign, when "signing a tx". It's sometimes called a sighash.

func (TxDataToSign) String added in v0.3.0

func (data TxDataToSign) String() string

type TxHash

type TxHash string

TxHash is a tx hash or id

type TxInfo

type TxInfo struct {
	BlockHash       string
	TxID            string
	ExplorerURL     string
	From            Address
	To              Address
	ToAlt           Address
	ContractAddress ContractAddress
	Amount          AmountBlockchain
	Fee             AmountBlockchain
	BlockIndex      int64
	BlockTime       int64
	Confirmations   int64
	Status          TxStatus
	Sources         []*TxInfoEndpoint
	Destinations    []*TxInfoEndpoint
	Time            int64
	TimeReceived    int64
}

TxInfo is a unified view of common tx info across multiple blockchains. Use it as an example to build your own.

type TxInfoEndpoint added in v0.3.0

type TxInfoEndpoint struct {
	Address         Address
	ContractAddress ContractAddress
	Amount          AmountBlockchain
	NativeAsset     NativeAsset
	Asset           Asset
	AssetConfig     *AssetConfig
}

TxInfoEndpoint is a unified view of an endpoint (source or destination) in a TxInfo.

type TxInput

type TxInput interface {
}

TxInput is input data to a tx. Depending on the blockchain it can include nonce, recent block hash, account id, ...

type TxInputEnvelope added in v0.3.0

type TxInputEnvelope struct {
	Type Driver `json:"type"`
}

func NewTxInputEnvelope added in v0.3.0

func NewTxInputEnvelope(envType Driver) *TxInputEnvelope

type TxInputWithPublicKey added in v0.3.0

type TxInputWithPublicKey interface {
	TxInput
	SetPublicKey(PublicKey) error
	SetPublicKeyFromStr(string) error
}

TxInputWithPublicKey is input data to a tx for chains that need to explicitly set the public key, e.g. Cosmos

type TxSignature

type TxSignature []byte

TxSignature is a tx signature

func NewTxSignatures added in v0.3.0

func NewTxSignatures(data [][]byte) []TxSignature

NewTxSignatures creates a new array of TxSignature, useful to cast [][]byte into []TxSignature

type TxStatus added in v0.2.0

type TxStatus uint8

TxStatus is the status of a tx on chain, currently success or failure.

const (
	TxStatusSuccess TxStatus = 0
	TxStatusFailure TxStatus = 1
)

TxStatus values

type TxTokenBuilder

type TxTokenBuilder interface {
	TxBuilder
	NewNativeTransfer(from Address, to Address, amount AmountBlockchain, input TxInput) (Tx, error)
	NewTokenTransfer(from Address, to Address, amount AmountBlockchain, input TxInput) (Tx, error)
}

TxTokenBuilder is a Builder that can transfer token assets, in addition to native assets

type TxXTransferBuilder added in v0.3.0

type TxXTransferBuilder interface {
	TxBuilder
	NewTask(from Address, to Address, amount AmountBlockchain, input TxInput) (Tx, error)
}

TxXTransferBuilder is a Builder that can mutate an asset into another asset

Directories

Path Synopsis
chain
evm
sui
examples

Jump to

Keyboard shortcuts

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