/
api.go
2052 lines (1784 loc) · 64.9 KB
/
api.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 blockchain
import (
"bytes"
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"strings"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/noxiouz/zapctx/ctxlog"
marketAPI "github.com/sonm-io/core/blockchain/source/api"
sonm "github.com/sonm-io/core/proto"
"github.com/sonm-io/core/util"
"go.uber.org/zap"
)
const (
txRetryTimes = 20
txRetryDelayTime = 100 * time.Millisecond
//TODO: make configurable
blockGenPeriod = 4 * time.Second
)
type API interface {
ProfileRegistry() ProfileRegistryAPI
Events() EventsAPI
Market() MarketAPI
Blacklist() BlacklistAPI
MasterchainToken() TokenAPI
SidechainToken() TokenAPI
OracleUSD() OracleAPI
MasterchainGate() SimpleGatekeeperAPI
SidechainGate() SimpleGatekeeperAPI
OracleMultiSig() MultiSigAPI
ContractRegistry() ContractRegistry
}
type ContractRegistry interface {
SidechainSNMAddress() common.Address
MasterchainSNMAddress() common.Address
BlacklistAddress() common.Address
MarketAddress() common.Address
ProfileRegistryAddress() common.Address
OracleUsdAddress() common.Address
GatekeeperMasterchainAddress() common.Address
GatekeeperSidechainAddress() common.Address
TestnetFaucetAddress() common.Address
OracleMultiSig() common.Address
}
type ProfileRegistryAPI interface {
AddValidator(ctx context.Context, key *ecdsa.PrivateKey, validator common.Address, level int8) (*types.Transaction, error)
RemoveValidator(ctx context.Context, key *ecdsa.PrivateKey, validator common.Address) (*types.Transaction, error)
GetValidator(ctx context.Context, validatorID common.Address) (*sonm.Validator, error)
GetValidatorLevel(ctx context.Context, validatorID common.Address) (int8, error)
CreateCertificate(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address, attributeType *big.Int, value []byte) (*types.Transaction, error)
RemoveCertificate(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error
GetCertificate(ctx context.Context, certificateID *big.Int) (*sonm.Certificate, error)
GetAttributeCount(ctx context.Context, owner common.Address, attributeType *big.Int) (*big.Int, error)
GetAttributeValue(ctx context.Context, owner common.Address, attributeType *big.Int) ([]byte, error)
GetProfileLevel(ctx context.Context, owner common.Address) (sonm.IdentityLevel, error)
}
type EventsAPI interface {
GetEvents(ctx context.Context, filter *EventFilter) (chan *Event, error)
GetLastBlock(ctx context.Context) (uint64, error)
GetMarketFilter(fromBlock *big.Int) *EventFilter
GetMultiSigFilter(addresses []common.Address, fromBlock *big.Int) *EventFilter
}
type MarketAPI interface {
QuickBuy(ctx context.Context, key *ecdsa.PrivateKey, askId *big.Int, duration uint64) (*sonm.Deal, error)
OpenDeal(ctx context.Context, key *ecdsa.PrivateKey, askID, bigID *big.Int) (*sonm.Deal, error)
CloseDeal(ctx context.Context, key *ecdsa.PrivateKey, dealID *big.Int, blacklistType sonm.BlacklistType) error
GetDealInfo(ctx context.Context, dealID *big.Int) (*sonm.Deal, error)
GetDealsAmount(ctx context.Context) (*big.Int, error)
PlaceOrder(ctx context.Context, key *ecdsa.PrivateKey, order *sonm.Order) (*sonm.Order, error)
CancelOrder(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error
GetOrderInfo(ctx context.Context, orderID *big.Int) (*sonm.Order, error)
GetOrdersAmount(ctx context.Context) (*big.Int, error)
Bill(ctx context.Context, key *ecdsa.PrivateKey, dealID *big.Int) error
RegisterWorker(ctx context.Context, key *ecdsa.PrivateKey, master common.Address) error
ConfirmWorker(ctx context.Context, key *ecdsa.PrivateKey, slave common.Address) error
RemoveWorker(ctx context.Context, key *ecdsa.PrivateKey, master, slave common.Address) error
GetMaster(ctx context.Context, slave common.Address) (common.Address, error)
GetDealChangeRequestInfo(ctx context.Context, id *big.Int) (*sonm.DealChangeRequest, error)
CreateChangeRequest(ctx context.Context, key *ecdsa.PrivateKey, request *sonm.DealChangeRequest) (*big.Int, error)
CancelChangeRequest(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error
GetNumBenchmarks(ctx context.Context) (uint64, error)
}
type BlacklistAPI interface {
Check(ctx context.Context, who, whom common.Address) (bool, error)
Add(ctx context.Context, key *ecdsa.PrivateKey, who, whom common.Address) (*types.Transaction, error)
Remove(ctx context.Context, key *ecdsa.PrivateKey, whom common.Address) error
AddMaster(ctx context.Context, key *ecdsa.PrivateKey, root common.Address) (*types.Transaction, error)
RemoveMaster(ctx context.Context, key *ecdsa.PrivateKey, root common.Address) (*types.Transaction, error)
SetMarketAddress(ctx context.Context, key *ecdsa.PrivateKey, market common.Address) (*types.Transaction, error)
}
// TokenAPI is a go implementation of ERC20-compatibility token with full functionality high-level interface
// standard description with placed: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
type TokenAPI interface {
// Approve allows managing some amount of your tokens by given address.
// Note that setting an allowance value is prohibited if current allowance value is non-zero.
// This behavior will persist until migrate our token to the ERC827 standard.
// You're forced to reset current allowance value for your address, then set a new value.
// This method performs resetting an old allowance value and setting a new one.
Approve(ctx context.Context, key *ecdsa.PrivateKey, to common.Address, amount *big.Int) error
// ApproveAtLeast acts as Approve, but change allowance only if it less than required.
ApproveAtLeast(ctx context.Context, key *ecdsa.PrivateKey, to common.Address, amount *big.Int) error
// Transfer token from caller
Transfer(ctx context.Context, key *ecdsa.PrivateKey, to common.Address, amount *big.Int) error
// TransferFrom fallback function for contracts to transfer you allowance
TransferFrom(ctx context.Context, key *ecdsa.PrivateKey, from common.Address, to common.Address, amount *big.Int) (*types.Transaction, error)
// BalanceOf returns balance of given address
BalanceOf(ctx context.Context, address common.Address) (*Balance, error)
// AllowanceOf returns allowance of given address to spender account
AllowanceOf(ctx context.Context, from, to common.Address) (*big.Int, error)
// TotalSupply - all amount of emitted token
TotalSupply(ctx context.Context) (*big.Int, error)
// IncreaseApproval increase the amount of tokens that an owner allowed to a spender
// approve should be called when current allowance = 0. To increment
// allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
IncreaseApproval(ctx context.Context, key *ecdsa.PrivateKey, spender common.Address, value *big.Int) error
// DecreaseApproval - decrease the amount of tokens that an owner allowed to a spender
// approve should be called when current allowance = 0. To decrement
// allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)
DecreaseApproval(ctx context.Context, key *ecdsa.PrivateKey, spender common.Address, value *big.Int) error
}
// OracleAPI manage price relation between some currency and SNM token
type OracleAPI interface {
// SetCurrentPrice sets current price relation between some currency and SONM token
SetCurrentPrice(ctx context.Context, key *ecdsa.PrivateKey, price *big.Int) (*types.Transaction, error)
// GetCurrentPrice returns current price relation between some currency and SONM token
GetCurrentPrice(ctx context.Context) (*big.Int, error)
// PackSetCurrentPriceTransactionData pack `SetCurrentPrice` method call
PackSetCurrentPriceTransactionData(price *big.Int) ([]byte, error)
// UnpackSetCurrentPriceTransactionData unpack `SetCurrentPrice` method call
UnpackSetCurrentPriceTransactionData(data []byte) (*big.Int, error)
// GetOwner get owner address
GetOwner(ctx context.Context) (common.Address, error)
// SetOwner set owner address, owner can change oracle price
SetOwner(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address) error
}
// SimpleGatekeeperAPI facade to interact with deposit/withdraw functions through gates
type SimpleGatekeeperAPI interface {
// PayIn grab sender tokens and signal gate to transfer it to mirrored chain.
// On Masterchain ally as `Deposit`
// On Sidecain ally as `Withdraw`
PayIn(ctx context.Context, key *ecdsa.PrivateKey, value *big.Int) error
// Payout release payout transaction from mirrored chain.
// Accessible only by owner.
Payout(ctx context.Context, key *ecdsa.PrivateKey, to common.Address, value *big.Int, txNumber *big.Int) (*types.Transaction, error)
// Kill calls contract to suicide, all ether and tokens funds transfer to owner.
// Accessible only by owner.
Kill(ctx context.Context, key *ecdsa.PrivateKey) (*types.Transaction, error)
}
type MultiSigAPI interface {
AddOwner(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address) error
RemoveOwner(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address) error
ReplaceOwner(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address, newOwner common.Address) error
ChangeRequirement(ctx context.Context, key *ecdsa.PrivateKey, required *big.Int) error
SubmitTransaction(ctx context.Context, key *ecdsa.PrivateKey, destination common.Address, value *big.Int, data []byte) error
ConfirmTransaction(ctx context.Context, key *ecdsa.PrivateKey, transactionID *big.Int) error
RevokeConfirmation(ctx context.Context, key *ecdsa.PrivateKey, transactionID *big.Int) error
ExecuteTransaction(ctx context.Context, key *ecdsa.PrivateKey, transactionID *big.Int) error
IsConfirmed(ctx context.Context, transactionID *big.Int) (bool, error)
GetConfirmationCount(ctx context.Context, transactionID *big.Int) (*big.Int, error)
GetTransactionCount(ctx context.Context, penging bool, executed bool) (*big.Int, error)
GetOwners(ctx context.Context) ([]common.Address, error)
GetConfirmations(ctx context.Context, transactionID *big.Int) ([]common.Address, error)
GetTransactionIDs(ctx context.Context, from *big.Int, to *big.Int, pending bool, executed bool) ([]*big.Int, error)
GetTransaction(ctx context.Context, transactionID *big.Int) (*MultiSigTransactionData, error)
}
type BasicAPI struct {
options *options
contractRegistry ContractRegistry
masterchainToken TokenAPI
sidechainToken TokenAPI
blacklist BlacklistAPI
market MarketAPI
profileRegistry ProfileRegistryAPI
events EventsAPI
oracle OracleAPI
masterchainGate SimpleGatekeeperAPI
sidechainGate SimpleGatekeeperAPI
oracleMultiSig MultiSigAPI
}
func NewAPI(ctx context.Context, opts ...Option) (API, error) {
defaults := defaultOptions()
for _, o := range opts {
o(defaults)
}
api := &BasicAPI{options: defaults}
setup := []func(ctx context.Context) error{
api.setupContractRegistry,
api.setupMasterchainToken,
api.setupSidechainToken,
api.setupBlacklist,
api.setupMarket,
api.setupProfileRegistry,
api.setupEvents,
api.setupOracle,
api.setupMasterchainGate,
api.setupSidechainGate,
api.setupOracleMultiSig,
}
for _, setupFunc := range setup {
if err := setupFunc(ctx); err != nil {
return nil, err
}
}
return api, nil
}
func (api *BasicAPI) setupContractRegistry(ctx context.Context) error {
registry, err := NewRegistry(ctx, api.options.contractRegistry, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup contract registry: %s", err)
}
api.contractRegistry = registry
return nil
}
func (api *BasicAPI) setupMasterchainToken(ctx context.Context) error {
masterchainTokenAddr := api.contractRegistry.MasterchainSNMAddress()
masterchainToken, err := NewStandardToken(masterchainTokenAddr, api.options.masterchain)
if err != nil {
return fmt.Errorf("failed to setup masterchain token: %s", err)
}
api.masterchainToken = masterchainToken
return nil
}
func (api *BasicAPI) setupSidechainToken(ctx context.Context) error {
sidechainTokenAddr := api.contractRegistry.SidechainSNMAddress()
sidechainToken, err := NewStandardToken(sidechainTokenAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup sidechain token: %s", err)
}
api.sidechainToken = sidechainToken
return nil
}
func (api *BasicAPI) setupBlacklist(ctx context.Context) error {
blacklistAddr := api.contractRegistry.BlacklistAddress()
blacklist, err := NewBasicBlacklist(blacklistAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup blacklist: %s", err)
}
api.blacklist = blacklist
return nil
}
func (api *BasicAPI) setupMarket(ctx context.Context) error {
marketAddr := api.contractRegistry.MarketAddress()
market, err := NewBasicMarket(marketAddr, api.sidechainToken, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup market: %s", err)
}
api.market = market
return nil
}
func (api *BasicAPI) setupProfileRegistry(ctx context.Context) error {
profileRegistryAddr := api.contractRegistry.ProfileRegistryAddress()
profileRegistry, err := NewProfileRegistry(profileRegistryAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup profile registry: %s", err)
}
api.profileRegistry = profileRegistry
return nil
}
func (api *BasicAPI) setupEvents(ctx context.Context) error {
events, err := NewEventsAPI(api, api.options.sidechain, ctxlog.GetLogger(ctx), api.options.blocksBatchSize)
if err != nil {
return fmt.Errorf("failed to setup events: %s", err)
}
api.events = events
return nil
}
func (api *BasicAPI) setupOracle(ctx context.Context) error {
oracleAddr := api.contractRegistry.OracleUsdAddress()
oracle, err := NewOracleUSDAPI(oracleAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup oracle: %s", err)
}
api.oracle = oracle
return nil
}
func (api *BasicAPI) setupOracleMultiSig(ctx context.Context) error {
multiSigAddr := api.contractRegistry.OracleMultiSig()
oracleMultiSig, err := NewMultiSigAPI(multiSigAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup oracle: %s", err)
}
api.oracleMultiSig = oracleMultiSig
return nil
}
func (api *BasicAPI) setupMasterchainGate(ctx context.Context) error {
gatekeeperMasterchainAddr := api.contractRegistry.GatekeeperMasterchainAddress()
masterchainGate, err := NewSimpleGatekeeper(gatekeeperMasterchainAddr, api.options.masterchain)
if err != nil {
return fmt.Errorf("failed to setup masterchain gatekeeper: %s", err)
}
api.masterchainGate = masterchainGate
return nil
}
func (api *BasicAPI) setupSidechainGate(ctx context.Context) error {
gatekeeperSidechainAddr := api.contractRegistry.GatekeeperSidechainAddress()
sidechainGate, err := NewSimpleGatekeeper(gatekeeperSidechainAddr, api.options.sidechain)
if err != nil {
return fmt.Errorf("failed to setup sidechain gatekeeper: %s", err)
}
api.sidechainGate = sidechainGate
return nil
}
func (api *BasicAPI) Market() MarketAPI {
if api.options.niceMarket {
return &niceMarketAPI{
MarketAPI: api.market,
profiles: api.profileRegistry,
blacklist: api.blacklist,
}
}
return api.market
}
func (api *BasicAPI) MasterchainToken() TokenAPI {
return api.masterchainToken
}
func (api *BasicAPI) SidechainToken() TokenAPI {
return api.sidechainToken
}
func (api *BasicAPI) Blacklist() BlacklistAPI {
return api.blacklist
}
func (api *BasicAPI) ProfileRegistry() ProfileRegistryAPI {
return api.profileRegistry
}
func (api *BasicAPI) Events() EventsAPI {
return api.events
}
func (api *BasicAPI) OracleUSD() OracleAPI {
return api.oracle
}
func (api *BasicAPI) OracleMultiSig() MultiSigAPI {
return api.oracleMultiSig
}
func (api *BasicAPI) MasterchainGate() SimpleGatekeeperAPI {
return api.masterchainGate
}
func (api *BasicAPI) SidechainGate() SimpleGatekeeperAPI {
return api.sidechainGate
}
func (api *BasicAPI) ContractRegistry() ContractRegistry {
return api.contractRegistry
}
func NewRegistry(ctx context.Context, address common.Address, opts *chainOpts) (*BasicContractRegistry, error) {
client, err := opts.getClient()
if err != nil {
return nil, err
}
contract, err := marketAPI.NewAddressHashMap(address, client)
if err != nil {
return nil, err
}
registry := &BasicContractRegistry{
registryContract: contract,
}
if err := registry.setup(ctx); err != nil {
return nil, err
}
return registry, nil
}
type BasicContractRegistry struct {
sidechainSNMAddress common.Address
masterchainSNMAddress common.Address
blacklistAddress common.Address
marketAddress common.Address
profileRegistryAddress common.Address
oracleUsdAddress common.Address
gatekeeperMasterchainAddress common.Address
gatekeeperSidechainAddress common.Address
testnetFaucetAddress common.Address
oracleMultiSigAddress common.Address
registryContract *marketAPI.AddressHashMap
}
func registryKey(key string) [32]byte {
if len(key) > 32 {
panic("registry key exceeds 32 byte limit")
}
result := [32]byte{}
copy(result[:], key)
return result
}
func (m *BasicContractRegistry) readContract(ctx context.Context, key string, target *common.Address) error {
data, err := m.registryContract.Read(getCallOptions(ctx), registryKey(key))
if err != nil {
return err
}
*target = data
return nil
}
func (m *BasicContractRegistry) setup(ctx context.Context) error {
addresses := []struct {
key string
target *common.Address
}{
{sidechainSNMAddressKey, &m.sidechainSNMAddress},
{masterchainSNMAddressKey, &m.masterchainSNMAddress},
{blacklistAddressKey, &m.blacklistAddress},
{marketAddressKey, &m.marketAddress},
{profileRegistryAddressKey, &m.profileRegistryAddress},
{oracleUsdAddressKey, &m.oracleUsdAddress},
{gatekeeperMasterchainAddressKey, &m.gatekeeperMasterchainAddress},
{gatekeeperSidechainAddressKey, &m.gatekeeperSidechainAddress},
{testnetFaucetAddressKey, &m.testnetFaucetAddress},
{oracleMultiSigAddressKey, &m.oracleMultiSigAddress},
}
for _, param := range addresses {
if err := m.readContract(ctx, param.key, param.target); err != nil {
return err
}
ctxlog.S(ctx).Infof("fetched `%s` contract address: %s", param.key, param.target.String())
}
return nil
}
func (m *BasicContractRegistry) SidechainSNMAddress() common.Address {
return m.sidechainSNMAddress
}
func (m *BasicContractRegistry) MasterchainSNMAddress() common.Address {
return m.masterchainSNMAddress
}
func (m *BasicContractRegistry) BlacklistAddress() common.Address {
return m.blacklistAddress
}
func (m *BasicContractRegistry) MarketAddress() common.Address {
return m.marketAddress
}
func (m *BasicContractRegistry) ProfileRegistryAddress() common.Address {
return m.profileRegistryAddress
}
func (m *BasicContractRegistry) OracleUsdAddress() common.Address {
return m.oracleUsdAddress
}
func (m *BasicContractRegistry) GatekeeperMasterchainAddress() common.Address {
return m.gatekeeperMasterchainAddress
}
func (m *BasicContractRegistry) GatekeeperSidechainAddress() common.Address {
return m.gatekeeperSidechainAddress
}
func (m *BasicContractRegistry) TestnetFaucetAddress() common.Address {
return m.testnetFaucetAddress
}
func (m *BasicContractRegistry) OracleMultiSig() common.Address {
return m.oracleMultiSigAddress
}
type BasicMarketAPI struct {
client CustomEthereumClient
token TokenAPI
marketContractAddr common.Address
marketContract *marketAPI.Market
opts *chainOpts
}
func NewBasicMarket(address common.Address, token TokenAPI, opts *chainOpts) (MarketAPI, error) {
client, err := opts.getClient()
if err != nil {
return nil, err
}
marketContract, err := marketAPI.NewMarket(address, client)
if err != nil {
return nil, err
}
return &BasicMarketAPI{
client: client,
token: token,
marketContractAddr: address,
marketContract: marketContract,
opts: opts,
}, nil
}
func txRetryWrapper(fn func() (*types.Transaction, error)) (*types.Transaction, error) {
var err error
var tx *types.Transaction
for i := 0; i < txRetryTimes; i++ {
tx, err = fn()
if err == nil {
break
} else {
if err.Error() != "replacement transaction underpriced" &&
err.Error() != "nonce too low" &&
!strings.Contains(err.Error(), "known transaction:") {
break
} else {
time.Sleep(txRetryDelayTime)
}
}
}
return tx, err
}
func (api *BasicMarketAPI) checkAllowance(ctx context.Context, key *ecdsa.PrivateKey) error {
maxAllowance := big.NewInt(1)
maxAllowance = maxAllowance.Lsh(maxAllowance, 256)
maxAllowance = maxAllowance.Sub(maxAllowance, big.NewInt(1))
minAllowance := big.NewInt(0).Div(maxAllowance, big.NewInt(2))
curAllowance, err := api.token.AllowanceOf(ctx, crypto.PubkeyToAddress(key.PublicKey), api.marketContractAddr)
if err != nil {
return fmt.Errorf("failed to get allowance: %s", err)
}
if curAllowance.Cmp(minAllowance) < 0 {
if err := api.token.Approve(ctx, key, api.marketContractAddr, maxAllowance); err != nil {
return fmt.Errorf("failed to set allowance: %s", err)
}
}
return nil
}
func (api *BasicMarketAPI) QuickBuy(ctx context.Context, key *ecdsa.PrivateKey, askId *big.Int, duration uint64) (*sonm.Deal, error) {
if err := api.checkAllowance(ctx, key); err != nil {
return nil, err
}
opts := api.opts.getTxOpts(ctx, key, quickBuyGasLimit)
tx, err := api.marketContract.QuickBuy(opts, askId, big.NewInt(0).SetUint64(duration))
if err != nil {
return nil, err
}
return api.extractOpenDealData(ctx, tx)
}
func (api *BasicMarketAPI) OpenDeal(ctx context.Context, key *ecdsa.PrivateKey, askID, bidID *big.Int) (*sonm.Deal, error) {
opts := api.opts.getTxOpts(ctx, key, openDealGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.OpenDeal(opts, askID, bidID)
})
if err != nil {
return nil, err
}
return api.extractOpenDealData(ctx, tx)
}
func (api *BasicMarketAPI) extractOpenDealData(ctx context.Context, tx *types.Transaction) (*sonm.Deal, error) {
logs, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, DealOpenedTopic)
if err != nil {
return nil, err
}
id, err := extractBig(logs.Topics, 1)
if err != nil {
return nil, err
}
return api.GetDealInfo(ctx, id)
}
func (api *BasicMarketAPI) CloseDeal(ctx context.Context, key *ecdsa.PrivateKey, dealID *big.Int, blacklistType sonm.BlacklistType) error {
if err := api.checkAllowance(ctx, key); err != nil {
return err
}
opts := api.opts.getTxOpts(ctx, key, closeDealGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.CloseDeal(opts, dealID, uint8(blacklistType))
})
if err != nil {
return err
}
if _, err = WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, DealUpdatedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) GetDealInfo(ctx context.Context, dealID *big.Int) (*sonm.Deal, error) {
deal1, err := api.marketContract.GetDealInfo(getCallOptions(ctx), dealID)
if err != nil {
return nil, err
}
noAsk := deal1.AskID.Cmp(big.NewInt(0)) == 0
noBid := deal1.BidID.Cmp(big.NewInt(0)) == 0
if noAsk && noBid {
return nil, fmt.Errorf("no deal with id = %s", dealID.String())
}
deal2, err := api.marketContract.GetDealParams(getCallOptions(ctx), dealID)
if err != nil {
return nil, err
}
if deal2.Status == 0 {
return nil, fmt.Errorf("deal fetching inconsistency for deal %s", dealID.String())
}
benchmarks, err := sonm.NewBenchmarks(deal1.Benchmarks)
if err != nil {
return nil, err
}
return &sonm.Deal{
Id: sonm.NewBigInt(dealID),
Benchmarks: benchmarks,
SupplierID: sonm.NewEthAddress(deal1.SupplierID),
ConsumerID: sonm.NewEthAddress(deal1.ConsumerID),
MasterID: sonm.NewEthAddress(deal1.MasterID),
AskID: sonm.NewBigInt(deal1.AskID),
BidID: sonm.NewBigInt(deal1.BidID),
Duration: deal2.Duration.Uint64(),
Price: sonm.NewBigInt(deal2.Price),
StartTime: &sonm.Timestamp{Seconds: deal1.StartTime.Int64()},
EndTime: &sonm.Timestamp{Seconds: deal2.EndTime.Int64()},
Status: sonm.DealStatus(deal2.Status),
BlockedBalance: sonm.NewBigInt(deal2.BlockedBalance),
TotalPayout: sonm.NewBigInt(deal2.TotalPayout),
LastBillTS: &sonm.Timestamp{Seconds: deal2.LastBillTS.Int64()},
}, nil
}
func (api *BasicMarketAPI) GetDealsAmount(ctx context.Context) (*big.Int, error) {
return api.marketContract.GetDealsAmount(getCallOptions(ctx))
}
func (api *BasicMarketAPI) PlaceOrder(ctx context.Context, key *ecdsa.PrivateKey, order *sonm.Order) (*sonm.Order, error) {
if err := api.checkAllowance(ctx, key); err != nil {
return nil, err
}
opts := api.opts.getTxOpts(ctx, key, placeOrderGasLimit)
var fixedTag [32]byte
copy(fixedTag[:], order.Tag[:])
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.PlaceOrder(opts,
uint8(order.OrderType),
order.CounterpartyID.Unwrap(),
big.NewInt(int64(order.Duration)),
order.Price.Unwrap(),
order.Netflags.ToBoolSlice(),
uint8(order.IdentityLevel),
common.HexToAddress(order.Blacklist),
fixedTag,
order.GetBenchmarks().ToArray())
})
if err != nil {
return nil, err
}
logs, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, OrderPlacedTopic)
if err != nil {
return nil, err
}
id, err := extractBig(logs.Topics, 1)
if err != nil {
return nil, err
}
return api.GetOrderInfo(ctx, id)
}
func (api *BasicMarketAPI) CancelOrder(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error {
opts := api.opts.getTxOpts(ctx, key, cancelOrderGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.CancelOrder(opts, id)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, OrderUpdatedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) GetOrderInfo(ctx context.Context, orderID *big.Int) (*sonm.Order, error) {
order1, err := api.marketContract.GetOrderInfo(getCallOptions(ctx), orderID)
if err != nil {
return nil, err
}
noAuthor := order1.Author.Big().Cmp(big.NewInt(0)) == 0
noType := sonm.OrderType(order1.OrderType) == sonm.OrderType_ANY
if noAuthor && noType {
return nil, fmt.Errorf("no order with id = %s", orderID.String())
}
order2, err := api.marketContract.GetOrderParams(getCallOptions(ctx), orderID)
if err != nil {
return nil, err
}
if order2.OrderStatus == 0 {
return nil, fmt.Errorf("order fetching inconsistency for order %s", orderID.String())
}
netflags := sonm.NetFlagsFromBoolSlice(order1.Netflags[:])
benchmarks, err := sonm.NewBenchmarks(order1.Benchmarks)
if err != nil {
return nil, err
}
return &sonm.Order{
Id: sonm.NewBigInt(orderID),
DealID: sonm.NewBigInt(order2.DealID),
OrderType: sonm.OrderType(order1.OrderType),
OrderStatus: sonm.OrderStatus(order2.OrderStatus),
AuthorID: sonm.NewEthAddress(order1.Author),
CounterpartyID: sonm.NewEthAddress(order1.Counterparty),
Duration: order1.Duration.Uint64(),
Price: sonm.NewBigInt(order1.Price),
Netflags: netflags,
IdentityLevel: sonm.IdentityLevel(order1.IdentityLevel),
Blacklist: order1.Blacklist.String(),
Tag: order1.Tag[:],
Benchmarks: benchmarks,
FrozenSum: sonm.NewBigInt(order1.FrozenSum),
}, nil
}
func (api *BasicMarketAPI) GetOrdersAmount(ctx context.Context) (*big.Int, error) {
return api.marketContract.GetOrdersAmount(getCallOptions(ctx))
}
func (api *BasicMarketAPI) Bill(ctx context.Context, key *ecdsa.PrivateKey, dealID *big.Int) error {
if err := api.checkAllowance(ctx, key); err != nil {
return err
}
opts := api.opts.getTxOpts(ctx, key, billGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.Bill(opts, dealID)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, BilledTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) RegisterWorker(ctx context.Context, key *ecdsa.PrivateKey, master common.Address) error {
opts := api.opts.getTxOpts(ctx, key, registerWorkerGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.RegisterWorker(opts, master)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, WorkerAnnouncedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) ConfirmWorker(ctx context.Context, key *ecdsa.PrivateKey, slave common.Address) error {
opts := api.opts.getTxOpts(ctx, key, confirmWorkerGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.ConfirmWorker(opts, slave)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, WorkerConfirmedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) RemoveWorker(ctx context.Context, key *ecdsa.PrivateKey, master, slave common.Address) error {
opts := api.opts.getTxOpts(ctx, key, removeWorkerGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.RemoveWorker(opts, master, slave)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, WorkerRemovedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) GetMaster(ctx context.Context, slave common.Address) (common.Address, error) {
return api.marketContract.GetMaster(getCallOptions(ctx), slave)
}
func (api *BasicMarketAPI) GetDealChangeRequestInfo(ctx context.Context, changeRequestID *big.Int) (*sonm.DealChangeRequest, error) {
changeRequest, err := api.marketContract.GetChangeRequestInfo(getCallOptions(ctx), changeRequestID)
if err != nil {
return nil, err
}
return &sonm.DealChangeRequest{
Id: sonm.NewBigInt(changeRequestID),
DealID: sonm.NewBigInt(changeRequest.DealID),
RequestType: sonm.OrderType(changeRequest.RequestType),
Duration: changeRequest.Duration.Uint64(),
Price: sonm.NewBigInt(changeRequest.Price),
Status: sonm.ChangeRequestStatus(changeRequest.Status),
}, nil
}
func (api *BasicMarketAPI) CreateChangeRequest(ctx context.Context, key *ecdsa.PrivateKey, req *sonm.DealChangeRequest) (*big.Int, error) {
if err := api.checkAllowance(ctx, key); err != nil {
return nil, err
}
duration := big.NewInt(int64(req.GetDuration()))
opts := api.opts.getTxOpts(ctx, key, createChangeRequestGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.CreateChangeRequest(opts, req.GetDealID().Unwrap(), req.GetPrice().Unwrap(), duration)
})
if err != nil {
return nil, err
}
logs, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, DealChangeRequestSentTopic)
if err != nil {
return nil, err
}
id, err := extractBig(logs.Topics, 1)
if err != nil {
return nil, fmt.Errorf("cannot extract change request id from transaction logs: %v", err)
}
return id, nil
}
func (api *BasicMarketAPI) CancelChangeRequest(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error {
opts := api.opts.getTxOpts(ctx, key, cancelChangeRequestGasLimit)
tx, err := txRetryWrapper(func() (*types.Transaction, error) {
return api.marketContract.CancelChangeRequest(opts, id)
})
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, DealChangeRequestUpdatedTopic); err != nil {
return err
}
return nil
}
func (api *BasicMarketAPI) GetNumBenchmarks(ctx context.Context) (uint64, error) {
num, err := api.marketContract.GetBenchmarksQuantity(getCallOptions(ctx))
if err != nil {
return 0, err
}
if !num.IsUint64() {
return 0, errors.New("benchmarks quantity overflows int64")
}
return num.Uint64(), nil
}
type ProfileRegistry struct {
client CustomEthereumClient
profileRegistryContract *marketAPI.ProfileRegistry
opts *chainOpts
}
func NewProfileRegistry(address common.Address, opts *chainOpts) (ProfileRegistryAPI, error) {
client, err := opts.getClient()
if err != nil {
return nil, err
}
profileRegistryContract, err := marketAPI.NewProfileRegistry(address, client)
if err != nil {
return nil, err
}
return &ProfileRegistry{
client: client,
profileRegistryContract: profileRegistryContract,
opts: opts,
}, nil
}
func (api *ProfileRegistry) CreateCertificate(ctx context.Context, key *ecdsa.PrivateKey, owner common.Address, attributeType *big.Int, value []byte) (*types.Transaction, error) {
opts := api.opts.getTxOpts(ctx, key, api.opts.gasLimit)
return api.profileRegistryContract.CreateCertificate(opts, owner, attributeType, value)
}
func (api *ProfileRegistry) RemoveCertificate(ctx context.Context, key *ecdsa.PrivateKey, id *big.Int) error {
opts := api.opts.getTxOpts(ctx, key, api.opts.gasLimit)
tx, err := api.profileRegistryContract.RemoveCertificate(opts, id)
if err != nil {
return err
}
if _, err := WaitTxAndExtractLog(ctx, api.client, api.opts.blockConfirmations, api.opts.logParsePeriod, tx, CertificateUpdatedTopic); err != nil {
return err
}
return nil
}
func (api *ProfileRegistry) AddValidator(ctx context.Context, key *ecdsa.PrivateKey, validator common.Address, level int8) (*types.Transaction, error) {
opts := api.opts.getTxOpts(ctx, key, api.opts.gasLimit)
return api.profileRegistryContract.AddValidator(opts, validator, level)
}
func (api *ProfileRegistry) GetValidatorLevel(ctx context.Context, validatorID common.Address) (int8, error) {
return api.profileRegistryContract.GetValidatorLevel(getCallOptions(ctx), validatorID)
}
func (api *ProfileRegistry) RemoveValidator(ctx context.Context, key *ecdsa.PrivateKey, validator common.Address) (*types.Transaction, error) {
opts := api.opts.getTxOpts(ctx, key, api.opts.gasLimit)
return api.profileRegistryContract.RemoveValidator(opts, validator)
}
func (api *ProfileRegistry) GetAttributeCount(ctx context.Context, owner common.Address, attributeType *big.Int) (*big.Int, error) {
return api.profileRegistryContract.GetAttributeCount(getCallOptions(ctx), owner, attributeType)
}
func (api *ProfileRegistry) GetAttributeValue(ctx context.Context, owner common.Address, attributeType *big.Int) ([]byte, error) {
return api.profileRegistryContract.GetAttributeValue(getCallOptions(ctx), owner, attributeType)
}
func (api *ProfileRegistry) GetProfileLevel(ctx context.Context, owner common.Address) (sonm.IdentityLevel, error) {
lev, err := api.profileRegistryContract.GetProfileLevel(getCallOptions(ctx), owner)
if err != nil {
return sonm.IdentityLevel_UNKNOWN, fmt.Errorf("failed to get profile level: %s", err)
}
return sonm.IdentityLevel(lev), err