forked from denkhaus/go-bitshares
-
Notifications
You must be signed in to change notification settings - Fork 2
/
websocket.go
1933 lines (1579 loc) · 58.9 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cocos
import (
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/gkany/cocos-go/api"
"github.com/gkany/cocos-go/config"
"github.com/gkany/cocos-go/crypto"
"github.com/gkany/cocos-go/logging"
"github.com/gkany/cocos-go/operations"
"github.com/gkany/cocos-go/types"
"github.com/gkany/cocos-go/util"
"github.com/juju/errors"
"github.com/pquerna/ffjson/ffjson"
// init operations
_ "github.com/gkany/cocos-go/operations"
)
const (
InvalidApiID = -1
AssetsListAll = -1
AssetsMaxBatchSize = 100
GetCallOrdersLimit = 100
GetLimitOrdersLimit = 100
GetForceSettlementOrdersLimit = 100
GetTradeHistoryLimit = 100
GetAccountHistoryLimit = 100
)
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, 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)
GetWitness(accountID string) (*types.Witness, error)
GetCommitteeMember(accountID string) (*types.CommitteeMember, 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)
GetChainProperties() (*types.ChainProperty, error)
GetGlobalProperties() (*types.GlobalProperty, 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)
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 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 types.GrapheneObject, amount types.AssetAmount, memo string, isEncrypt bool) error
UnsubscribeFromMarket(base, quote types.GrapheneObject) error
Get24Volume(base types.GrapheneObject, quote types.GrapheneObject) (*types.Volume24, error)
CreateAsset(keyBag *crypto.KeyBag, issuer types.GrapheneObject, symbol string, precision uint8, common types.AssetOptions, bitasset *types.BitassetOptions) error
RegisterAccount(keyBag *crypto.KeyBag, name string, owner, active *types.PublicKey, register string) error
UpgradeAccount(keyBag *crypto.KeyBag, name string) error
IssueAsset(keyBag *crypto.KeyBag, toAccount types.Account, amount int64, asset types.Asset, memo string, isEncrypt bool) error
UpdateAsset(keyBag *crypto.KeyBag, asset types.Asset, newIssuer *types.Account, newOptions types.AssetOptions) error
UpdateBitAsset(keyBag *crypto.KeyBag, asset types.Asset, newIssuer *types.Account, newOptions types.BitassetOptions) error
UpdateAssetFeedProducers(keyBag *crypto.KeyBag, asset types.Asset, producers types.AccountIDs) error
PublishAssetFeed(keyBag *crypto.KeyBag, publisher types.Account, asset types.Asset, feed types.PriceFeed) error
ReserveAsset(keyBag *crypto.KeyBag, payer types.Account, asset types.Asset, amount int64) error
GlobalSettleAsset(keyBag *crypto.KeyBag, asset types.Asset, settlePrice types.Price) error
SettleAsset(keyBag *crypto.KeyBag, account types.Account, asset types.Asset, amount int64) error
// BidCollateral(keyBag *crypto.KeyBag, bidder types.Account, asset types.Asset, debtAmount, additionalCollateral int64) error
CreateCommitteeMember(keyBag *crypto.KeyBag, ownerAccount types.Account, url string) error
UpdateCommitteeMember(keyBag *crypto.KeyBag, committeeAccount types.Account, url *string, workStatus bool) error
CreateWitness(keyBag *crypto.KeyBag, ownerAccount types.Account, url string, signKey types.PublicKey) error
UpdateWitness(keyBag *crypto.KeyBag, witnessAccount types.Account, url *string, signKey *types.PublicKey, workStatus bool) error
ContractCreate(keyBag *crypto.KeyBag, ownerAccount *types.Account, name, data string, contractAuthority *types.PublicKey) error
ReviseContract(keyBag *crypto.KeyBag, reviser *types.Account, contractID types.ContractID, data string) error
ContractCreateFromFile(keyBag *crypto.KeyBag, ownerAccount *types.Account, name, filename string, contractAuthority *types.PublicKey) error
ReviseContractFromFile(keyBag *crypto.KeyBag, reviser *types.Account, contractID types.ContractID, filename string) error
GetContract(name string) (*types.Contract, error)
GetVestingBalances(account *types.Account) (*types.VestingBalances, error)
WithDrawVesting(keyBag *crypto.KeyBag, owner *types.Account, id types.VestingBalanceID, amount types.AssetAmount) error
VoteForCommitteeMember(keyBag *crypto.KeyBag, votingAccount, committeeMember string, approve uint64) error
VoteForWitness(keyBag *crypto.KeyBag, votingAccount, witnessAccount string, approve uint64) error
GetConnectedPeers() (*types.NetWorkPeers, error)
Info()(*types.Info, error)
// improt_balances
// sell_asset
// sell
// buy
// borrow_asset
// cancel_order
// approve_proposal
// update_collateral_for_gas
// nh_asset/order
// contract
// file
// crontab
}
type websocketAPI struct {
wsClient ClientProvider
username string
password string
databaseAPIID int
historyAPIID int
broadcastAPIID int
networkNodeAPIID int
}
func (p *websocketAPI) getAPIID(identifier string) (int, error) {
resp, err := p.wsClient.CallAPI(1, identifier, types.EmptyParams)
if err != nil {
return InvalidApiID, errors.Annotatef(err, "CallAPI %s", identifier)
}
logging.DDumpJSON("getApiID <", resp)
var id int
if err := ffjson.Unmarshal(*resp, &id); err != nil {
return InvalidApiID, errors.Annotate(err, "Unmarshal [id]")
}
return id, nil
}
// login
func (p *websocketAPI) login() (bool, error) {
resp, err := p.wsClient.CallAPI(1, "login", p.username, p.password)
if err != nil {
return false, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("login <", resp)
var success bool
if err := ffjson.Unmarshal(*resp, &success); err != nil {
return false, errors.Annotate(err, "Unmarshal [success]")
}
return success, nil
}
// SetSubscribeCallback - To simplify development a global subscription callback can be registered.
// Every notification initiated by the full node will carry a particular id as defined by the user with the identifier parameter.
func (p *websocketAPI) SetSubscribeCallback(ID uint64, clearFilter bool) error {
_, err := p.wsClient.CallAPI(p.databaseAPIID, "set_subscribe_callback", ID, clearFilter)
if err != nil {
return errors.Annotate(err, "CallAPI")
}
return nil
}
// SubscribeToPendingTransactions - Notifications for incoming unconfirmed transactions.
func (p *websocketAPI) SubscribeToPendingTransactions(onPendingTransaction api.SubscribeCallback) error {
_, err := p.wsClient.Subscribe(p.databaseAPIID, "set_pending_transaction_callback",
onPendingTransaction,
)
return err
}
// SubscribeToBlockApplied gives a notification whenever the block blockid is applied to the blockchain.
func (p *websocketAPI) SubscribeToBlockApplied(onBlockApplied api.BlockAppliedCallback) error {
_, err := p.wsClient.Subscribe(p.databaseAPIID, "set_block_applied_callback",
func(in interface{}) error {
for _, id := range in.([]interface{}) {
if err := onBlockApplied(id.(string)); err != nil {
return err
}
}
return nil
},
)
return err
}
// SubscribeToMarket subscribes to market changes in market base:quote and sends notifications by callback.
func (p *websocketAPI) SubscribeToMarket(base, quote types.GrapheneObject, onMarketData api.SubscribeCallback) error {
_, err := p.wsClient.Subscribe(p.databaseAPIID, "subscribe_to_market",
onMarketData, base.ID(), quote.ID(),
)
return err
}
// UnsubscribeFromMarket
func (p *websocketAPI) UnsubscribeFromMarket(base types.GrapheneObject, quote types.GrapheneObject) error {
// returns nil if successful
_, err := p.wsClient.CallAPI(p.databaseAPIID, "unsubscribe_from_market", base.ID(), quote.ID())
if err != nil {
return errors.Annotate(err, "CallAPI")
}
return nil
}
// CancelAllSubscriptions
func (p *websocketAPI) CancelAllSubscriptions() error {
// returns nil
_, err := p.wsClient.CallAPI(p.databaseAPIID, "cancel_all_subscriptions", types.EmptyParams)
if err != nil {
return errors.Annotate(err, "CallAPI")
}
return nil
}
// BroadcastTransaction broadcasts a transaction to the network.
// The transaction will be checked for validity prior to broadcasting. If it fails to apply at the connected node,
// an error will be thrown and the transaction will not be broadcast.
func (p *websocketAPI) BroadcastTransaction(tx *types.SignedTransaction) error {
_, err := p.wsClient.CallAPI(p.broadcastAPIID, "broadcast_transaction", tx)
if err != nil {
return errors.Annotate(err, "CallAPI")
}
return nil
}
// BroadcastTransactionSynchronous broadcasts a transaction to the network.
// The transaction will be checked for validity prior to broadcasting. If it fails to apply at the connected node,
// an error will be thrown and the transaction will not be broadcast. This version of broadcast transaction registers a callback method
// that will be called when the transaction is included into a block. The callback method includes the transaction id, block number, and transaction number in the block.
func (p *websocketAPI) BroadcastTransactionSynchronous(tx *types.SignedTransaction) (*types.BroadcastResponse, error) {
resp, err := p.wsClient.CallAPI(p.broadcastAPIID, "broadcast_transaction_synchronous", tx)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
var ret types.BroadcastResponse
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [BroadcastResponse]")
}
return &ret, nil
}
//SignTransaction signs a given transaction.
//Required signing keys get selected by API and have to be in keyBag.
func (p *websocketAPI) SignTransaction(keyBag *crypto.KeyBag, tx *types.SignedTransaction) error {
reqPk, err := p.RequiredSigningKeys(tx)
if err != nil {
return errors.Annotate(err, "RequiredSigningKeys")
}
signer := crypto.NewTransactionSigner(tx)
privKeys := keyBag.PrivatesByPublics(reqPk)
if len(privKeys) == 0 {
return types.ErrNoSigningKeyFound
}
if err := signer.Sign(privKeys, config.Current()); err != nil {
return errors.Annotate(err, "Sign")
}
return nil
}
//BuildSignedTransaction builds a new transaction by given operation(s),
//applies fees, current block data and signs the transaction.
func (p *websocketAPI) BuildSignedTransaction(keyBag *crypto.KeyBag, ops ...types.Operation) (*types.SignedTransaction, error) {
operations := types.Operations(ops)
props, err := p.GetDynamicGlobalProperties()
if err != nil {
return nil, errors.Annotate(err, "GetDynamicGlobalProperties")
}
tx, err := types.NewSignedTransactionWithBlockData(props)
if err != nil {
return nil, errors.Annotate(err, "NewTransaction")
}
tx.Operations = operations
fmt.Printf("tx: %v\n", tx)
reqPk, err := p.RequiredSigningKeys(tx)
if err != nil {
return nil, errors.Annotate(err, "RequiredSigningKeys")
}
fmt.Printf("reqPk: %v\n", reqPk)
signer := crypto.NewTransactionSigner(tx)
privKeys := keyBag.PrivatesByPublics(reqPk)
if len(privKeys) == 0 {
return nil, types.ErrNoSigningKeyFound
}
// fmt.Printf("privKeys: %v\n", privKeys)
if err := signer.Sign(privKeys, config.Current()); err != nil {
return nil, errors.Annotate(err, "Sign")
}
return tx, nil
}
//RequiredSigningKeys is a convenience call to retrieve the minimum subset of public keys to sign a transaction.
//If the transaction is already signed, the result is empty.
func (p *websocketAPI) RequiredSigningKeys(tx *types.SignedTransaction) (types.PublicKeys, error) {
potPk, err := p.GetPotentialSignatures(tx)
if err != nil {
return nil, errors.Annotate(err, "GetPotentialSignatures")
}
logging.DDumpJSON("potential pubkeys <", potPk)
reqPk, err := p.GetRequiredSignatures(tx, potPk)
if err != nil {
return nil, errors.Annotate(err, "GetRequiredSignatures")
}
logging.DDumpJSON("required pubkeys <", reqPk)
return reqPk, nil
}
//GetPotentialSignatures will return the set of all public keys that could possibly sign for a given transaction.
//This call can be used by wallets to filter their set of public keys to just the relevant subset prior to calling
//GetRequiredSignatures to get the minimum subset.
func (p *websocketAPI) GetPotentialSignatures(tx *types.SignedTransaction) (types.PublicKeys, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_potential_signatures", tx)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_potential_signatures <", resp)
ret := types.PublicKeys{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [PublicKeys]")
}
return ret, nil
}
// GetTransaction used to fetch an individual transaction.
func (p *websocketAPI) GetTransaction(blockNum uint64, trxInBlock uint32) (*types.SignedTransaction, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_transaction", blockNum, trxInBlock)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_transaction <", resp)
ret := types.SignedTransaction{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Transaction]")
}
return &ret, nil
}
// GetRecentTransactionByID
// If the transaction has not expired, this method will return the transaction for the given ID or
// it will return nil if it is not known. Just because it is not known does not mean
// it wasn’t included in the blockchain.
func (p *websocketAPI) GetRecentTransactionByID(transactionID uint32) (*types.SignedTransaction, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_recent_transaction_by_id", transactionID)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_recent_transaction_by_id <", resp)
ret := types.SignedTransaction{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Transaction]")
}
return &ret, nil
}
//GetRequiredSignatures returns the minimum subset of public keys to sign a transaction.
func (p *websocketAPI) GetRequiredSignatures(tx *types.SignedTransaction, potKeys types.PublicKeys) (types.PublicKeys, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_required_signatures", tx, potKeys)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_required_signatures <", resp)
ret := types.PublicKeys{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [PublicKeys]")
}
return ret, nil
}
//GetBlock returns a Block by number.
func (p *websocketAPI) GetBlock(block uint64) (*types.Block, error) {
resp, err := p.wsClient.CallAPI(0, "get_block", block)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_block <", resp)
ret := types.Block{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Block]")
}
return &ret, nil
}
// GetBlockHeader returns block header by number.
func (p *websocketAPI) GetBlockHeader(block uint64) (*types.BlockHeader, error) {
resp, err := p.wsClient.CallAPI(0, "get_block_header", block)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_block_header <", resp)
ret := types.BlockHeader{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [BlockHeader]")
}
return &ret, nil
}
// GetTicker returns the ticker for the market base:quote for the last 24 h
func (p *websocketAPI) GetTicker(base, quote types.GrapheneObject) (*types.MarketTicker, error) {
resp, err := p.wsClient.CallAPI(0, "get_ticker", base.ID(), quote.ID())
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_ticker <", resp)
ret := types.MarketTicker{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [MarketTicker]")
}
return &ret, nil
}
//GetAccountByName returns a Account object by username
func (p *websocketAPI) GetAccountByName(name string) (*types.Account, error) {
resp, err := p.wsClient.CallAPI(0, "get_account_by_name", name)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_account_by_name <", resp)
ret := types.Account{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Account]")
}
return &ret, nil
}
func (p *websocketAPI) GetContract(name string) (*types.Contract, error) {
resp, err := p.wsClient.CallAPI(0, "get_contract", name)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
fmt.Println("--------------------------- resp start")
fmt.Println(string(*resp))
fmt.Println("--------------------------- resp end")
// logging.DDumpJSON("get_contract <", resp)
// fmt.Println("get_contract <", resp)
ret := types.Contract{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Contract]")
}
return &ret, nil
}
func (p *websocketAPI) GetWitness(accountID string) (*types.Witness, error) {
resp, err := p.wsClient.CallAPI(0, "get_witness_by_account", accountID)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_witness_by_account <", resp)
ret := types.Witness{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Account]")
}
return &ret, nil
}
func (p *websocketAPI) GetCommitteeMember(accountID string) (*types.CommitteeMember, error) {
resp, err := p.wsClient.CallAPI(0, "get_committee_member_by_account", accountID)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_committee_member_by_account <", resp)
ret := types.CommitteeMember{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Account]")
}
return &ret, nil
}
// GetAccountHistory returns OperationHistory object(s).
// account: The account whose history should be queried
// stop: ID of the earliest operation to retrieve
// limit: Maximum number of operations to retrieve (must not exceed 100)
// start: ID of the most recent operation to retrieve
func (p *websocketAPI) GetAccountHistory(account types.GrapheneObject, stop types.GrapheneObject, limit int, start types.GrapheneObject) (types.OperationHistories, error) {
if limit > GetAccountHistoryLimit {
limit = GetAccountHistoryLimit
}
resp, err := p.wsClient.CallAPI(p.historyAPIID, "get_account_history", account.ID(), stop.ID(), limit, start.ID())
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_account_history <", resp)
ret := types.OperationHistories{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Histories]")
}
return ret, nil
}
//GetAccounts returns a list of accounts by accountID(s).
func (p *websocketAPI) GetAccounts(accounts ...types.GrapheneObject) (types.Accounts, error) {
ids := types.GrapheneObjects(accounts).ToStrings()
resp, err := p.wsClient.CallAPI(0, "get_accounts", ids)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_accounts <", resp)
ret := types.Accounts{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Accounts]")
}
return ret, nil
}
//GetDynamicGlobalProperties returns essential runtime properties of bitshares network
func (p *websocketAPI) GetDynamicGlobalProperties() (*types.DynamicGlobalProperties, error) {
resp, err := p.wsClient.CallAPI(0, "get_dynamic_global_properties", types.EmptyParams)
fmt.Println(resp)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_dynamic_global_properties <", resp)
ret := types.DynamicGlobalProperties{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [DynamicGlobalProperties]")
}
return &ret, nil
}
func (p *websocketAPI) GetChainProperties() (*types.ChainProperty, error) {
resp, err := p.wsClient.CallAPI(0, "get_chain_properties", types.EmptyParams)
fmt.Println(resp)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_chain_properties <", resp)
ret := types.ChainProperty{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [ChainProperty]")
}
return &ret, nil
}
func (p *websocketAPI) GetGlobalProperties() (*types.GlobalProperty, error) {
resp, err := p.wsClient.CallAPI(0, "get_global_properties", types.EmptyParams)
fmt.Println(resp)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_global_properties <", resp)
ret := types.GlobalProperty{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [GlobalProperty]")
}
return &ret, nil
}
//GetAccountBalances retrieves AssetAmounts by given AccountID
func (p *websocketAPI) GetAccountBalances(account types.GrapheneObject, assets ...types.GrapheneObject) (types.AssetAmounts, error) {
ids := types.GrapheneObjects(assets).ToStrings()
resp, err := p.wsClient.CallAPI(0, "get_account_balances", account.ID(), ids)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_account_balances <", resp)
ret := types.AssetAmounts{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [AssetAmounts]")
}
return ret, nil
}
// GetFullAccounts retrieves full account information by given AccountIDs
func (p *websocketAPI) GetFullAccounts(accounts ...types.GrapheneObject) (types.FullAccountInfos, error) {
ids := types.GrapheneObjects(accounts).ToStrings()
resp, err := p.wsClient.CallAPI(0, "get_full_accounts", ids, false) //do not subscribe for now
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_full_accounts <", resp)
ret := types.FullAccountInfos{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [FullAccountInfos]")
}
return ret, nil
}
// Get24Volume returns the base:quote assets 24h volume
func (p *websocketAPI) Get24Volume(base, quote types.GrapheneObject) (*types.Volume24, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_24_volume", base.ID(), quote.ID())
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_24_volume <", resp)
ret := types.Volume24{}
if err = ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Volume24]")
}
return &ret, nil
}
// ListAssets retrieves assets
// lowerBoundSymbol: Lower bound of symbol names to retrieve
// limit: Maximum number of assets to fetch, if the constant AssetsListAll is passed, all existing assets will be retrieved.
func (p *websocketAPI) ListAssets(lowerBoundSymbol string, limit int) (types.Assets, error) {
if limit > AssetsMaxBatchSize {
limit = AssetsMaxBatchSize
}
resp, err := p.wsClient.CallAPI(0, "list_assets", lowerBoundSymbol, limit)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("list_assets <", resp)
ret := types.Assets{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Assets]")
}
return ret, nil
}
// LookupAssetSymbols get assets corresponding to the provided symbols or IDs
func (p *websocketAPI) LookupAssetSymbols(symbols ...string) (types.Assets, error) {
resp, err := p.wsClient.CallAPI(0, "lookup_asset_symbols", symbols)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("lookup_asset_symbols <", resp)
ret := types.Assets{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Assets]")
}
return ret, nil
}
//GetLimitOrders returns LimitOrders type.
func (p *websocketAPI) GetLimitOrders(base, quote types.GrapheneObject, limit int) (types.LimitOrders, error) {
if limit > GetLimitOrdersLimit {
limit = GetLimitOrdersLimit
}
resp, err := p.wsClient.CallAPI(0, "get_limit_orders", base.ID(), quote.ID(), limit)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_limit_orders <", resp)
ret := types.LimitOrders{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [LimitOrders]")
}
return ret, nil
}
// LimitOrderCancel cancels a certain limit order given by orderID. Fees are paid in feeAsset.
// The transaction is signed with private keys in keyBag.
func (p *websocketAPI) LimitOrderCancel(keyBag *crypto.KeyBag, feePayingAccount, orderID types.GrapheneObject) error {
op := operations.LimitOrderCancelOperation{
FeePayingAccount: types.AccountIDFromObject(feePayingAccount),
Order: types.LimitOrderIDFromObject(orderID),
Extensions: types.Extensions{},
}
trx, err := p.BuildSignedTransaction(keyBag, &op)
if err != nil {
return errors.Annotate(err, "BuildSignedTransaction")
}
if err := p.BroadcastTransaction(trx); err != nil {
return errors.Annotate(err, "BroadcastTransaction")
}
return nil
}
//GetOrderBook returns the OrderBook for the market base:quote.
func (p *websocketAPI) GetOrderBook(base, quote types.GrapheneObject, depth int) (*types.OrderBook, error) {
resp, err := p.wsClient.CallAPI(0, "get_order_book", base.ID(), quote.ID(), depth)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_order_book <", resp)
ret := types.OrderBook{}
if err = ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [OrderBook]")
}
return &ret, nil
}
//GetForceSettlementOrders returns ForceSettlementOrders type.
func (p *websocketAPI) GetForceSettlementOrders(assetID types.GrapheneObject, limit int) (types.ForceSettlementOrders, error) {
if limit > GetForceSettlementOrdersLimit {
limit = GetForceSettlementOrdersLimit
}
resp, err := p.wsClient.CallAPI(0, "get_settle_orders", assetID.ID(), limit)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_settle_orders <", resp)
ret := types.ForceSettlementOrders{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [ForceSettlementOrders]")
}
return ret, nil
}
//GetCallOrders returns CallOrders type.
func (p *websocketAPI) GetCallOrders(assetID types.GrapheneObject, limit int) (types.CallOrders, error) {
if limit > GetCallOrdersLimit {
limit = GetCallOrdersLimit
}
resp, err := p.wsClient.CallAPI(0, "get_call_orders", assetID.ID(), limit)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_call_orders <", resp)
ret := types.CallOrders{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [CallOrders]")
}
return ret, nil
}
//GetMarginPositions returns CallOrders type.
func (p *websocketAPI) GetMarginPositions(accountID types.GrapheneObject) (types.CallOrders, error) {
resp, err := p.wsClient.CallAPI(0, "get_margin_positions", accountID.ID())
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_margin_positions <", resp)
ret := types.CallOrders{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [CallOrders]")
}
return ret, nil
}
//GetTradeHistory returns MarketTrades type.
func (p *websocketAPI) GetTradeHistory(base, quote types.GrapheneObject, toTime, fromTime time.Time, limit int) (types.MarketTrades, error) {
if limit > GetTradeHistoryLimit {
limit = GetTradeHistoryLimit
}
resp, err := p.wsClient.CallAPI(0, "get_trade_history", base.ID(), quote.ID(), toTime, fromTime, limit)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_trade_history <", resp)
ret := types.MarketTrades{}
if err := ffjson.Unmarshal(*resp, &ret); err != nil {
return nil, errors.Annotate(err, "Unmarshal [MarketTrades]")
}
return ret, nil
}
//GetChainID returns the ID of the chain we are connected to.
func (p *websocketAPI) GetChainID() (string, error) {
resp, err := p.wsClient.CallAPI(p.databaseAPIID, "get_chain_id", types.EmptyParams)
if err != nil {
return "", errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_chain_id <", resp)
var id string
if err := ffjson.Unmarshal(*resp, &id); err != nil {
return "", errors.Annotate(err, "Unmarshal [id]")
}
return id, nil
}
//GetObjects returns a list of Graphene Objects by ID.
func (p *websocketAPI) GetObjects(ids ...types.GrapheneObject) ([]interface{}, error) {
params := types.GrapheneObjects(ids).ToStrings()
resp, err := p.wsClient.CallAPI(0, "get_objects", params)
if err != nil {
return nil, errors.Annotate(err, "CallAPI")
}
logging.DDumpJSON("get_objects <", resp)
var data []interface{}
if err := ffjson.Unmarshal(*resp, &data); err != nil {
return nil, errors.Annotate(err, "Unmarshal [data]")
}
ret := make([]interface{}, 0)
id := types.ObjectID{}
for _, obj := range data {
if obj == nil {
continue
}
if err := id.FromRawData(obj); err != nil {
return nil, errors.Annotate(err, "from raw data")
}
b := util.ToBytes(obj)
//TODO: implement
// ObjectTypeBase
// ObjectTypeWitness
// ObjectTypeCustom
// ObjectTypeProposal
// ObjectTypeWithdrawPermission
// ObjectTypeWorker
switch id.SpaceType() {
case types.SpaceTypeProtocol:
switch id.ObjectType() {
case types.ObjectTypeVestingBalance:
t := types.VestingBalance{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [VestingBalance]")
}
ret = append(ret, t)
case types.ObjectTypeAccount:
t := types.Account{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Account]")
}
ret = append(ret, t)
case types.ObjectTypeAsset:
t := types.Asset{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Asset]")
}
ret = append(ret, t)
case types.ObjectTypeForceSettlement:
t := types.ForceSettlementOrder{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [ForceSettlementOrder]")
}
ret = append(ret, t)
case types.ObjectTypeLimitOrder:
t := types.LimitOrder{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [LimitOrder]")
}
ret = append(ret, t)
case types.ObjectTypeCallOrder:
t := types.CallOrder{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [CallOrder]")
}
ret = append(ret, t)
case types.ObjectTypeCommitteeMember:
t := types.CommitteeMember{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [CommitteeMember]")
}
ret = append(ret, t)
case types.ObjectTypeOperationHistory:
t := types.OperationHistory{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [OperationHistory]")
}
ret = append(ret, t)
case types.ObjectTypeBalance:
t := types.Balance{}
if err := t.UnmarshalJSON(b); err != nil {
return nil, errors.Annotate(err, "Unmarshal [Balance]")
}
ret = append(ret, t)
default:
logging.DDumpUnmarshaled(id.ObjectType().String(), b)
return nil, errors.Errorf("unable to parse Object with ID %s", id)
}
// TODO: implement