base

package
v0.0.0-...-3f3ae68 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnsupportedFunction = errors.New("this method is not supported")

	ErrInvalidPrivateKey = errors.New("invalid private key")
	ErrInvalidPublicKey  = errors.New("invalid public key")
	ErrInvalidAddress    = errors.New("invalid address")

	ErrInvalidChainType       = errors.New("invalid chain type")
	ErrInvalidAccountType     = errors.New("invalid account type")
	ErrInvalidTransactionType = errors.New("invalid transaction type")

	ErrInvalidAccountAddress = errors.New("invalid account address")
	ErrInvalidAmount         = errors.New("invalid amount")

	ErrMissingTransaction = errors.New("missing transaction information")

	ErrNotCoinTransferTxn = errors.New("not a coin transfer transaction")

	ErrEstimateGasNeedPublicKey = errors.New("the estimated fee should invoking `EstimateTransactionFeeUsePublicKey`")
)

Functions

func CatchPanicAndMapToBasicError

func CatchPanicAndMapToBasicError(errOfResult *error)

[zh] 该方法会捕捉 panic 抛出的值,并转成一个 error 对象通过参数指针返回 * 注意: 如果想要返回它抓住的 error, 必须使用命名返回值!! * [en] This method will catch the value thrown by panic, and turn it into an error object and return it through the parameter pointer * Note: If you want to return the error it caught, you must use a named return value! ! * ``` * func actionWillThrowError(parameters...) (namedErr error, other...) { * defer CatchPanicAndMapToBasicError(&namedErr) * // action code ... * return namedErr, other... * } * ```

func FromJsonString

func FromJsonString(jsonStr string, out interface{}) error

func MapAnyToBasicError

func MapAnyToBasicError(e any) error

func MapListConcurrent

func MapListConcurrent(list []interface{}, limit int, maper func(interface{}) (interface{}, error)) ([]interface{}, error)

This method will traverse the array concurrently and map each object in the array. @param list: [TYPE1], a list that all item is TYPE1 @param limit: maximum number of tasks to execute, 0 means no limit @param maper: func(TYPE1) (TYPE2, error), a function that input TYPE1, return TYPE2

you can throw an error to finish task.

@return : [TYPE2], a list that all item is TYPE2 @example : ```

nums := []interface{}{1, 2, 3, 4, 5, 6}
res, _ := MapListConcurrent(nums, func(i interface{}) (interface{}, error) {
    return strconv.Itoa(i.(int) * 100), nil
})
println(res) // ["100" "200" "300" "400" "500" "600"]

```

func MapListConcurrentStringToString

func MapListConcurrentStringToString(strList []string, maper func(string) (string, error)) ([]string, error)

The encapsulation of MapListConcurrent.

func Max

func Max[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | string](x, y T) T

@note float64 should use `math.Max()`

func MaxBigInt

func MaxBigInt(x, y *big.Int) *big.Int

Return the more biger of the two numbers

func Min

func Min[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | string](x, y T) T

@note float64 should use `math.Min()`

func ParseNumber

func ParseNumber(num string) (*big.Int, error)

ParseNumber @param num any format number, such as decimal "1237890123", hex "0x123ef0", "123ef0"

func ParseNumberToDecimal

func ParseNumberToDecimal(num string) string

ParseNumberToDecimal @param num any format number, such as decimal "1237890123", hex "0x123ef0", "123ef0" @return decimal number, characters include 0-9

func ParseNumberToHex

func ParseNumberToHex(num string) string

ParseNumberToHex @param num any format number, such as decimal "1237890123", hex "0x123ef0", "123ef0" @return hex number start with 0x, characters include 0-9 a-f

Types

type Account

type Account interface {
	// PrivateKey 生成私钥
	PrivateKey() ([]byte, error)
	// PrivateKeyHex 生成私钥16进制
	PrivateKeyHex() (string, error)

	// PublicKey 生成公钥
	PublicKey() []byte
	// PublicKeyHex 公钥16进制
	PublicKeyHex() string

	// Address 转换地址
	Address() string

	// Sign 签名数据
	Sign(message []byte, password string) ([]byte, error)
	SignHex(messageHex string, password string) (*OptionalString, error)
}

type AddressUtil

type AddressUtil interface {
	// EncodePublicKeyToAddress 地址加密转换伴随0x
	EncodePublicKeyToAddress(publicKey string) (string, error)
	// DecodeAddressToPublicKey 地址解密转换伴随0x
	DecodeAddressToPublicKey(address string) (string, error)
	// IsValidAddress 是否是合法地址
	IsValidAddress(address string) bool
}

type Aniable

type Aniable interface {
	AsAny() *Any
}

exchange `Aniable Object` & `Any`

type Any

type Any struct {
	Value any
}

如果需要自定义类型支持 Any, 需要遵循协议 Aniable

func NewAny

func NewAny() *Any

func (*Any) GetBigInt

func (a *Any) GetBigInt() *BigInt

func (*Any) GetBool

func (a *Any) GetBool() bool

func (*Any) GetInt

func (a *Any) GetInt() int

func (*Any) GetInt16

func (a *Any) GetInt16() int16

func (*Any) GetInt32

func (a *Any) GetInt32() int32

func (*Any) GetInt64

func (a *Any) GetInt64() int64

func (*Any) GetInt8

func (a *Any) GetInt8() int8

func (*Any) GetString

func (a *Any) GetString() string

func (*Any) GetUInt16

func (a *Any) GetUInt16() *BigInt

func (*Any) GetUInt32

func (a *Any) GetUInt32() *BigInt

func (*Any) GetUInt64

func (a *Any) GetUInt64() *BigInt

func (*Any) GetUInt8

func (a *Any) GetUInt8() *BigInt

func (*Any) JsonString

func (a *Any) JsonString() (*OptionalString, error)

func (Any) MarshalJSON

func (a Any) MarshalJSON() ([]byte, error)

`Any` only support Marshal

func (*Any) SetBigInt

func (a *Any) SetBigInt(v *BigInt)

func (*Any) SetBool

func (a *Any) SetBool(v bool)

func (*Any) SetInt

func (a *Any) SetInt(v int)

func (*Any) SetInt16

func (a *Any) SetInt16(v int16)

func (*Any) SetInt32

func (a *Any) SetInt32(v int32)

func (*Any) SetInt64

func (a *Any) SetInt64(v int64)

func (*Any) SetInt8

func (a *Any) SetInt8(v int8)

func (*Any) SetString

func (a *Any) SetString(v string)

func (*Any) SetUInt16

func (a *Any) SetUInt16(v *BigInt)

func (*Any) SetUInt32

func (a *Any) SetUInt32(v *BigInt)

func (*Any) SetUInt64

func (a *Any) SetUInt64(v *BigInt)

func (*Any) SetUInt8

func (a *Any) SetUInt8(v *BigInt)

type AnyArray

type AnyArray struct {
	Values []any
}

func AsAnyArray

func AsAnyArray(a *Any) *AnyArray

func NewAnyArray

func NewAnyArray() *AnyArray

func (*AnyArray) Append

func (a *AnyArray) Append(any *Any)

func (*AnyArray) AsAny

func (a *AnyArray) AsAny() *Any

func (*AnyArray) Contains

func (a *AnyArray) Contains(any *Any) bool

func (*AnyArray) Count

func (a *AnyArray) Count() int

func (*AnyArray) IndexOf

func (a *AnyArray) IndexOf(any *Any) int

return -1 if not found

func (*AnyArray) JsonString

func (a *AnyArray) JsonString() (*OptionalString, error)

func (AnyArray) MarshalJSON

func (a AnyArray) MarshalJSON() ([]byte, error)

`AnyArray` only support Marshal

func (*AnyArray) Remove

func (a *AnyArray) Remove(index int)

func (*AnyArray) SetValue

func (a *AnyArray) SetValue(value *Any, index int)

func (*AnyArray) String

func (a *AnyArray) String() string

func (*AnyArray) ValueOf

func (a *AnyArray) ValueOf(index int) *Any

type AnyMap

type AnyMap struct {
	Values map[string]any
}

func AsAnyMap

func AsAnyMap(a *Any) *AnyMap

func NewAnyMap

func NewAnyMap() *AnyMap

func (*AnyMap) AsAny

func (a *AnyMap) AsAny() *Any

func (*AnyMap) HasKey

func (a *AnyMap) HasKey(key string) bool

func (*AnyMap) JsonString

func (a *AnyMap) JsonString() (*OptionalString, error)

func (*AnyMap) Keys

func (a *AnyMap) Keys() *StringArray

func (AnyMap) MarshalJSON

func (a AnyMap) MarshalJSON() ([]byte, error)

`AnyMap` only support Marshal

func (*AnyMap) Remove

func (a *AnyMap) Remove(key string) *Any

func (*AnyMap) SetValue

func (a *AnyMap) SetValue(value *Any, key string)

func (*AnyMap) String

func (a *AnyMap) String() string

func (*AnyMap) ValueOf

func (a *AnyMap) ValueOf(key string) *Any

type Balance

type Balance struct {
	Total  string
	Usable string
}

func EmptyBalance

func EmptyBalance() *Balance

type BigInt

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

A BigInt represents a signed multi-precision integer.

func NewBigInt

func NewBigInt(x int64) *BigInt

NewBigInt allocates and returns a new BigInt set to x.

func NewBigIntFromString

func NewBigIntFromString(x string, base int) *BigInt

NewBigIntFromString allocates and returns a new BigInt set to x interpreted in the provided base.

func (*BigInt) GetBytes

func (bi *BigInt) GetBytes() []byte

GetBytes returns the absolute value of x as a big-endian byte slice.

func (*BigInt) GetInt64

func (bi *BigInt) GetInt64() int64

GetInt64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined.

func (*BigInt) GetString

func (bi *BigInt) GetString(base int) string

GetString returns the value of x as a formatted string in some number base.

func (*BigInt) SetBytes

func (bi *BigInt) SetBytes(buf []byte)

SetBytes interprets buf as the bytes of a big-endian unsigned integer and sets the big int to that value.

func (*BigInt) SetInt64

func (bi *BigInt) SetInt64(x int64)

SetInt64 sets the big int to x.

func (*BigInt) SetString

func (bi *BigInt) SetString(x string, base int)

SetString sets the big int to x.

The string prefix determines the actual conversion base. A prefix of "0x" or "0X" selects base 16; the "0" prefix selects base 8, and a "0b" or "0B" prefix selects base 2. Otherwise the selected base is 10.

func (*BigInt) Sign

func (bi *BigInt) Sign() int

Sign returns:

-1 if x <  0
 0 if x == 0
+1 if x >  0

func (*BigInt) String

func (bi *BigInt) String() string

String returns the value of x as a formatted decimal string.

type BigInts

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

BigInts represents a slice of big ints.

func NewBigInts

func NewBigInts(size int) *BigInts

NewBigInts creates a slice of uninitialized big numbers.

func (*BigInts) Get

func (bi *BigInts) Get(index int) (bigint *BigInt, _ error)

Get returns the bigint at the given index from the slice.

func (*BigInts) Set

func (bi *BigInts) Set(index int, bigint *BigInt) error

Set sets the big int at the given index in the slice.

func (*BigInts) Size

func (bi *BigInts) Size() int

Size returns the number of big ints in the slice.

type Chain

type Chain interface {
	MainToken() Token

	BalanceOfAddress(address string) (*Balance, error)
	BalanceOfPublicKey(publicKey string) (*Balance, error)
	BalanceOfAccount(account Account) (*Balance, error)

	// Send the raw transaction on-chain
	// @return the hex hash string
	SendRawTransaction(signedTx string) (string, error)

	// Send the signed transaction on-chain
	// @return the hex hash string
	SendSignedTransaction(signedTxn SignedTransaction) (*OptionalString, error)

	// Fetch transaction details through transaction hash
	FetchTransactionDetail(hash string) (*TransactionDetail, error)

	// Fetch transaction status through transaction hash
	FetchTransactionStatus(hash string) TransactionStatus

	// Batch fetch the transaction status, the hash list and the return value,
	// which can only be passed as strings separated by ","
	// @param hashListString The hash of the transactions to be queried in batches, a string concatenated with ",": "hash1,hash2,hash3"
	// @return Batch transaction status, its order is consistent with hashListString: "status1,status2,status3"
	BatchFetchTransactionStatus(hashListString string) string
}

type Jsonable

type Jsonable interface {
	JsonString() (*OptionalString, error)
}

type NFT

type NFT struct {
	Timestamp  int64  `json:"timestamp"`
	HashString string `json:"hashString"`

	Id              string `json:"id"`
	Name            string `json:"name"`
	Image           string `json:"image"`
	Standard        string `json:"standard"`
	Collection      string `json:"collection"`
	Descr           string `json:"descr"`
	ContractAddress string `json:"contract_address"`

	RelatedUrl string `json:"related_url"`

	// Aptos token's largest_property_version
	AptTokenVersion int64 `json:"apt_token_version"`
	// Aptos token's amount
	AptAmount int64 `json:"apt_amount"`
}

func (*NFT) ExtractedImageUrl

func (n *NFT) ExtractedImageUrl() string

func (*NFT) GroupName

func (n *NFT) GroupName() string

type NFTFetcher

type NFTFetcher interface {
	/** Gets all NFTs for the specified account and groups them by Collection name
	 * @owner The specified account address
	 * @return Grouped NFTs in below format
	 * “`
	 *  {
	 *    "Collection1": [ NFT1, NFT2 ],
	 *    "Collection2": [ NFT3 ],
	 *    "Collection3": [ NFT4, NFT5, NFT6, ... ],
	 *  }
	 * “`
	 */
	FetchNFTs(owner string) (map[string][]*NFT, error)

	/** Gets all NFT JSON Strings for the specified account
	 * @owner The specified account address
	 * @return This method directly calls `FetchNFTs()` and jsonifies the result and returns
	 */
	FetchNFTsJsonString(owner string) (*OptionalString, error)
}

type OptionalBool

type OptionalBool struct {
	Value bool
}

OptionalBool Optional bool for easy of writing iOS code

type OptionalString

type OptionalString struct {
	Value string
}

OptionalString Optional string for easy of writing iOS code

func ExtractNFTImageUrl

func ExtractNFTImageUrl(url string) (u *OptionalString, err error)

ExtractNFTImageUrl Extract the nft's real image url. If the content type of the given url is JSON, it's will return the `image` field specified url.

func JsonString

func JsonString(o interface{}) (*OptionalString, error)

type Pageable

type Pageable interface {
	Jsonable

	// The total count of all data in the remote server. Returns 0 if statistics are not available
	TotalCount() int
	// The count of data in the current page.
	CurrentCount() int
	// The cursor of the current page.
	CurrentCursor() string
	// Is there has next page.
	HasNextPage() bool

	ItemArray() *AnyArray
}

type ReachMonitor

type ReachMonitor struct {
	// The number of network connectivity tests to be performed per rpc. 0 means infinite, default is 1
	ReachCount int
	// Timeout for each connectivity test (ms). default 20000ms
	Timeout int64
	// Time interval between two network connectivity tests (ms). default 1500ms
	Delay int64
	// contains filtered or unexported fields
}

func NewReachMonitorWithReachability

func NewReachMonitorWithReachability(reachability RpcReachability) *ReachMonitor

You need to pass in different objects to get the latency and block height of different chains. let reachability = eth.RpcReachability() let reachability = polka.RpcReachability() let reachability = sui.RestReachability() ... let monitor = NewReachMonitorWithReachability(reachability)

func (*ReachMonitor) StartConnectivityDelegate

func (r *ReachMonitor) StartConnectivityDelegate(rpcList string, delegate ReachMonitorDelegate)

@param rpcList string of rpcs like "rpc1,rpc2,rpc3,..."

func (*ReachMonitor) StartConnectivitySync

func (r *ReachMonitor) StartConnectivitySync(rpcList string) string

@param rpcList string of rpcs like "rpc1,rpc2,rpc3,..." @return jsonString sorted array base of tatency like "[{rpcUrl:rpc1,latency:100}, {rpcUrl:rpc2, latency:111}, ...]" latency unit is ms. -1 means the connection failed

func (*ReachMonitor) StopConnectivity

func (r *ReachMonitor) StopConnectivity()

type ReachMonitorDelegate

type ReachMonitorDelegate interface {
	// A node has received a response
	ReachabilityDidReceiveNode(monitor *ReachMonitor, latency *RpcLatency)
	// A node request failed
	ReachabilityDidFailNode(monitor *ReachMonitor, latency *RpcLatency)
	// The entire network connection test task is over
	// @param overview Overview of the results of all connection tests
	ReachabilityDidFinish(monitor *ReachMonitor, overview string)
}

type RpcLatency

type RpcLatency struct {
	RpcUrl  string `json:"rpcUrl"`
	Latency int64  `json:"latency"`
	Height  int64  `json:"height"`
}

type RpcReachability

type RpcReachability interface {
	LatencyOf(rpc string, timeout int64) (l *RpcLatency, err error)
}

You can customize the test latency method of rpc

type SDKEnumInt

type SDKEnumInt = int

type SDKEnumString

type SDKEnumString = string

type SignedTransaction

type SignedTransaction interface {
	HexString() (res *OptionalString, err error)
}

type StringArray

type StringArray struct {
	Values []string
}

func (*StringArray) Append

func (a *StringArray) Append(value string)

func (*StringArray) Contains

func (a *StringArray) Contains(value string) bool

func (*StringArray) Count

func (a *StringArray) Count() int

func (*StringArray) IndexOf

func (a *StringArray) IndexOf(value string) int

IndexOf return -1 if not found

func (*StringArray) Remove

func (a *StringArray) Remove(index int)

func (*StringArray) SetValue

func (a *StringArray) SetValue(value string, index int)

func (*StringArray) String

func (a *StringArray) String() string

func (*StringArray) ValueOf

func (a *StringArray) ValueOf(index int) string

type Token

type Token interface {
	Chain() Chain

	TokenInfo() (*TokenInfo, error)

	BalanceOfAddress(address string) (*Balance, error)
	BalanceOfPublicKey(publicKey string) (*Balance, error)
	BalanceOfAccount(account Account) (*Balance, error)

	BuildTransfer(sender, receiver, amount string) (txn Transaction, err error)
	// CanTransferAll Before invoking this method, it is best to check `CanTransferAll()`
	CanTransferAll() bool
	BuildTransferAll(sender, receiver string) (txn Transaction, err error)
}

type TokenInfo

type TokenInfo struct {
	Name    string
	Symbol  string
	Decimal int16
}

type Transaction

type Transaction interface {
	SignWithAccount(account Account) (signedTxn *OptionalString, err error)
	SignedTransactionWithAccount(account Account) (signedTxn SignedTransaction, err error)
}

type TransactionDetail

type TransactionDetail struct {
	// hash string on chain
	HashString string

	// transaction amount
	Amount string

	EstimateFees string

	// sender's address
	FromAddress string
	// receiver's address
	ToAddress string

	Status TransactionStatus
	// transaction completion timestamp (s), 0 if Status is in Pending
	FinishTimestamp int64
	// failure message
	FailureMessage string

	// If this transaction is a CID transfer, its value will be the CID, otherwise it is empty
	CIDNumber string
	// If this transaction is a NFT transfer, its value will be the Token name, otherwise it is empty
	TokenName string
}

Transaction details that can be fetched from the chain

func (*TransactionDetail) IsCIDTransfer

func (d *TransactionDetail) IsCIDTransfer() bool

Check the `CIDNumber` is not empty.

func (*TransactionDetail) IsNFTTransfer

func (d *TransactionDetail) IsNFTTransfer() bool

Check the `TokenName` is not empty.

func (*TransactionDetail) JsonString

func (d *TransactionDetail) JsonString() string

type TransactionStatus

type TransactionStatus = SDKEnumInt
const (
	TransactionStatusNone    TransactionStatus = 0
	TransactionStatusPending TransactionStatus = 1
	TransactionStatusSuccess TransactionStatus = 2
	TransactionStatusFailure TransactionStatus = 3
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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