forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 59
/
XDCx_price.go
71 lines (61 loc) · 2.34 KB
/
XDCx_price.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
package vm
import (
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/log"
"github.com/XinFinOrg/XDPoSChain/params"
)
const XDCXPriceNumberOfBytesReturn = 32
// XDCxPrice implements a pre-compile contract to get token price in XDCx
type XDCxLastPrice struct {
tradingStateDB *tradingstate.TradingStateDB
}
type XDCxEpochPrice struct {
tradingStateDB *tradingstate.TradingStateDB
}
func (t *XDCxLastPrice) RequiredGas(input []byte) uint64 {
return params.XDCXPriceGas
}
func (t *XDCxLastPrice) Run(input []byte) ([]byte, error) {
// input includes baseTokenAddress, quoteTokenAddress
if t.tradingStateDB != nil && len(input) == 64 {
base := common.BytesToAddress(input[12:32]) // 20 bytes from 13-32
quote := common.BytesToAddress(input[44:]) // 20 bytes from 45-64
price := t.tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(base, quote))
if price != nil {
log.Debug("Run GetLastPrice", "base", base.Hex(), "quote", quote.Hex(), "price", price)
return common.LeftPadBytes(price.Bytes(), XDCXPriceNumberOfBytesReturn), nil
}
}
return common.LeftPadBytes([]byte{}, XDCXPriceNumberOfBytesReturn), nil
}
func (t *XDCxLastPrice) SetTradingState(tradingStateDB *tradingstate.TradingStateDB) {
if tradingStateDB != nil {
t.tradingStateDB = tradingStateDB.Copy()
} else {
t.tradingStateDB = nil
}
}
func (t *XDCxEpochPrice) RequiredGas(input []byte) uint64 {
return params.XDCXPriceGas
}
func (t *XDCxEpochPrice) Run(input []byte) ([]byte, error) {
// input includes baseTokenAddress, quoteTokenAddress
if t.tradingStateDB != nil && len(input) == 64 {
base := common.BytesToAddress(input[12:32]) // 20 bytes from 13-32
quote := common.BytesToAddress(input[44:]) // 20 bytes from 45-64
price := t.tradingStateDB.GetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(base, quote))
if price != nil {
log.Debug("Run GetEpochPrice", "base", base.Hex(), "quote", quote.Hex(), "price", price)
return common.LeftPadBytes(price.Bytes(), XDCXPriceNumberOfBytesReturn), nil
}
}
return common.LeftPadBytes([]byte{}, XDCXPriceNumberOfBytesReturn), nil
}
func (t *XDCxEpochPrice) SetTradingState(tradingStateDB *tradingstate.TradingStateDB) {
if tradingStateDB != nil {
t.tradingStateDB = tradingStateDB.Copy()
} else {
t.tradingStateDB = nil
}
}