crosschain

package module
v0.0.0-...-2e449e2 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: Apache-2.0, MIT Imports: 9 Imported by: 0

README ¶

Crosschain

Go Reference Coverage Status

A Go library to interact with multiple blockchains. This library is used by the Cordial Treasury custody product to interact with various blockchains securely. Cordial Treasury will be able to support any chain supported in this library.

Crosschain's main design principle is to isolate functionality into separate Client, Signer and TxBuilder interfaces.
In addition to providing unified interfaces, it allows blockchains to be safely used in secure contexts.

Example usage

First install the xc utility which will quickly demonstrate usage of the library.

go install -v ./cmd/xc/...

By default, xc, will using Cordial System's connector API to connect to blockchains. You will need an API key for this to work. Otherwise, you can easily override and supply your own standard RPC url for the target chain.

Manually interact with blockchains

Usage:
  xc [command]

Available Commands:
  address     Derive an address from the PRIVATE_KEY environment variable.
  balance     Check balance of an asset.  Reported as big integer, not accounting for any decimals.
  chains      List information on all supported chains.
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  staking     Staking commands
  transfer    Create and broadcast a new transaction transferring funds. The amount should be a decimal amount.
  tx-info     Check an existing transaction on chain.
  tx-input    Check inputs for a new transaction.

Flags:
      --api-key string    Api key to use for client (may set CORDIAL_API_KEY).
      --chain string      Chain to use. Required.
      --config string     Path to treasury.toml configuration file.
  -h, --help              help for xc
      --not-mainnet       Do not use mainnets, instead use a test or dev network.
      --provider string   Provider to use for chain client.  Only valid for BTC chains.
      --rpc string        RPC url to use. Optional.
  -v, --verbose count     Set verbosity.
Generate or import a wallet

Set PRIVATE_KEY env and confirm you address is correct on the target chain you want to use.

# random 32-byte key
export PRIVATE_KEY=$(cat /dev/urandom | head -c 32 | xxd -p -c100)
xc address --chain SOL
Send a transfer
xc transfer <destination-address> 0.1 -v --chain SOL

Add --contract for token transfers.

xc transfer <destination-address> 0.1 -v --chain SOL --contract EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v --decimals 6

Add --rpc to use your own RPC node or use a devnet or testnet network.

xc transfer <destination-address> 0.1 -v --chain SOL --rpc "https://api.devnet.solana.com"
Stake an asset

Stake 0.1 SOL on mainnet.

xc staking stake --amount 0.1 --chain SOL --rpc https://api.mainnet-beta.solana.com --validator he1iusunGwqrNtafDtLdhsUQDFvo13z9sUa36PauBtk
Download a transaction

Transactions are represented in a universal format across different chains.

xc tx-info --chain BTC b5734126a7b9f5a3a94491c7297959b74099c5c88d2f5f34ea3cb432abdf9c5e

Download another transaction from a difference chain.

xc tx-info --chain SOL 2NNSwe5ZCHx1SuYfgqy1pyWxDCfEcge3H4Eak1KyGCctjJictYtkQ4FFRH7CMJHM1W55FnyBmtKrxdZzkkThkjVL
Lookup a balance

Get ether balance (in wei).

xc balance 0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5 --chain ETH

Add --contract to see a token balance.

xc balance 0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5 --chain ETH --contract 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
Lookup transaction input

This looks up all of the necessary inputs needed to serialize a transaction on a given blockchain. The values for the "input" depends on each chain. Normally this is providing account sequences, gas fees, or unspent outputs.

xc tx-input <from-address> --chain ETH
xc tx-input 0x95222290DD7278Aa3Ddd389Cc1E1d165CC4BAfe5 --chain ETH

Features

Blockchains
  • Aptos
  • Bitcoin
  • Bitcoin derived: Bitcoin Cash, Dogecoin
  • Bittensor
  • Cosmos
  • Cosmos derived: Terra, Injective, XPLA, ...
  • Ethereum
  • EVMs: Polygon, Binance Smart Chain, ...
  • Filecoin
  • Polkadot
  • Solana
  • Sui
  • TON
  • Tron
  • XRP
Assets
  • Native assets
  • Tokens
  • Staked assets
  • NFTs
  • Liquidity pools
Operations
  • Balances (native asset, tokens)
  • Transfers (native transfers, token transfers)
  • Transaction reporting
  • Wraps/unwraps: ETH, SOL (partial support)
  • Staking/unstaking
Devnet nodes

You can spin up your own devnet nodes + universal faucet API for testing.

Example on EVM:

# build and run container
cd chain/evm/node && docker build -t devnet-evm .
devnet-evm
docker run --name devnet-evm -p 10000:10000 -p 10001:10001 devnet-evm

Fund some asset onto an address using the faucet:

curl -X POST -d '{"amount": 1234, "address": "0x0000000000000000000000000000000000001234"}' localhost:10001/chains/ETH/assets/ETH

Query the devnet node:

curl localhost:10000 -X POST \
  --data '{"method":"eth_getBalance","params":["0x0000000000000000000000000000000000001234", "latest"],"id":1,"jsonrpc":"2.0"}'

Contribute

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

To add a new chain, we recommend you first study existing implementations in chains/. Normally it's easiest to start with the client methods (reporting a balance), and then incrementally get to building a transaction and broadcasting it.

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

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 (
	K256Keccak = SignatureType("k256-keccak")
	K256Sha256 = SignatureType("k256-sha256")
	Ed255      = SignatureType("ed255")
	Schnorr    = SignatureType("schnorr")
)
View Source
const (
	ACA    = NativeAsset("ACA")    // Acala
	APTOS  = NativeAsset("APTOS")  // APTOS
	ArbETH = NativeAsset("ArbETH") // Arbitrum
	ATOM   = NativeAsset("ATOM")   // Cosmos
	AurETH = NativeAsset("AurETH") // Aurora
	AVAX   = NativeAsset("AVAX")   // Avalanche
	BASE   = NativeAsset("BASE")   // BASE
	BERA   = NativeAsset("BERA")   // Berachain
	BCH    = NativeAsset("BCH")    // Bitcoin Cash
	BNB    = NativeAsset("BNB")    // Binance Coin
	BTC    = NativeAsset("BTC")    // Bitcoin
	CELO   = NativeAsset("CELO")   // Celo
	CHZ    = NativeAsset("CHZ")    // Chiliz
	CHZ2   = NativeAsset("CHZ2")   // Chiliz 2.0
	DOGE   = NativeAsset("DOGE")   // Dogecoin
	DOT    = NativeAsset("DOT")    // Polkadot
	ENJ    = NativeAsset("ENJ")    // Enjin
	ETC    = NativeAsset("ETC")    // Ethereum Classic
	ETH    = NativeAsset("ETH")    // Ethereum
	ETHW   = NativeAsset("ETHW")   // Ethereum PoW
	FTM    = NativeAsset("FTM")    // Fantom
	HASH   = NativeAsset("HASH")   // Provenance
	INJ    = NativeAsset("INJ")    // Injective
	LTC    = NativeAsset("LTC")    // Litecoin
	LUNA   = NativeAsset("LUNA")   // Terra V2
	LUNC   = NativeAsset("LUNC")   // Terra Classic
	KAR    = NativeAsset("KAR")    // Karura
	KLAY   = NativeAsset("KLAY")   // Klaytn
	KSM    = NativeAsset("KSM")    // Kusama
	XDC    = NativeAsset("XDC")    // XinFin
	MATIC  = NativeAsset("MATIC")  // Polygon
	NOBLE  = NativeAsset("NOBLE")  // Noble Chain
	OAS    = NativeAsset("OAS")    // Oasys (not Oasis!)
	OptETH = NativeAsset("OptETH") // Optimism
	EmROSE = NativeAsset("EmROSE") // Rose (Oasis EVM-compat "Emerald" parachain)
	SOL    = NativeAsset("SOL")    // Solana
	SUI    = NativeAsset("SUI")    // SUI
	XPLA   = NativeAsset("XPLA")   // XPLA
	TAO    = NativeAsset("TAO")    // Bittensor
	TIA    = NativeAsset("TIA")    // celestia
	TON    = NativeAsset("TON")    // TON
	TRX    = NativeAsset("TRX")    // TRON
	SEI    = NativeAsset("SEI")    // Sei
	XRP    = NativeAsset("XRP")    // XRP
)

List of supported NativeAsset

View Source
const (
	DriverAptos         = Driver("aptos")
	DriverBitcoin       = Driver("bitcoin")
	DriverBitcoinCash   = Driver("bitcoin-cash")
	DriverBitcoinLegacy = Driver("bitcoin-legacy")
	DriverCosmos        = Driver("cosmos")
	DriverCosmosEvmos   = Driver("evmos")
	DriverEVM           = Driver("evm")
	DriverEVMLegacy     = Driver("evm-legacy")
	DriverSubstrate     = Driver("substrate")
	DriverSolana        = Driver("solana")
	DriverSui           = Driver("sui")
	DriverTron          = Driver("tron")
	DriverTon           = Driver("ton")
	DriverXrp           = Driver("xrp")
	// Crosschain is a client-only driver
	DriverCrosschain = Driver("crosschain")
)

List of supported Driver

View Source
const FLOAT_PRECISION = 6

Variables ¶

View Source
var SupportedStakingProviders = []StakingProvider{
	Native,
	Kiln,
	Figment,
	Twinstake,
}

Functions ¶

func SameTxInputTypes ¶

func SameTxInputTypes[T TxInput](as T, inputs ...TxInput) bool

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 ¶

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 MultiplyByFloat ¶

func MultiplyByFloat(amount AmountBlockchain, multiplier float64) AmountBlockchain

func NewAmountBlockchainFromStr ¶

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 ¶

func NewAmountBlockchainToMaskFloat64(f64 float64) AmountBlockchain

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

func (*AmountBlockchain) Abs ¶

func (amount *AmountBlockchain) Abs() AmountBlockchain

func (*AmountBlockchain) Add ¶

Use the underlying big.Int.Add()

func (AmountBlockchain) ApplyGasPriceMultiplier ¶

func (amount AmountBlockchain) ApplyGasPriceMultiplier(chain *ChainConfig) AmountBlockchain

func (*AmountBlockchain) Cmp ¶

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

Use the underlying big.Int.Cmp()

func (*AmountBlockchain) Div ¶

Use the underlying big.Int.Div()

func (AmountBlockchain) Int ¶

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

Int converts an AmountBlockchain into *bit.Int

func (*AmountBlockchain) IsZero ¶

func (amount *AmountBlockchain) IsZero() bool

func (AmountBlockchain) MarshalJSON ¶

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

func (*AmountBlockchain) Mul ¶

Use the underlying big.Int.Mul()

func (AmountBlockchain) Sign ¶

func (amount AmountBlockchain) Sign() int

func (AmountBlockchain) String ¶

func (amount AmountBlockchain) String() string

func (*AmountBlockchain) Sub ¶

Use the underlying big.Int.Sub()

func (*AmountBlockchain) ToHuman ¶

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

func (AmountBlockchain) Uint64 ¶

func (amount AmountBlockchain) Uint64() uint64

Uint64 converts an AmountBlockchain into uint64

func (*AmountBlockchain) UnmarshalJSON ¶

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

func (AmountBlockchain) UnmaskFloat64 ¶

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 NewAmountHumanReadableFromStr ¶

func NewAmountHumanReadableFromStr(str string) (AmountHumanReadable, error)

NewAmountHumanReadableFromStr creates a new AmountHumanReadable from a string

func (AmountHumanReadable) Decimal ¶

func (amount AmountHumanReadable) Decimal() decimal.Decimal

func (AmountHumanReadable) Div ¶

func (AmountHumanReadable) MarshalJSON ¶

func (b AmountHumanReadable) MarshalJSON() ([]byte, error)

func (AmountHumanReadable) String ¶

func (amount AmountHumanReadable) String() string

func (AmountHumanReadable) ToBlockchain ¶

func (amount AmountHumanReadable) ToBlockchain(decimals int32) AmountBlockchain

func (*AmountHumanReadable) UnmarshalJSON ¶

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

type AssetID ¶

type AssetID string

AssetID is an internal identifier for each asset (legacy/deprecated) Examples: ETH, USDC, USDC.SOL - see tests for details

func GetAssetIDFromAsset ¶

func GetAssetIDFromAsset(asset string, nativeAsset NativeAsset) 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 ChainConfig ¶

type ChainConfig struct {
	// The crosschain symbol of the chain
	Chain NativeAsset `yaml:"chain,omitempty"`
	// The driver to use for the chain
	Driver Driver `yaml:"driver,omitempty"`
	// The network selector, if necessary (e.g. select mainnet, testnet, or devnet for bitcoin chains)
	Net string `yaml:"net,omitempty"`
	// Decimals for the chain's native asset (if it has one).
	Decimals int32 `yaml:"decimals,omitempty"`
	// RPC URL to use
	URL     string          `yaml:"url,omitempty"`
	Clients []*ClientConfig `yaml:"clients,omitempty"`

	// Optional configuration of the Driver.  Some chains support different kinds of RPC.
	Provider string `yaml:"provider,omitempty"`

	// The ChainID of the chain, either in integer or string format
	ChainID    int64  `yaml:"chain_id,omitempty"`
	ChainIDStr string `yaml:"chain_id_str,omitempty"`

	// Human readable name of the chain, e.g. "Bitcoin"
	ChainName string `yaml:"chain_name,omitempty"`

	// Does the chain use a special prefix for it's address?
	// E.g. most cosmos chains do this.
	ChainPrefix string `yaml:"chain_prefix,omitempty"`

	// If the chain has a native asset, and it has an actual contract address, it should be set here.
	// This is also referred to as the "ContractID".
	// E.g.
	// - APTOS has 0x1::aptos_coin::AptosCoin
	// - INJ has inj
	// - HASH has nhash
	// - LUNA has uluna
	ChainCoin string `yaml:"chain_coin,omitempty"`

	// If necessary, specific which asset to use to spend for gas.
	GasCoin string `yaml:"gas_coin,omitempty"`

	// Does the chain rely on an indexer in addition to RPC?  If so, the URL and type
	// may be set here.
	IndexerUrl  string `yaml:"indexer_url,omitempty"`
	IndexerType string `yaml:"indexer_type,omitempty"`
	// Maximun depth to scan for transaction, if there is no index to use (substrate...)
	MaxScanDepth int `yaml:"max_scan_depth,omitempty"`
	// Optional delay inbetween scanning
	ScanDelay time.Duration `yaml:"scan_delay,omitempty"`

	// PollingPeriod string `yaml:"polling_period,omitempty"`
	NoGasFees bool `yaml:"no_gas_fees,omitempty"`
	// Indicate if this chain should not be included.
	Disabled *bool `yaml:"disabled,omitempty"`

	// How many confirmations is considered "final" for this chain?
	ConfirmationsFinal int `yaml:"confirmations_final,omitempty"`

	// Staking configuration
	Staking StakingConfig `yaml:"staking,omitempty"`

	// Optional settings around the gas, if needed.
	ChainGasPriceDefault float64 `yaml:"chain_gas_price_default,omitempty"`
	ChainGasMultiplier   float64 `yaml:"chain_gas_multiplier,omitempty"`
	ChainGasTip          uint64  `yaml:"chain_gas_tip,omitempty"`
	// The max/min prices can be set to provide sanity limits for what a gas price (per gas or per byte) should be.
	// This should be in the blockchain amount.
	ChainMaxGasPrice float64 `yaml:"chain_max_gas_price,omitempty"`
	ChainMinGasPrice float64 `yaml:"chain_min_gas_price,omitempty"`

	// Transfer tax is percentage that the network takes from every transfer .. only used so far for Terra Classic
	ChainTransferTax float64 `yaml:"chain_transfer_tax,omitempty"`

	// Used only for deriving private keys from mnemonic phrases in local testing
	ChainCoinHDPath uint32 `yaml:"chain_coin_hd_path,omitempty"`

	// This contains the derefenced value of "auth", if "auth" is set.
	AuthSecret string `yaml:"-"`
	// Set a secret reference, see config/secret.go.  Used for setting an API key.
	Auth string `yaml:"auth,omitempty"`

	// Additional metadata.  Not Used in crosschain itself, but helpful to enrich API endpoints.
	External External `yaml:"external,omitempty"`

	// Unused deprecated fields
	XAssetDeprecated NativeAsset  `yaml:"asset,omitempty"`
	XExplorerUrls    ExplorerUrls `yaml:"explorer_urls,omitempty"`

	XDti             string `yaml:"dti,omitempty"`
	XCoinGeckoId     string `yaml:"coingecko_id,omitempty"`
	XCoinMarketCapId string `yaml:"coinmarketcap_id,omitempty"`
}

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

func (ChainConfig) GetAllClients ¶

func (asset ChainConfig) GetAllClients() []*ClientConfig

Return list of clients with the "default" client added if it's not already there

func (*ChainConfig) GetAssetSymbol ¶

func (native *ChainConfig) GetAssetSymbol() string

func (*ChainConfig) GetChain ¶

func (asset *ChainConfig) GetChain() *ChainConfig

func (*ChainConfig) GetContract ¶

func (native *ChainConfig) GetContract() string

func (*ChainConfig) GetDecimals ¶

func (asset *ChainConfig) GetDecimals() int32

func (ChainConfig) GetNativeClients ¶

func (asset ChainConfig) GetNativeClients() []*ClientConfig

Return all clients that are not crosschain driver

func (*ChainConfig) ID ¶

func (asset *ChainConfig) ID() AssetID

func (*ChainConfig) IsChain ¶

func (native *ChainConfig) IsChain(contract ContractAddress) bool

func (*ChainConfig) Migrate ¶

func (chain *ChainConfig) Migrate()

func (ChainConfig) String ¶

func (c ChainConfig) String() string

type ClientConfig ¶

type ClientConfig struct {
	Driver   Driver          `yaml:"driver"`
	URL      string          `yaml:"url,omitempty"`
	Auth     string          `yaml:"auth,omitempty"`
	Provider string          `yaml:"provider,omitempty"`
	Network  NetworkSelector `yaml:"network,omitempty"`
}

ClientConfig is the model used to represent a client inside an AssetConfig

type ContractAddress ¶

type ContractAddress Address

ContractAddress is a smart contract address

type Driver ¶

type Driver string

Driver is the type of a chain

func (Driver) PublicKeyFormat ¶

func (driver Driver) PublicKeyFormat() PublicKeyFormat

func (Driver) SignatureAlgorithm ¶

func (driver Driver) SignatureAlgorithm() SignatureType

type ExplorerUrls ¶

type ExplorerUrls struct {
	Tx      string `yaml:"tx"`
	Address string `yaml:"address"`
	Token   string `yaml:"token"`
}

type External ¶

type External struct {
	Dti          string       `yaml:"dti,omitempty"`
	ExplorerUrls ExplorerUrls `yaml:"explorer_urls,omitempty"`

	CoinMarketCap struct {
		// CoinMarketCap's ID for the chain
		ChainId string `yaml:"chain_id,omitempty"`
		// CoinMarketCap's ID for the chain's native asset, also called "UCID"
		AssetId string `yaml:"asset_id,omitempty"`
	} `yaml:"coin_market_cap,omitempty"`
	CoinGecko struct {
		// TODO: is there a chain ID for coingecko?
		ChainId string `yaml:"chain_id,omitempty"`
		// Coingecko's asset ID, if relevant
		AssetId string `yaml:"asset_id,omitempty"`
	} `yaml:"coin_gecko,omitempty"`
}

External ID's used by other vendors for the given chain

type GasFeePriority ¶

type GasFeePriority string
var Aggressive GasFeePriority = "aggressive"
var Low GasFeePriority = "low"
var Market GasFeePriority = "market"
var VeryAggressive GasFeePriority = "very-aggressive"

func NewPriority ¶

func NewPriority(input string) (GasFeePriority, error)

func (GasFeePriority) AsCustom ¶

func (p GasFeePriority) AsCustom() (decimal.Decimal, error)

func (GasFeePriority) GetDefault ¶

func (p GasFeePriority) GetDefault() (decimal.Decimal, error)

func (GasFeePriority) IsEnum ¶

func (p GasFeePriority) IsEnum() bool

type ITask ¶

type ITask interface {
	// unique identifier used within crosschain, typically a combination of asset.chain
	ID() AssetID
	GetChain() *ChainConfig
	// Get associated asset decimals if it exists
	GetDecimals() int32
	// Get associated contract if it exists
	GetContract() string

	// Informational / debugging
	String() string
	// Get asset symbol (e.g. 'USDC') if it exists.  Does not include the chain.  Informational.
	GetAssetSymbol() string
}

type LegacyTxInfo ¶

type LegacyTxInfo struct {
	BlockHash       string                  `json:"block_hash"`
	TxID            string                  `json:"tx_id"`
	From            Address                 `json:"from"`
	To              Address                 `json:"to"`
	ToAlt           Address                 `json:"to_alt,omitempty"`
	ContractAddress ContractAddress         `json:"contract,omitempty"`
	Amount          AmountBlockchain        `json:"amount"`
	Fee             AmountBlockchain        `json:"fee"`
	FeeContract     ContractAddress         `json:"fee_contract,omitempty"`
	BlockIndex      int64                   `json:"block_index,omitempty"`
	BlockTime       int64                   `json:"block_time,omitempty"`
	Confirmations   int64                   `json:"confirmations,omitempty"`
	Status          TxStatus                `json:"status"`
	Sources         []*LegacyTxInfoEndpoint `json:"sources,omitempty"`
	Destinations    []*LegacyTxInfoEndpoint `json:"destinations,omitempty"`
	Time            int64                   `json:"time,omitempty"`
	TimeReceived    int64                   `json:"time_received,omitempty"`
	// If this transaction failed, this is the reason why.
	Error string `json:"error,omitempty"`
	// contains filtered or unexported fields
}

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

func (*LegacyTxInfo) AddDroppedDestination ¶

func (info *LegacyTxInfo) AddDroppedDestination(dest *LegacyTxInfoEndpoint)

func (*LegacyTxInfo) AddStakeEvent ¶

func (info *LegacyTxInfo) AddStakeEvent(ev StakeEvent)

func (*LegacyTxInfo) GetDroppedBtcDestinations ¶

func (info *LegacyTxInfo) GetDroppedBtcDestinations() []*LegacyTxInfoEndpoint

func (*LegacyTxInfo) GetStakeEvents ¶

func (info *LegacyTxInfo) GetStakeEvents() []StakeEvent

type LegacyTxInfoEndpoint ¶

type LegacyTxInfoEndpoint struct {
	Address         Address          `json:"address"`
	ContractAddress ContractAddress  `json:"contract,omitempty"`
	Amount          AmountBlockchain `json:"amount"`
	NativeAsset     NativeAsset      `json:"chain"`
	Asset           string           `json:"asset,omitempty"`
	Memo            string           `json:"memo,omitempty"`

	// Set only when there's a contract ID for native asset (and conflicts with our chosen identifier)
	ContractId ContractAddress `json:"contract_id,omitempty"`
}

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

type NativeAsset ¶

type NativeAsset string

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

func LegacyParseAssetAndNativeAsset ¶

func LegacyParseAssetAndNativeAsset(asset string, nativeAsset string) (string, NativeAsset)

func (NativeAsset) Driver ¶

func (native NativeAsset) Driver() Driver

func (NativeAsset) IsValid ¶

func (native NativeAsset) IsValid() bool

type NetworkSelector ¶

type NetworkSelector string

Network selector is used by crosschain client to select which network of a blockchain to select.

const Mainnets NetworkSelector = ""
const NotMainnets NetworkSelector = "!mainnet"

type PipelineConfig ¶

type PipelineConfig struct {
	Name  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) ID ¶

func (p PipelineConfig) ID() AssetID

func (PipelineConfig) String ¶

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 PublicKeyFormat ¶

type PublicKeyFormat string
var Compressed PublicKeyFormat = "compressed"
var Raw PublicKeyFormat = "raw"
var Uncompressed PublicKeyFormat = "uncompressed"

type SignatureType ¶

type SignatureType string

type StakeEvent ¶

type StakeEvent interface {
	GetValidator() string
}

type StakeTxInput ¶

type StakeTxInput interface {
	TxVariantInput
	Staking()
}

Markers for each type of Variant Tx

type StakingConfig ¶

type StakingConfig struct {
	// the contract used for staking, if relevant
	StakeContract string `yaml:"stake_contract,omitempty"`
	// the contract used for unstaking, if relevant
	UnstakeContract string `yaml:"unstake_contract,omitempty"`
	// Compatible providers for staking
	Providers []StakingProvider `yaml:"providers,omitempty"`
}

func (*StakingConfig) Enabled ¶

func (staking *StakingConfig) Enabled() bool

type StakingProvider ¶

type StakingProvider string
const Figment StakingProvider = "figment"
const Kiln StakingProvider = "kiln"
const Native StakingProvider = "native"
const Twinstake StakingProvider = "twinstake"

func (StakingProvider) Valid ¶

func (stakingProvider StakingProvider) Valid() bool

type Task ¶

type Task string

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

type TaskConfig ¶

type TaskConfig struct {
	Name          string                 `yaml:"name"`
	Code          string                 `yaml:"code"`
	Allow         []string               `yaml:"allow"`
	Chain         string                 `yaml:"chain"`
	DefaultParams map[string]interface{} `yaml:"default_params"`
	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) GetAssetSymbol ¶

func (task *TaskConfig) GetAssetSymbol() string

func (TaskConfig) GetChain ¶

func (task TaskConfig) GetChain() *ChainConfig

func (*TaskConfig) GetContract ¶

func (task *TaskConfig) GetContract() string

func (*TaskConfig) GetDecimals ¶

func (task *TaskConfig) GetDecimals() int32

func (TaskConfig) GetTask ¶

func (task TaskConfig) GetTask() *TaskConfig

func (*TaskConfig) ID ¶

func (task *TaskConfig) ID() AssetID

func (*TaskConfig) IsChain ¶

func (task *TaskConfig) IsChain(contract ContractAddress) bool

func (TaskConfig) String ¶

func (task TaskConfig) String() string

type TaskConfigOperation ¶

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

type TaskConfigOperationParam ¶

type TaskConfigOperationParam struct {
	Name  string      `yaml:"name"`
	Type  string      `yaml:"type"`
	Bind  string      `yaml:"bind"`
	Match string      `yaml:"match"`
	Value interface{} `yaml:"value"` // string or map[string]string
	// Defaults []TaskConfigOperationParamDefaults `yaml:"defaults"`
	Fields []TaskConfigOperationParam `yaml:"fields"`
}

type TaskConfigOperationParamDefaults ¶

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

type TokenAssetConfig ¶

type TokenAssetConfig struct {
	Asset    string      `yaml:"asset,omitempty"`
	Chain    NativeAsset `yaml:"chain,omitempty"`
	Decimals int32       `yaml:"decimals,omitempty"`
	Contract string      `yaml:"contract,omitempty"`

	// Token configs are joined with a chain config upon loading.
	// If there is no matching native asset config, there will be a loading error.
	ChainConfig *ChainConfig `yaml:"-"`
}

func (*TokenAssetConfig) GetAssetSymbol ¶

func (token *TokenAssetConfig) GetAssetSymbol() string

func (*TokenAssetConfig) GetChain ¶

func (asset *TokenAssetConfig) GetChain() *ChainConfig

func (*TokenAssetConfig) GetContract ¶

func (token *TokenAssetConfig) GetContract() string

func (*TokenAssetConfig) GetDecimals ¶

func (asset *TokenAssetConfig) GetDecimals() int32
func (asset *TokenAssetConfig) GetDriver() Driver {
	return Driver(asset.GetNativeAsset().Driver)
}

func (*TokenAssetConfig) ID ¶

func (asset *TokenAssetConfig) ID() AssetID

func (*TokenAssetConfig) String ¶

func (c *TokenAssetConfig) String() string

type Tx ¶

type Tx interface {
	Hash() TxHash
	Sighashes() ([]TxDataToSign, error)
	AddSignatures(...TxSignature) error
	// only needed for RPC endpoints that require signatures in separate fields
	GetSignatures() []TxSignature
	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 ¶

func (data TxDataToSign) String() string

type TxHash ¶

type TxHash string

TxHash is a tx hash or id

type TxInput ¶

type TxInput interface {
	GetDriver() Driver
	TxInputConflicts
	TxInputGasFeeMultiplier
}

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

type TxInputConflicts ¶

type TxInputConflicts interface {
	// Test independence of two tx-inputs, assuming the same address is used.
	// Examples:
	// - using the same nonce or sequence is NOT independent
	// - spending the same resources or utxo's is NOT independent
	// - solana (using recent_block_hash) is pretty much always independent
	// This is used to determine if a transaction needs to be queued or if it can be immediately signed & broadcasted.
	IndependentOf(other TxInput) (independent bool)

	// Test if tx-input could possibly result in a "double-send" given the history of past attempts.
	// A double send is a user re-signing their transaction (to overcome a timeout or use new fees), but then risk multiple transactions
	// landing on chain.  A valid re-sign should only occur if it's only possible for one transaction to land out of the total set of attempts.
	// Examples:
	// - Solana typically has no conflicts, but need to ensure (a) new blockhash is used, and (b) sufficient time has passed
	//   to be sure a double send won't occur (return `true`).
	// - If tx-inputs are not independent (spending same resources), then typically double-sends are impossible (and should return `true` here).
	// - If there exists tx-inputs that are fully independent (and not timed out), then a double-send is possible and this should return false.
	SafeFromDoubleSend(previousAttempts ...TxInput) (safe bool)
}

This interface determines whether if different tx inputs conflict with one another.

type TxInputEnvelope ¶

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

func NewTxInputEnvelope ¶

func NewTxInputEnvelope(envType Driver) *TxInputEnvelope

type TxInputGasFeeMultiplier ¶

type TxInputGasFeeMultiplier interface {
	SetGasFeePriority(priority GasFeePriority) error
}

type TxInputWithAmount ¶

type TxInputWithAmount interface {
	SetAmount(AmountBlockchain)
}

TxInputWithAmount for chains that can optimize the tx input if they know the amount being transferred.

type TxInputWithMemo ¶

type TxInputWithMemo interface {
	SetMemo(string)
}

For chains/transactions that leverage memo field

type TxInputWithPublicKey ¶

type TxInputWithPublicKey interface {
	TxInput
	SetPublicKey([]byte) 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 TxInputWithUnix ¶

type TxInputWithUnix interface {
	SetUnix(int64)
}

For chains/transactions that can benefit from knowing the timestamp

type TxSignature ¶

type TxSignature []byte

TxSignature is a tx signature

func NewTxSignatures ¶

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

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

type TxStatus ¶

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 This interface is soon being removed.

type TxVariantInput ¶

type TxVariantInput interface {
	TxInput
	GetVariant() TxVariantInputType
}

type TxVariantInputType ¶

type TxVariantInputType string

func NewStakingInputType ¶

func NewStakingInputType(driver Driver, variant string) TxVariantInputType

func NewUnstakingInputType ¶

func NewUnstakingInputType(driver Driver, variant string) TxVariantInputType

func NewWithdrawingInputType ¶

func NewWithdrawingInputType(driver Driver, variant string) TxVariantInputType

func (TxVariantInputType) Driver ¶

func (variant TxVariantInputType) Driver() Driver

func (TxVariantInputType) Validate ¶

func (variant TxVariantInputType) Validate() error

func (TxVariantInputType) Variant ¶

func (variant TxVariantInputType) Variant() string

type TxXTransferBuilder ¶

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 This interface is soon being removed.

type UnstakeTxInput ¶

type UnstakeTxInput interface {
	TxVariantInput
	Unstaking()
}

type WithdrawTxInput ¶

type WithdrawTxInput interface {
	TxVariantInput
	Withdrawing()
}

Directories ¶

Path Synopsis
chain
cosmos/types/CosmWasm/wasmd/x/wasm/types
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
Package types is a reverse proxy.
cosmos/types/evmos/ethermint/x/evm/types
Package types is a reverse proxy.
Package types is a reverse proxy.
cosmos/types/evmos/ethermint/x/feemarket/types
Package types is a reverse proxy.
Package types is a reverse proxy.
evm
sui
ton
xrp
cmd
xc
examples
ton
testutil

Jump to

Keyboard shortcuts

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