-
Notifications
You must be signed in to change notification settings - Fork 1
/
sdk.go
88 lines (83 loc) · 1.89 KB
/
sdk.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
package sdk
import (
"fmt"
"math/big"
"runtime/debug"
"time"
"github.com/XunleiBlockchain/tc-libs/accounts"
"github.com/XunleiBlockchain/tc-libs/accounts/keystore"
"github.com/XunleiBlockchain/tc-libs/common"
)
// ------------------------------- SDK Impl -------------------------------
type SDKImpl struct {
cfg *Config
am *accounts.Manager
signParam *big.Int
gasPrice *big.Int
nonceLock *addrLocker
c *client
}
// NewSDK return a pointer to SDKImpl
func NewSDK(cfg *Config, log Logger) (*SDKImpl, error) {
sdklog = log
// 1. account manager
am, err := makeAccountManager(cfg.Keystore)
if err != nil {
return nil, fmt.Errorf("New: makeAccountManager error: %v", err)
}
// 2. keystore
ks := am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
for addr, passwd := range cfg.UnlockAccounts {
acc := accounts.Account{Address: common.HexToAddress(addr)}
_, err = am.Find(acc)
if err != nil {
continue
}
err = ks.Unlock(acc, passwd)
debug.FreeOSMemory()
if err != nil {
continue
}
}
// 3. get client
cli, err := newClient(cfg)
if err != nil {
return nil, fmt.Errorf("New: newClient error: %v", err)
}
// 3. get chain id
chainID, err := cli.getChainID()
if err != nil {
return nil, fmt.Errorf("New: getChainID error: %v", err)
}
// 4. get SDKImpl
sdk := &SDKImpl{
cfg: cfg,
signParam: big.NewInt(0).SetBytes([]byte(fmt.Sprintf("%d", chainID))),
am: am,
nonceLock: &addrLocker{},
c: cli,
}
go sdk.getLoop()
return sdk, nil
}
func (sdk *SDKImpl) getLoop() {
interval := 30 * time.Second
timer := time.NewTimer(interval)
defer timer.Stop()
for {
// timer may be not active, and fired
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(interval)
select {
case <-timer.C:
if gasPrice, err := sdk.c.getGasPrice(); err == nil {
sdk.gasPrice = gasPrice
}
}
}
}