bitshares

package module
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: May 7, 2020 License: MIT Imports: 15 Imported by: 0

README

bitshares

A Bitshares API consuming a websocket connection to an active full node or a RPC connection to your cli_wallet. Look for several examples in examples and tests folder. This is work in progress. To mitigate breaking changes, please use tagged branches. New tagged branches will be created for breaking changes. No additional cgo dependencies for transaction signing required. Use it at your own risk.

install

go get -u github.com/youthonline/bitshares

Install dev-dependencies with

make init

This API uses ffjson. If you change types or operations you have to regenerate the required static MarshalJSON and UnmarshalJSON functions for the new/changed code.

make generate

If you encounter any errors, try:

make generate_new

to generate ffjson helpers from scratch.

generate operation samples

To generate op samples for testing, go to gen package. Generated operation samples get injected automatically while running operation tests.

testing

To test this stuff I use a combined docker based MainNet/TestNet wallet, you can find here. Operations testing uses generated real blockchain sample code by gen package. To test run:

make test_operations
make test_api

or a long running block (deserialize/serialize/compare) range test.

make test_blocks

code

wsFullApiUrl := "wss://bitshares.openledger.info/ws"

api := bitshares.NewWebsocketAPI(wsFullApiUrl)
if err := api.Connect(); err != nil {
	log.Fatal(err)
}

api.OnError(func(err error) {
	log.Fatal(err)
})

UserID   := types.NewAccountID("1.2.253")
AssetBTS := types.NewAssetID("1.3.0")

res, api.GetAccountBalances(UserID, AssetBTS)
if err != nil {
	log.Fatal(err)
}

log.Printf("balances: %v", res)

If you need wallet functions, use:

rpcApiUrl    := "http://localhost:8095" 
api := bitshares.NewWalletAPI(rpcApiUrl)

if err := api.Connect(); err != nil{
	log.Fatal(err)
}

...

For a long application lifecycle, you can use an API instance with latency tester that connects to the most reliable node. Note: Because the tester takes time to unleash its magic, use the above-mentioned constructor for quick in and out.

wsFullApiUrl := "wss://bitshares.openledger.info/ws"

//wsFullApiUrl serves as "quick startup" fallback endpoint here, 
//until the latency tester provides the first results.

api, err := bitshares.NewWithAutoEndpoint(wsFullApiUrl)
if err != nil {
	log.Fatal(err)
}

if err := api.Connect(); err != nil {
	log.Fatal(err)
}

api.OnError(func(err error) {
	log.Fatal(err)
})

...

implemented and tested (serialize/unserialize) operations

  • OperationTypeTransfer OperationType
  • OperationTypeLimitOrderCreate
  • OperationTypeLimitOrderCancel
  • OperationTypeCallOrderUpdate
  • OperationTypeFillOrder (virtual)
  • OperationTypeAccountCreate
  • OperationTypeAccountUpdate
  • OperationTypeAccountWhitelist
  • OperationTypeAccountUpgrade
  • OperationTypeAccountTransfer
  • OperationTypeAssetCreate
  • OperationTypeAssetUpdate
  • OperationTypeAssetUpdateBitasset
  • OperationTypeAssetUpdateFeedProducers
  • OperationTypeAssetIssue
  • OperationTypeAssetReserve
  • OperationTypeAssetFundFeePool
  • OperationTypeAssetSettle
  • OperationTypeAssetGlobalSettle
  • OperationTypeAssetPublishFeed
  • OperationTypeWitnessCreate
  • OperationTypeWitnessUpdate
  • OperationTypeProposalCreate
  • OperationTypeProposalUpdate
  • OperationTypeProposalDelete
  • OperationTypeWithdrawPermissionCreate
  • OperationTypeWithdrawPermissionUpdate
  • OperationTypeWithdrawPermissionClaim
  • OperationTypeWithdrawPermissionDelete
  • OperationTypeCommitteeMemberCreate
  • OperationTypeCommitteeMemberUpdate
  • OperationTypeCommitteeMemberUpdateGlobalParameters
  • OperationTypeVestingBalanceCreate
  • OperationTypeVestingBalanceWithdraw
  • OperationTypeWorkerCreate
  • OperationTypeCustom
  • OperationTypeAssert
  • OperationTypeBalanceClaim
  • OperationTypeOverrideTransfer
  • OperationTypeTransferToBlind
  • OperationTypeBlindTransfer
  • OperationTypeTransferFromBlind
  • OperationTypeAssetSettleCancel
  • OperationTypeAssetClaimFees
  • OperationTypeFBADistribute
  • OperationTypeBidColatteral
  • OperationTypeExecuteBid

todo

  • add missing operations
  • add convenience functions

Have fun and feel free to contribute needed operations and tests.

Documentation

Index

Constants

View Source
const (
	InvalidApiID                  = -1
	AssetsListAll                 = -1
	AssetsMaxBatchSize            = 100
	GetCallOrdersLimit            = 100
	GetLimitOrdersLimit           = 100
	GetForceSettlementOrdersLimit = 100
	GetTradeHistoryLimit          = 100
	GetAccountHistoryLimit        = 100
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BestNodeClientProvider

type BestNodeClientProvider struct {
	api.WebsocketClient
	// contains filtered or unexported fields
}

func (*BestNodeClientProvider) CallAPI

func (p *BestNodeClientProvider) CallAPI(apiID int, method string, args ...interface{}) (*json.RawMessage, error)

func (*BestNodeClientProvider) Close

func (p *BestNodeClientProvider) Close() error

type ClientProvider

type ClientProvider interface {
	OnError(fn api.ErrorFunc)
	Connect() error
	Subscribe(apiID int, method string, fn api.SubscribeCallback, args ...interface{}) (*json.RawMessage, error)
	CallAPI(apiID int, method string, args ...interface{}) (*json.RawMessage, error)
	Close() error
}

func NewBestNodeClientProvider

func NewBestNodeClientProvider(endpointURL string, ws WebsocketAPI) (ClientProvider, error)

func NewSimpleClientProvider

func NewSimpleClientProvider(endpointURL string, ws WebsocketAPI) ClientProvider

type MemoBuilder

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

MemoBuilder is a memo factory

func (*MemoBuilder) Encrypt

func (p *MemoBuilder) Encrypt(keyBag *crypto.KeyBag) (*types.Memo, error)

Encrypt encrypts the memo message with the corresponding private key found in keyBag

type SimpleClientProvider

type SimpleClientProvider struct {
	api.WebsocketClient
	// contains filtered or unexported fields
}

func (*SimpleClientProvider) CallAPI

func (p *SimpleClientProvider) CallAPI(apiID int, method string, args ...interface{}) (*json.RawMessage, error)

type WalletAPI

type WalletAPI interface {
	Close() error
	Connect() error
	GetBlock(number uint64) (*types.Block, error)
	GetRelativeAccountHistory(account types.GrapheneObject, stop int64, limit int, start int64) (types.OperationRelativeHistories, error)
	GetDynamicGlobalProperties() (*types.DynamicGlobalProperties, error)
	BorrowAsset(account types.GrapheneObject, amountToBorrow string, symbolToBorrow types.GrapheneObject, amountOfCollateral string, broadcast bool) (*types.SignedTransaction, error)
	Buy(account types.GrapheneObject, base, quote types.GrapheneObject, rate string, amount string, broadcast bool) (*types.SignedTransaction, error)
	BuyEx(account types.GrapheneObject, base, quote types.GrapheneObject, rate float64, amount float64, broadcast bool) (*types.SignedTransaction, error)
	CancelOrder(orderID types.GrapheneObject, broadcast bool) (*types.SignedTransaction, error)
	Info() (*types.Info, error)
	IsLocked() (bool, error)
	ListAccountBalances(account types.GrapheneObject) (types.AssetAmounts, error)
	Lock() error
	ReadMemo(memo *types.Memo) (string, error)
	Sell(account types.GrapheneObject, base, quote types.GrapheneObject, rate string, amount string, broadcast bool) (*types.SignedTransaction, error)
	SellEx(account types.GrapheneObject, base, quote types.GrapheneObject, rate float64, amount float64, broadcast bool) (*types.SignedTransaction, error)
	SellAsset(account types.GrapheneObject, amountToSell string, symbolToSell types.GrapheneObject, minToReceive string, symbolToReceive types.GrapheneObject, timeout uint32, fillOrKill bool, broadcast bool) (*types.SignedTransaction, error)
	SignTransaction(tx *types.SignedTransaction, broadcast bool) (*types.SignedTransaction, error)
	SerializeTransaction(tx *types.SignedTransaction) (string, error)
	//Transfer2(from, to types.GrapheneObject, amount string, asset types.GrapheneObject, memo string) (*types.SignedTransactionWithTransactionId, error)
	Unlock(password string) error
}

func NewWalletAPI

func NewWalletAPI(rpcEndpointURL string) WalletAPI

NewWalletAPI creates a new WalletAPI interface. rpcEndpointURL: Is an RPC endpoint URL to your local `cli_wallet`.

type WebsocketAPI

type WebsocketAPI interface {
	//Common functions
	CallWsAPI(apiID int, method string, args ...interface{}) (*json.RawMessage, error)
	Close() error
	Connect() error
	DatabaseAPIID() int
	HistoryAPIID() int
	BroadcastAPIID() int
	SetCredentials(username, password string)
	OnError(api.ErrorFunc)
	Subscribe(apiID int, method string, fn api.SubscribeCallback, args ...interface{}) (*json.RawMessage, error)
	BuildSignedTransaction(keyBag *crypto.KeyBag, feeAsset types.GrapheneObject, ops ...types.Operation) (*types.SignedTransaction, error)
	SignTransaction(keyBag *crypto.KeyBag, trx *types.SignedTransaction) error

	//Websocket API functions
	BroadcastTransaction(tx *types.SignedTransaction) error
	BroadcastTransactionSynchronous(tx *types.SignedTransaction) (*types.BroadcastResponse, error)
	CancelAllSubscriptions() error
	GetAccountBalances(account types.GrapheneObject, assets ...types.GrapheneObject) (types.AssetAmounts, error)
	GetAccountByName(name string) (*types.Account, error)
	GetAccountHistory(account types.GrapheneObject, stop types.GrapheneObject, limit int, start types.GrapheneObject) (types.OperationHistories, error)
	GetAccounts(accountIDs ...types.GrapheneObject) (types.Accounts, error)
	GetBlock(number uint64) (*types.Block, error)
	GetBlockHeader(block uint64) (*types.BlockHeader, error)
	GetCallOrders(assetID types.GrapheneObject, limit int) (types.CallOrders, error)
	GetChainID() (string, error)
	GetDynamicGlobalProperties() (*types.DynamicGlobalProperties, error)
	GetForceSettlementOrders(assetID types.GrapheneObject, limit int) (types.ForceSettlementOrders, error)
	GetFullAccounts(accountIDs ...types.GrapheneObject) (types.FullAccountInfos, error)
	GetLimitOrders(base, quote types.GrapheneObject, limit int) (types.LimitOrders, error)
	GetOrderBook(base, quote types.GrapheneObject, depth int) (*types.OrderBook, error)
	GetMarginPositions(accountID types.GrapheneObject) (types.CallOrders, error)
	GetObjects(objectIDs ...types.GrapheneObject) ([]interface{}, error)
	GetPotentialSignatures(tx *types.SignedTransaction) (types.PublicKeys, error)
	GetRecentTransactionByID(transactionID uint32) (*types.SignedTransaction, error)
	GetRequiredSignatures(tx *types.SignedTransaction, keys types.PublicKeys) (types.PublicKeys, error)
	GetRequiredFees(ops types.Operations, feeAsset types.GrapheneObject) (types.AssetAmounts, error)
	GetTicker(base, quote types.GrapheneObject) (*types.MarketTicker, error)
	GetTradeHistory(base, quote types.GrapheneObject, toTime, fromTime time.Time, limit int) (types.MarketTrades, error)
	GetTransaction(blockNum uint64, trxInBlock uint32) (*types.SignedTransaction, error)
	LimitOrderCancel(keyBag *crypto.KeyBag, feePayingAccount, orderID, feeAsset types.GrapheneObject) error
	ListAssets(lowerBoundSymbol string, limit int) (types.Assets, error)
	LookupAssetSymbols(symbols ...string) (types.Assets, error)
	SetSubscribeCallback(ID uint64, clearFilter bool) error
	SubscribeToBlockApplied(onBlockApplied api.BlockAppliedCallback) error
	SubscribeToMarket(base, quote types.GrapheneObject, onMarketData api.SubscribeCallback) error
	SubscribeToPendingTransactions(onPendingTransaction api.SubscribeCallback) error
	Transfer(keyBag *crypto.KeyBag, from, to, feeAsset types.GrapheneObject, amount types.AssetAmount, memo string) error
	UnsubscribeFromMarket(base, quote types.GrapheneObject) error
	Get24Volume(base types.GrapheneObject, quote types.GrapheneObject) (*types.Volume24, error)
}

func NewWebsocketAPI

func NewWebsocketAPI(wsEndpointURL string) WebsocketAPI

NewWebsocketAPI creates a new WebsocketAPI interface. wsEndpointURL: a websocket node endpoint URL.

func NewWebsocketAPIWithAutoEndpoint

func NewWebsocketAPIWithAutoEndpoint(startupEndpointURL string) (WebsocketAPI, error)

NewWebsocketAPIWithAutoEndpoint creates a new WebsocketAPI interface with automatic node latency checking. It's best to use this API instance type for a long API lifecycle because the latency tester takes time to unleash its magic. startupEndpointURL: a websocket node endpoint URL to startup the latency tester quickly.

Directories

Path Synopsis
examples
gen

Jump to

Keyboard shortcuts

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