common: add binary variables for system contract

This commit is contained in:
JukLee0ira 2024-05-30 19:34:43 +08:00
parent 21c62f9ef0
commit 0aab4ced98
36 changed files with 250 additions and 193 deletions

View file

@ -292,10 +292,10 @@ func (XDCx *XDCX) GetAveragePriceLastEpoch(chain consensus.ChainContext, statedb
// return tokenQuantity (after convert from XDC to token), tokenPriceInXDC, error // return tokenQuantity (after convert from XDC to token), tokenPriceInXDC, error
func (XDCx *XDCX) ConvertXDCToToken(chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address, quantity *big.Int) (*big.Int, *big.Int, error) { func (XDCx *XDCX) ConvertXDCToToken(chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address, quantity *big.Int) (*big.Int, *big.Int, error) {
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
return quantity, common.BasePrice, nil return quantity, common.BasePrice, nil
} }
tokenPriceInXDC, err := XDCx.GetAveragePriceLastEpoch(chain, statedb, tradingStateDb, token, common.HexToAddress(common.XDCNativeAddress)) tokenPriceInXDC, err := XDCx.GetAveragePriceLastEpoch(chain, statedb, tradingStateDb, token, common.XDCNativeAddressBinary)
if err != nil || tokenPriceInXDC == nil || tokenPriceInXDC.Sign() <= 0 { if err != nil || tokenPriceInXDC == nil || tokenPriceInXDC.Sign() <= 0 {
return common.Big0, common.Big0, err return common.Big0, common.Big0, err
} }
@ -596,7 +596,7 @@ func (XDCx *XDCX) GetTriegc() *prque.Prque {
func (XDCx *XDCX) GetTradingStateRoot(block *types.Block, author common.Address) (common.Hash, error) { func (XDCx *XDCX) GetTradingStateRoot(block *types.Block, author common.Address) (common.Hash, error) {
for _, tx := range block.Transactions() { for _, tx := range block.Transactions() {
from := *(tx.From()) from := *(tx.From())
if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from == author { if tx.To() != nil && *tx.To() == common.TradingStateAddrBinary && from == author {
if len(tx.Data()) >= 32 { if len(tx.Data()) >= 32 {
return common.BytesToHash(tx.Data()[:32]), nil return common.BytesToHash(tx.Data()[:32]), nil
} }

View file

@ -236,11 +236,11 @@ func (XDCx *XDCX) processOrderList(coinbase common.Address, chain consensus.Chai
maxTradedQuantity = tradingstate.CloneBigInt(amount) maxTradedQuantity = tradingstate.CloneBigInt(amount)
} }
var quotePrice *big.Int var quotePrice *big.Int
if oldestOrder.QuoteToken.String() != common.XDCNativeAddress { if oldestOrder.QuoteToken != common.XDCNativeAddressBinary {
quotePrice = tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(oldestOrder.QuoteToken, common.HexToAddress(common.XDCNativeAddress))) quotePrice = tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(oldestOrder.QuoteToken, common.XDCNativeAddressBinary))
log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice) log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice)
if quotePrice == nil || quotePrice.Sign() == 0 { if quotePrice == nil || quotePrice.Sign() == 0 {
inversePrice := tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), oldestOrder.QuoteToken)) inversePrice := tradingStateDB.GetLastPrice(tradingstate.GetTradingOrderBookHash(common.XDCNativeAddressBinary, oldestOrder.QuoteToken))
quoteTokenDecimal, err := XDCx.GetTokenDecimal(chain, statedb, oldestOrder.QuoteToken) quoteTokenDecimal, err := XDCx.GetTokenDecimal(chain, statedb, oldestOrder.QuoteToken)
if err != nil || quoteTokenDecimal.Sign() == 0 { if err != nil || quoteTokenDecimal.Sign() == 0 {
return nil, nil, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", oldestOrder.QuoteToken.String(), err) return nil, nil, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", oldestOrder.QuoteToken.String(), err)
@ -374,7 +374,7 @@ func (XDCx *XDCX) getTradeQuantity(quotePrice *big.Int, coinbase common.Address,
if err != nil || quoteTokenDecimal.Sign() == 0 { if err != nil || quoteTokenDecimal.Sign() == 0 {
return tradingstate.Zero, false, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.QuoteToken.String(), err) return tradingstate.Zero, false, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.QuoteToken.String(), err)
} }
if makerOrder.QuoteToken.String() == common.XDCNativeAddress { if makerOrder.QuoteToken == common.XDCNativeAddressBinary {
quotePrice = quoteTokenDecimal quotePrice = quoteTokenDecimal
} }
if takerOrder.ExchangeAddress == makerOrder.ExchangeAddress { if takerOrder.ExchangeAddress == makerOrder.ExchangeAddress {

View file

@ -1,12 +1,13 @@
package XDCx package XDCx
import ( import (
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
) )
func Test_getCancelFeeV1(t *testing.T) { func Test_getCancelFeeV1(t *testing.T) {
@ -103,9 +104,9 @@ func Test_getCancelFee(t *testing.T) {
XDCx.SetTokenDecimal(testTokenB, tokenBDecimal) XDCx.SetTokenDecimal(testTokenB, tokenBDecimal)
// set tokenAPrice = 1 XDC // set tokenAPrice = 1 XDC
tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.XDCNativeAddressBinary), common.BasePrice)
// set tokenBPrice = 1 XDC // set tokenBPrice = 1 XDC
tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), testTokenB), tokenBDecimal) tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(common.XDCNativeAddressBinary, testTokenB), tokenBDecimal)
type CancelFeeArg struct { type CancelFeeArg struct {
feeRate *big.Int feeRate *big.Int
@ -127,7 +128,7 @@ func Test_getCancelFee(t *testing.T) {
feeRate: common.Big0, feeRate: common.Big0,
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: testTokenA, BaseToken: testTokenA,
QuoteToken: common.HexToAddress(common.XDCNativeAddress), QuoteToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Ask, Side: tradingstate.Ask,
}, },
@ -142,7 +143,7 @@ func Test_getCancelFee(t *testing.T) {
feeRate: common.Big0, feeRate: common.Big0,
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: testTokenA, BaseToken: testTokenA,
QuoteToken: common.HexToAddress(common.XDCNativeAddress), QuoteToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Bid, Side: tradingstate.Bid,
}, },
@ -156,7 +157,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1%
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Ask, Side: tradingstate.Ask,
@ -172,7 +173,7 @@ func Test_getCancelFee(t *testing.T) {
feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1%
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Side: tradingstate.Bid, Side: tradingstate.Bid,
}, },
@ -188,7 +189,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
feeRate: common.Big0, feeRate: common.Big0,
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Ask, Side: tradingstate.Ask,
@ -203,7 +204,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
feeRate: common.Big0, feeRate: common.Big0,
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Bid, Side: tradingstate.Bid,
@ -218,7 +219,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1%
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: tradingstate.Ask, Side: tradingstate.Ask,
@ -234,7 +235,7 @@ func Test_getCancelFee(t *testing.T) {
feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1% feeRate: new(big.Int).SetUint64(10), // 10/10000= 0.1%
order: &tradingstate.OrderItem{ order: &tradingstate.OrderItem{
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: testTokenA, QuoteToken: testTokenA,
Side: tradingstate.Bid, Side: tradingstate.Bid,
}, },

View file

@ -48,7 +48,7 @@ func (XDCx *XDCX) GetTokenDecimal(chain consensus.ChainContext, statedb *state.S
if tokenDecimal, ok := XDCx.tokenDecimalCache.Get(tokenAddr); ok { if tokenDecimal, ok := XDCx.tokenDecimalCache.Get(tokenAddr); ok {
return tokenDecimal.(*big.Int), nil return tokenDecimal.(*big.Int), nil
} }
if tokenAddr.String() == common.XDCNativeAddress { if tokenAddr == common.XDCNativeAddressBinary {
XDCx.tokenDecimalCache.Add(tokenAddr, common.BasePrice) XDCx.tokenDecimalCache.Add(tokenAddr, common.BasePrice)
return common.BasePrice, nil return common.BasePrice, nil
} }

View file

@ -239,7 +239,7 @@ func (o *OrderItem) verifyRelayer(state *state.StateDB) error {
return nil return nil
} }
//verify signatures // verify signatures
func (o *OrderItem) verifySignature() error { func (o *OrderItem) verifySignature() error {
bigstr := o.Nonce.String() bigstr := o.Nonce.String()
n, err := strconv.ParseInt(bigstr, 10, 64) n, err := strconv.ParseInt(bigstr, 10, 64)
@ -269,7 +269,7 @@ func (o *OrderItem) verifyOrderType() error {
return nil return nil
} }
//verify order side // verify order side
func (o *OrderItem) verifyOrderSide() error { func (o *OrderItem) verifyOrderSide() error {
if o.Side != Bid && o.Side != Ask { if o.Side != Bid && o.Side != Ask {
@ -356,11 +356,11 @@ func VerifyPair(statedb *state.StateDB, exchangeAddress, baseToken, quoteToken c
func VerifyBalance(statedb *state.StateDB, XDCxStateDb *TradingStateDB, order *types.OrderTransaction, baseDecimal, quoteDecimal *big.Int) error { func VerifyBalance(statedb *state.StateDB, XDCxStateDb *TradingStateDB, order *types.OrderTransaction, baseDecimal, quoteDecimal *big.Int) error {
var quotePrice *big.Int var quotePrice *big.Int
if order.QuoteToken().String() != common.XDCNativeAddress { if order.QuoteToken() != common.XDCNativeAddressBinary {
quotePrice = XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(order.QuoteToken(), common.HexToAddress(common.XDCNativeAddress))) quotePrice = XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(order.QuoteToken(), common.XDCNativeAddressBinary))
log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice) log.Debug("TryGet quotePrice QuoteToken/XDC", "quotePrice", quotePrice)
if quotePrice == nil || quotePrice.Sign() == 0 { if quotePrice == nil || quotePrice.Sign() == 0 {
inversePrice := XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(common.HexToAddress(common.XDCNativeAddress), order.QuoteToken())) inversePrice := XDCxStateDb.GetLastPrice(GetTradingOrderBookHash(common.XDCNativeAddressBinary, order.QuoteToken()))
log.Debug("TryGet inversePrice XDC/QuoteToken", "inversePrice", inversePrice) log.Debug("TryGet inversePrice XDC/QuoteToken", "inversePrice", inversePrice)
if inversePrice != nil && inversePrice.Sign() > 0 { if inversePrice != nil && inversePrice.Sign() > 0 {
quotePrice = new(big.Int).Mul(common.BasePrice, quoteDecimal) quotePrice = new(big.Int).Mul(common.BasePrice, quoteDecimal)

View file

@ -159,7 +159,7 @@ func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateD
} }
func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
balance := statedb.GetBalance(addr) balance := statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value)
statedb.AddBalance(addr, value) statedb.AddBalance(addr, value)
@ -186,7 +186,7 @@ func AddTokenBalance(addr common.Address, value *big.Int, token common.Address,
func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
balance := statedb.GetBalance(addr) balance := statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value)
@ -219,7 +219,7 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address,
func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
var balance *big.Int var balance *big.Int
if value := mapBalances[token][addr]; value != nil { if value := mapBalances[token][addr]; value != nil {
balance = value balance = value
@ -256,7 +256,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr
func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
var balance *big.Int var balance *big.Int
if value := mapBalances[token][addr]; value != nil { if value := mapBalances[token][addr]; value != nil {
balance = value balance = value
@ -308,7 +308,7 @@ func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.Sta
func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int { func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
return statedb.GetBalance(addr) return statedb.GetBalance(addr)
} }
// TRC tokens // TRC tokens
@ -323,7 +323,7 @@ func GetTokenBalance(addr common.Address, token common.Address, statedb *state.S
func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error { func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
statedb.SetBalance(addr, balance) statedb.SetBalance(addr, balance)
return nil return nil
} }

View file

@ -52,7 +52,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I
log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "makerFee", makerFee, "defaultFee", defaultFee) log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "makerFee", makerFee, "defaultFee", defaultFee)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
if quoteToken.String() != common.XDCNativeAddress && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { if quoteToken != common.XDCNativeAddressBinary && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 {
// defaultFeeInXDC // defaultFeeInXDC
defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice) defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice)
defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal)
@ -69,7 +69,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I
log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC) log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
} else if quoteToken.String() == common.XDCNativeAddress { } else if quoteToken == common.XDCNativeAddressBinary {
exMakerReceivedFee := makerFee exMakerReceivedFee := makerFee
if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 { if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 {
log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee) log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee)
@ -108,7 +108,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I
log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee) log.Debug("quantity trade too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
if quoteToken.String() != common.XDCNativeAddress && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 { if quoteToken != common.XDCNativeAddressBinary && quotePrice != nil && quotePrice.Cmp(common.Big0) > 0 {
// defaultFeeInXDC // defaultFeeInXDC
defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice) defaultFeeInXDC := new(big.Int).Mul(defaultFee, quotePrice)
defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, quoteTokenDecimal)
@ -126,7 +126,7 @@ func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.I
log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC) log.Debug("takerFee too small", "quoteTokenQuantity", quoteTokenQuantity, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "quotePrice", quotePrice, "defaultFeeInXDC", defaultFeeInXDC)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
} else if quoteToken.String() == common.XDCNativeAddress { } else if quoteToken == common.XDCNativeAddressBinary {
exMakerReceivedFee := makerFee exMakerReceivedFee := makerFee
if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 { if (exMakerReceivedFee.Cmp(common.RelayerFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerFee) <= 0 {
log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee) log.Debug("makerFee too small", "quantityToTrade", quantityToTrade, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "makerFeeRate", makerFeeRate, "defaultFee", defaultFee)

View file

@ -1,10 +1,11 @@
package tradingstate package tradingstate
import ( import (
"github.com/XinFinOrg/XDPoSChain/common"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/common"
) )
func TestGetSettleBalance(t *testing.T) { func TestGetSettleBalance(t *testing.T) {
@ -89,7 +90,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Bid, takerSide: Bid,
takerFeeRate: big.NewInt(10), // feeRate 0.1% takerFeeRate: big.NewInt(10), // feeRate 0.1%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -106,7 +107,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Bid, takerSide: Bid,
takerFeeRate: big.NewInt(5), // feeRate 0.05% takerFeeRate: big.NewInt(5), // feeRate 0.05%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -124,7 +125,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Bid, takerSide: Bid,
takerFeeRate: big.NewInt(10), // feeRate 0.1% takerFeeRate: big.NewInt(10), // feeRate 0.1%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -132,8 +133,8 @@ func TestGetSettleBalance(t *testing.T) {
quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice), quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice),
}, },
&SettleBalance{ &SettleBalance{
Taker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.HexToAddress(common.XDCNativeAddress), OutTotal: tradeQuantityIncludedFee}, Taker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.XDCNativeAddressBinary, OutTotal: tradeQuantityIncludedFee},
Maker: TradeResult{Fee: testFee, InToken: common.HexToAddress(common.XDCNativeAddress), InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, Maker: TradeResult{Fee: testFee, InToken: common.XDCNativeAddressBinary, InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity},
}, },
false, false,
}, },
@ -196,7 +197,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Ask, takerSide: Ask,
takerFeeRate: big.NewInt(10), // feeRate 0.1% takerFeeRate: big.NewInt(10), // feeRate 0.1%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -213,7 +214,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Ask, takerSide: Ask,
takerFeeRate: big.NewInt(5), // feeRate 0.05% takerFeeRate: big.NewInt(5), // feeRate 0.05%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -231,7 +232,7 @@ func TestGetSettleBalance(t *testing.T) {
takerSide: Ask, takerSide: Ask,
takerFeeRate: big.NewInt(10), // feeRate 15% takerFeeRate: big.NewInt(10), // feeRate 15%
baseToken: testToken, baseToken: testToken,
quoteToken: common.HexToAddress(common.XDCNativeAddress), quoteToken: common.XDCNativeAddressBinary,
makerPrice: common.BasePrice, makerPrice: common.BasePrice,
makerFeeRate: big.NewInt(10), // feeRate 0.1% makerFeeRate: big.NewInt(10), // feeRate 0.1%
baseTokenDecimal: common.BasePrice, baseTokenDecimal: common.BasePrice,
@ -239,8 +240,8 @@ func TestGetSettleBalance(t *testing.T) {
quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice), quantityToTrade: new(big.Int).Mul(big.NewInt(1000), common.BasePrice),
}, },
&SettleBalance{ &SettleBalance{
Maker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.HexToAddress(common.XDCNativeAddress), OutTotal: tradeQuantityIncludedFee}, Maker: TradeResult{Fee: testFee, InToken: testToken, InTotal: tradeQuantity, OutToken: common.XDCNativeAddressBinary, OutTotal: tradeQuantityIncludedFee},
Taker: TradeResult{Fee: testFee, InToken: common.HexToAddress(common.XDCNativeAddress), InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity}, Taker: TradeResult{Fee: testFee, InToken: common.XDCNativeAddressBinary, InTotal: tradeQuantityExcludedFee, OutToken: testToken, OutTotal: tradeQuantity},
}, },
false, false,
}, },

View file

@ -697,7 +697,7 @@ func (l *Lending) GetTriegc() *prque.Prque {
func (l *Lending) GetLendingStateRoot(block *types.Block, author common.Address) (common.Hash, error) { func (l *Lending) GetLendingStateRoot(block *types.Block, author common.Address) (common.Hash, error) {
for _, tx := range block.Transactions() { for _, tx := range block.Transactions() {
from := *(tx.From()) from := *(tx.From())
if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from == author { if tx.To() != nil && *tx.To() == common.TradingStateAddrBinary && from == author {
if len(tx.Data()) >= 64 { if len(tx.Data()) >= 64 {
return common.BytesToHash(tx.Data()[32:]), nil return common.BytesToHash(tx.Data()[32:]), nil
} }

View file

@ -411,7 +411,7 @@ func VerifyBalance(isXDCXLendingFork bool, statedb *state.StateDB, lendingStateD
defaultFee := new(big.Int).Mul(quantity, new(big.Int).SetUint64(DefaultFeeRate)) defaultFee := new(big.Int).Mul(quantity, new(big.Int).SetUint64(DefaultFeeRate))
defaultFee = new(big.Int).Div(defaultFee, common.XDCXBaseFee) defaultFee = new(big.Int).Div(defaultFee, common.XDCXBaseFee)
defaultFeeInXDC := common.Big0 defaultFeeInXDC := common.Big0
if lendingToken.String() != common.XDCNativeAddress { if lendingToken != common.XDCNativeAddressBinary {
defaultFeeInXDC = new(big.Int).Mul(defaultFee, lendTokenXDCPrice) defaultFeeInXDC = new(big.Int).Mul(defaultFee, lendTokenXDCPrice)
defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, lendingTokenDecimal) defaultFeeInXDC = new(big.Int).Div(defaultFeeInXDC, lendingTokenDecimal)
} else { } else {

View file

@ -114,7 +114,7 @@ func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateD
} }
func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
balance := statedb.GetBalance(addr) balance := statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD TOKEN XDC NATIVE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value)
statedb.AddBalance(addr, value) statedb.AddBalance(addr, value)
@ -141,7 +141,7 @@ func AddTokenBalance(addr common.Address, value *big.Int, token common.Address,
func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error { func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
balance := statedb.GetBalance(addr) balance := statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE BEFORE", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value)
if balance.Cmp(value) < 0 { if balance.Cmp(value) < 0 {
@ -174,7 +174,7 @@ func SubTokenBalance(addr common.Address, value *big.Int, token common.Address,
func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
var balance *big.Int var balance *big.Int
if value := mapBalances[token][addr]; value != nil { if value := mapBalances[token][addr]; value != nil {
balance = value balance = value
@ -211,7 +211,7 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr
func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) { func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error) {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
var balance *big.Int var balance *big.Int
if value := mapBalances[token][addr]; value != nil { if value := mapBalances[token][addr]; value != nil {
balance = value balance = value
@ -263,7 +263,7 @@ func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.Sta
func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int { func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
return statedb.GetBalance(addr) return statedb.GetBalance(addr)
} }
// TRC tokens // TRC tokens
@ -278,7 +278,7 @@ func GetTokenBalance(addr common.Address, token common.Address, statedb *state.S
func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error { func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error {
// XDC native // XDC native
if token.String() == common.XDCNativeAddress { if token == common.XDCNativeAddressBinary {
statedb.SetBalance(addr, balance) statedb.SetBalance(addr, balance)
return nil return nil
} }

View file

@ -3,9 +3,10 @@ package lendingstate
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"math/big"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/log"
"math/big"
) )
const DefaultFeeRate = 100 // 100 / XDCXBaseFee = 100 / 10000 = 1% const DefaultFeeRate = 100 // 100 / XDCXBaseFee = 100 / 10000 = 1%
@ -71,7 +72,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "takerFee", takerFee) log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "takerFee", takerFee)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 {
exTakerReceivedFee := new(big.Int).Mul(takerFee, lendTokenXDCPrice) exTakerReceivedFee := new(big.Int).Mul(takerFee, lendTokenXDCPrice)
exTakerReceivedFee = new(big.Int).Div(exTakerReceivedFee, lendTokenDecimal) exTakerReceivedFee = new(big.Int).Div(exTakerReceivedFee, lendTokenDecimal)
@ -82,7 +83,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
} else if lendingToken.String() == common.XDCNativeAddress { } else if lendingToken == common.XDCNativeAddressBinary {
exTakerReceivedFee := takerFee exTakerReceivedFee := takerFee
if (exTakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exTakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { if (exTakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exTakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 {
log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) log.Debug("takerFee too small", "quantityToLend", quantityToLend, "takerFee", takerFee, "exTakerReceivedFee", exTakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee)
@ -121,7 +122,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "makerFee", makerFee) log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "makerFee", makerFee)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 {
exMakerReceivedFee := new(big.Int).Mul(makerFee, lendTokenXDCPrice) exMakerReceivedFee := new(big.Int).Mul(makerFee, lendTokenXDCPrice)
exMakerReceivedFee = new(big.Int).Div(exMakerReceivedFee, lendTokenDecimal) exMakerReceivedFee = new(big.Int).Div(exMakerReceivedFee, lendTokenDecimal)
@ -132,7 +133,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
} else if lendingToken.String() == common.XDCNativeAddress { } else if lendingToken == common.XDCNativeAddressBinary {
exMakerReceivedFee := makerFee exMakerReceivedFee := makerFee
if (exMakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { if (exMakerReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exMakerReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 {
log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) log.Debug("makerFee too small", "quantityToLend", quantityToLend, "makerFee", makerFee, "exMakerReceivedFee", exMakerReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee)
@ -171,7 +172,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee) log.Debug("quantity lending too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
if lendingToken.String() != common.XDCNativeAddress && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 { if lendingToken != common.XDCNativeAddressBinary && lendTokenXDCPrice != nil && lendTokenXDCPrice.Cmp(common.Big0) > 0 {
// exReceivedFee: the fee amount which borrowingRelayer will receive // exReceivedFee: the fee amount which borrowingRelayer will receive
exReceivedFee := new(big.Int).Mul(borrowFee, lendTokenXDCPrice) exReceivedFee := new(big.Int).Mul(borrowFee, lendTokenXDCPrice)
exReceivedFee = new(big.Int).Div(exReceivedFee, lendTokenDecimal) exReceivedFee = new(big.Int).Div(exReceivedFee, lendTokenDecimal)
@ -183,7 +184,7 @@ func GetSettleBalance(isXDCXLendingFork bool,
log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC) log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFeeInXDC", defaultFeeInXDC)
return result, ErrQuantityTradeTooSmall return result, ErrQuantityTradeTooSmall
} }
} else if lendingToken.String() == common.XDCNativeAddress { } else if lendingToken == common.XDCNativeAddressBinary {
exReceivedFee := borrowFee exReceivedFee := borrowFee
if (exReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 { if (exReceivedFee.Cmp(common.RelayerLendingFee) <= 0 && exReceivedFee.Sign() > 0) || defaultFee.Cmp(common.RelayerLendingFee) <= 0 {
log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee) log.Debug("takerFee too small", "quantityToLend", quantityToLend, "borrowFee", borrowFee, "exReceivedFee", exReceivedFee, "borrowFeeRate", borrowFeeRate, "defaultFee", defaultFee)

View file

@ -1,10 +1,11 @@
package lendingstate package lendingstate
import ( import (
"github.com/XinFinOrg/XDPoSChain/common"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
"github.com/XinFinOrg/XDPoSChain/common"
) )
func TestCalculateInterestRate(t *testing.T) { func TestCalculateInterestRate(t *testing.T) {
@ -171,7 +172,7 @@ func TestGetSettleBalance(t *testing.T) {
common.BasePrice, common.BasePrice,
big.NewInt(150), big.NewInt(150),
big.NewInt(100), // 1% big.NewInt(100), // 1%
common.HexToAddress(common.XDCNativeAddress), common.XDCNativeAddressBinary,
common.Address{}, common.Address{},
common.BasePrice, common.BasePrice,
common.BasePrice, common.BasePrice,
@ -277,7 +278,7 @@ func TestGetSettleBalance(t *testing.T) {
common.BasePrice, common.BasePrice,
big.NewInt(150), big.NewInt(150),
big.NewInt(100), // 1% big.NewInt(100), // 1%
common.HexToAddress(common.XDCNativeAddress), common.XDCNativeAddressBinary,
collateral, collateral,
common.BasePrice, common.BasePrice,
common.BasePrice, common.BasePrice,
@ -288,12 +289,12 @@ func TestGetSettleBalance(t *testing.T) {
Fee: common.Big0, Fee: common.Big0,
InToken: common.Address{}, InToken: common.Address{},
InTotal: common.Big0, InTotal: common.Big0,
OutToken: common.HexToAddress(common.XDCNativeAddress), OutToken: common.XDCNativeAddressBinary,
OutTotal: lendQuantity, OutTotal: lendQuantity,
}, },
Maker: TradeResult{ Maker: TradeResult{
Fee: fee, Fee: fee,
InToken: common.HexToAddress(common.XDCNativeAddress), InToken: common.XDCNativeAddressBinary,
InTotal: lendQuantityExcluded, InTotal: lendQuantityExcluded,
OutToken: collateral, OutToken: collateral,
OutTotal: collateralLocked, OutTotal: collateralLocked,
@ -312,7 +313,7 @@ func TestGetSettleBalance(t *testing.T) {
common.BasePrice, common.BasePrice,
big.NewInt(150), big.NewInt(150),
big.NewInt(100), // 1% big.NewInt(100), // 1%
common.HexToAddress(common.XDCNativeAddress), common.XDCNativeAddressBinary,
collateral, collateral,
common.BasePrice, common.BasePrice,
common.BasePrice, common.BasePrice,
@ -323,12 +324,12 @@ func TestGetSettleBalance(t *testing.T) {
Fee: common.Big0, Fee: common.Big0,
InToken: common.Address{}, InToken: common.Address{},
InTotal: common.Big0, InTotal: common.Big0,
OutToken: common.HexToAddress(common.XDCNativeAddress), OutToken: common.XDCNativeAddressBinary,
OutTotal: lendQuantity, OutTotal: lendQuantity,
}, },
Taker: TradeResult{ Taker: TradeResult{
Fee: fee, Fee: fee,
InToken: common.HexToAddress(common.XDCNativeAddress), InToken: common.XDCNativeAddressBinary,
InTotal: lendQuantityExcluded, InTotal: lendQuantityExcluded,
OutToken: collateral, OutToken: collateral,
OutTotal: collateralLocked, OutTotal: collateralLocked,

View file

@ -621,11 +621,11 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta
} }
mapBalances[settleBalance.Taker.InToken][takerExOwner] = newTakerFee mapBalances[settleBalance.Taker.InToken][takerExOwner] = newTakerFee
newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.HexToAddress(common.LendingLockAddress), settleBalance.Taker.OutTotal, settleBalance.Taker.OutToken, statedb, mapBalances) newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.LendingLockAddressBinary, settleBalance.Taker.OutTotal, settleBalance.Taker.OutToken, statedb, mapBalances)
if err != nil { if err != nil {
return err return err
} }
mapBalances[settleBalance.Taker.OutToken][common.HexToAddress(common.LendingLockAddress)] = newCollateralTokenLock mapBalances[settleBalance.Taker.OutToken][common.LendingLockAddressBinary] = newCollateralTokenLock
} else { } else {
relayerFee, err := lendingstate.CheckSubRelayerFee(makerOrder.Relayer, common.RelayerLendingFee, statedb, map[common.Address]*big.Int{}) relayerFee, err := lendingstate.CheckSubRelayerFee(makerOrder.Relayer, common.RelayerLendingFee, statedb, map[common.Address]*big.Int{})
if err != nil { if err != nil {
@ -662,11 +662,11 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta
} }
mapBalances[settleBalance.Maker.InToken][makerExOwner] = newMakerFee mapBalances[settleBalance.Maker.InToken][makerExOwner] = newMakerFee
newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.HexToAddress(common.LendingLockAddress), settleBalance.Maker.OutTotal, settleBalance.Maker.OutToken, statedb, mapBalances) newCollateralTokenLock, err := lendingstate.CheckAddTokenBalance(common.LendingLockAddressBinary, settleBalance.Maker.OutTotal, settleBalance.Maker.OutToken, statedb, mapBalances)
if err != nil { if err != nil {
return err return err
} }
mapBalances[settleBalance.Maker.OutToken][common.HexToAddress(common.LendingLockAddress)] = newCollateralTokenLock mapBalances[settleBalance.Maker.OutToken][common.LendingLockAddressBinary] = newCollateralTokenLock
} }
masternodeOwner := statedb.GetOwner(coinbase) masternodeOwner := statedb.GetOwner(coinbase)
statedb.AddBalance(masternodeOwner, matchingFee) statedb.AddBalance(masternodeOwner, matchingFee)
@ -854,7 +854,7 @@ func (l *Lending) LiquidationExpiredTrade(header *types.Header, chain consensus.
} else { } else {
repayAmount = lendingTrade.CollateralLockedAmount repayAmount = lendingTrade.CollateralLockedAmount
} }
err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
log.Warn("LiquidationExpiredTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("LiquidationExpiredTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
@ -897,7 +897,7 @@ func (l *Lending) LiquidationTrade(lendingStateDB *lendingstate.LendingStateDB,
if lendingTrade.TradeId != lendingTradeId { if lendingTrade.TradeId != lendingTradeId {
return nil, fmt.Errorf("Lending Trade Id not found : %d ", lendingTradeId) return nil, fmt.Errorf("Lending Trade Id not found : %d ", lendingTradeId)
} }
err := lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) err := lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
log.Warn("LiquidationTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("LiquidationTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
@ -1052,10 +1052,10 @@ func (l *Lending) GetCollateralPrices(header *types.Header, chain consensus.Chai
func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address) (*big.Int, error) { func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainContext, statedb *state.StateDB, tradingStateDb *tradingstate.TradingStateDB, token common.Address) (*big.Int, error) {
tokenXDCPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, token, common.HexToAddress(common.XDCNativeAddress)) tokenXDCPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, token, common.XDCNativeAddressBinary)
tokenXDCPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch tokenXDCPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch
if token == common.HexToAddress(common.XDCNativeAddress) { if token == common.XDCNativeAddressBinary {
return common.BasePrice, nil return common.BasePrice, nil
} else if tokenXDCPriceUpdatedFromContract { } else if tokenXDCPriceUpdatedFromContract {
// getting lendToken price from contract first // getting lendToken price from contract first
@ -1063,7 +1063,7 @@ func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainCo
log.Debug("Getting token/XDC price from contract", "price", tokenXDCPriceFromContract) log.Debug("Getting token/XDC price from contract", "price", tokenXDCPriceFromContract)
return tokenXDCPriceFromContract, nil return tokenXDCPriceFromContract, nil
} else { } else {
XDCTokenPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, common.HexToAddress(common.XDCNativeAddress), token) XDCTokenPriceFromContract, updatedBlock := lendingstate.GetCollateralPrice(statedb, common.XDCNativeAddressBinary, token)
XDCTokenPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch XDCTokenPriceUpdatedFromContract := updatedBlock.Uint64()/chain.Config().XDPoS.Epoch == header.Number.Uint64()/chain.Config().XDPoS.Epoch
if XDCTokenPriceUpdatedFromContract && XDCTokenPriceFromContract != nil && XDCTokenPriceFromContract.Sign() > 0 { if XDCTokenPriceUpdatedFromContract && XDCTokenPriceFromContract != nil && XDCTokenPriceFromContract.Sign() > 0 {
// getting lendToken price from contract first // getting lendToken price from contract first
@ -1078,7 +1078,7 @@ func (l *Lending) GetXDCBasePrices(header *types.Header, chain consensus.ChainCo
tokenXDCPrice = new(big.Int).Div(tokenXDCPrice, XDCTokenPriceFromContract) tokenXDCPrice = new(big.Int).Div(tokenXDCPrice, XDCTokenPriceFromContract)
return tokenXDCPrice, nil return tokenXDCPrice, nil
} }
tokenXDCPrice, err := l.GetMediumTradePriceBeforeEpoch(chain, statedb, tradingStateDb, token, common.HexToAddress(common.XDCNativeAddress)) tokenXDCPrice, err := l.GetMediumTradePriceBeforeEpoch(chain, statedb, tradingStateDb, token, common.XDCNativeAddressBinary)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1133,7 +1133,7 @@ func (l *Lending) ProcessTopUpLendingTrade(lendingStateDB *lendingstate.LendingS
if err != nil { if err != nil {
log.Warn("ProcessTopUpLendingTrade SubTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("ProcessTopUpLendingTrade SubTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
err = lendingstate.AddTokenBalance(common.HexToAddress(common.LendingLockAddress), quantity, lendingTrade.CollateralToken, statedb) err = lendingstate.AddTokenBalance(common.LendingLockAddressBinary, quantity, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
log.Warn("ProcessTopUpLendingTrade AddTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("ProcessTopUpLendingTrade AddTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
@ -1199,7 +1199,7 @@ func (l *Lending) ProcessRepayLendingTrade(header *types.Header, chain consensus
if err != nil { if err != nil {
log.Warn("ProcessRepayLendingTrade AddTokenBalance", "err", err, "lendingTrade.Investor", lendingTrade.Investor, "paymentBalance", *paymentBalance, "lendingTrade.LendingToken", lendingTrade.LendingToken) log.Warn("ProcessRepayLendingTrade AddTokenBalance", "err", err, "lendingTrade.Investor", lendingTrade.Investor, "paymentBalance", *paymentBalance, "lendingTrade.LendingToken", lendingTrade.LendingToken)
} }
err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
log.Warn("ProcessRepayLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("ProcessRepayLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
@ -1255,7 +1255,7 @@ func (l *Lending) ProcessRecallLendingTrade(lendingStateDB *lendingstate.Lending
if err != nil { if err != nil {
log.Warn("ProcessRecallLendingTrade AddTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("ProcessRecallLendingTrade AddTokenBalance", "err", err, "lendingTrade.Borrower", lendingTrade.Borrower, "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
err = lendingstate.SubTokenBalance(common.HexToAddress(common.LendingLockAddress), recallAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.SubTokenBalance(common.LendingLockAddressBinary, recallAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
log.Warn("ProcessRecallLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken) log.Warn("ProcessRecallLendingTrade SubTokenBalance", "err", err, "LendingLockAddress", common.HexToAddress(common.LendingLockAddress), "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }

View file

@ -1,14 +1,15 @@
package XDCxlending package XDCxlending
import ( import (
"math/big"
"reflect"
"testing"
"github.com/XinFinOrg/XDPoSChain/XDCx" "github.com/XinFinOrg/XDPoSChain/XDCx"
"github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate" "github.com/XinFinOrg/XDPoSChain/XDCx/tradingstate"
"github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate" "github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/rawdb" "github.com/XinFinOrg/XDPoSChain/core/rawdb"
"math/big"
"reflect"
"testing"
) )
func Test_getCancelFeeV1(t *testing.T) { func Test_getCancelFeeV1(t *testing.T) {
@ -107,9 +108,9 @@ func Test_getCancelFee(t *testing.T) {
XDCx.SetTokenDecimal(testTokenB, new(big.Int).Exp(big.NewInt(10), big.NewInt(8), nil)) XDCx.SetTokenDecimal(testTokenB, new(big.Int).Exp(big.NewInt(10), big.NewInt(8), nil))
// set tokenAPrice = 1 XDC // set tokenAPrice = 1 XDC
tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenA, common.XDCNativeAddressBinary), common.BasePrice)
// set tokenBPrice = 1 XDC // set tokenBPrice = 1 XDC
tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenB, common.HexToAddress(common.XDCNativeAddress)), common.BasePrice) tradingStateDb.SetMediumPriceBeforeEpoch(tradingstate.GetTradingOrderBookHash(testTokenB, common.XDCNativeAddressBinary), common.BasePrice)
l := New(XDCx) l := New(XDCx)
@ -132,7 +133,7 @@ func Test_getCancelFee(t *testing.T) {
borrowFeeRate: common.Big0, borrowFeeRate: common.Big0,
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: testTokenA, LendingToken: testTokenA,
CollateralToken: common.HexToAddress(common.XDCNativeAddress), CollateralToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Investing, Side: lendingstate.Investing,
}, },
@ -147,7 +148,7 @@ func Test_getCancelFee(t *testing.T) {
borrowFeeRate: common.Big0, borrowFeeRate: common.Big0,
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: testTokenA, LendingToken: testTokenA,
CollateralToken: common.HexToAddress(common.XDCNativeAddress), CollateralToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Borrowing, Side: lendingstate.Borrowing,
}, },
@ -162,7 +163,7 @@ func Test_getCancelFee(t *testing.T) {
borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3%
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: testTokenA, LendingToken: testTokenA,
CollateralToken: common.HexToAddress(common.XDCNativeAddress), CollateralToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Investing, Side: lendingstate.Investing,
}, },
@ -177,7 +178,7 @@ func Test_getCancelFee(t *testing.T) {
borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3%
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: testTokenA, LendingToken: testTokenA,
CollateralToken: common.HexToAddress(common.XDCNativeAddress), CollateralToken: common.XDCNativeAddressBinary,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Borrowing, Side: lendingstate.Borrowing,
}, },
@ -194,7 +195,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
borrowFeeRate: common.Big0, borrowFeeRate: common.Big0,
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: common.HexToAddress(common.XDCNativeAddress), LendingToken: common.XDCNativeAddressBinary,
CollateralToken: testTokenA, CollateralToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Investing, Side: lendingstate.Investing,
@ -209,7 +210,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
borrowFeeRate: common.Big0, borrowFeeRate: common.Big0,
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: common.HexToAddress(common.XDCNativeAddress), LendingToken: common.XDCNativeAddressBinary,
CollateralToken: testTokenA, CollateralToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Borrowing, Side: lendingstate.Borrowing,
@ -224,7 +225,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3%
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: common.HexToAddress(common.XDCNativeAddress), LendingToken: common.XDCNativeAddressBinary,
CollateralToken: testTokenA, CollateralToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Investing, Side: lendingstate.Investing,
@ -239,7 +240,7 @@ func Test_getCancelFee(t *testing.T) {
CancelFeeArg{ CancelFeeArg{
borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3% borrowFeeRate: new(big.Int).SetUint64(30), // 30/10000= 0.3%
order: &lendingstate.LendingItem{ order: &lendingstate.LendingItem{
LendingToken: common.HexToAddress(common.XDCNativeAddress), LendingToken: common.XDCNativeAddressBinary,
CollateralToken: testTokenA, CollateralToken: testTokenA,
Quantity: new(big.Int).SetUint64(10000), Quantity: new(big.Int).SetUint64(10000),
Side: lendingstate.Borrowing, Side: lendingstate.Borrowing,

View file

@ -28,7 +28,7 @@ var (
cacheSize = flag.Int("size", 1000000, "LRU cache size") cacheSize = flag.Int("size", 1000000, "LRU cache size")
sercureKey = []byte("secure-key-") sercureKey = []byte("secure-key-")
nWorker = runtime.NumCPU() / 2 nWorker = runtime.NumCPU() / 2
cleanAddress = []common.Address{common.HexToAddress(common.BlockSigners)} cleanAddress = []common.Address{common.BlockSignersBinary}
cache *lru.Cache cache *lru.Cache
finish = int32(0) finish = int32(0)
running = true running = true

View file

@ -197,7 +197,7 @@ func (w *wizard) makeGenesis() {
fmt.Println() fmt.Println()
fmt.Println("What is foundation wallet address? (default = xdc0000000000000000000000000000000000000068)") fmt.Println("What is foundation wallet address? (default = xdc0000000000000000000000000000000000000068)")
genesis.Config.XDPoS.FoudationWalletAddr = w.readDefaultAddress(common.HexToAddress(common.FoudationAddr)) genesis.Config.XDPoS.FoudationWalletAddr = w.readDefaultAddress(common.FoudationAddrBinary)
// Validator Smart Contract Code // Validator Smart Contract Code
pKey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") pKey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
@ -225,7 +225,7 @@ func (w *wizard) makeGenesis() {
return true return true
} }
contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f) contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f)
genesis.Alloc[common.HexToAddress(common.MasternodeVotingSMC)] = core.GenesisAccount{ genesis.Alloc[common.MasternodeVotingSMCBinary] = core.GenesisAccount{
Balance: validatorCap.Mul(validatorCap, big.NewInt(int64(len(validatorCaps)))), Balance: validatorCap.Mul(validatorCap, big.NewInt(int64(len(validatorCaps)))),
Code: code, Code: code,
Storage: storage, Storage: storage,
@ -259,7 +259,7 @@ func (w *wizard) makeGenesis() {
fBalance := big.NewInt(0) // 16m fBalance := big.NewInt(0) // 16m
fBalance.Add(fBalance, big.NewInt(16*1000*1000)) fBalance.Add(fBalance, big.NewInt(16*1000*1000))
fBalance.Mul(fBalance, big.NewInt(1000000000000000000)) fBalance.Mul(fBalance, big.NewInt(1000000000000000000))
genesis.Alloc[common.HexToAddress(common.FoudationAddr)] = core.GenesisAccount{ genesis.Alloc[common.FoudationAddrBinary] = core.GenesisAccount{
Balance: fBalance, Balance: fBalance,
Code: code, Code: code,
Storage: storage, Storage: storage,
@ -275,7 +275,7 @@ func (w *wizard) makeGenesis() {
code, _ = contractBackend.CodeAt(ctx, blockSignerAddress, nil) code, _ = contractBackend.CodeAt(ctx, blockSignerAddress, nil)
storage = make(map[common.Hash]common.Hash) storage = make(map[common.Hash]common.Hash)
contractBackend.ForEachStorageAt(ctx, blockSignerAddress, nil, f) contractBackend.ForEachStorageAt(ctx, blockSignerAddress, nil, f)
genesis.Alloc[common.HexToAddress(common.BlockSigners)] = core.GenesisAccount{ genesis.Alloc[common.BlockSignersBinary] = core.GenesisAccount{
Balance: big.NewInt(0), Balance: big.NewInt(0),
Code: code, Code: code,
Storage: storage, Storage: storage,
@ -291,7 +291,7 @@ func (w *wizard) makeGenesis() {
code, _ = contractBackend.CodeAt(ctx, randomizeAddress, nil) code, _ = contractBackend.CodeAt(ctx, randomizeAddress, nil)
storage = make(map[common.Hash]common.Hash) storage = make(map[common.Hash]common.Hash)
contractBackend.ForEachStorageAt(ctx, randomizeAddress, nil, f) contractBackend.ForEachStorageAt(ctx, randomizeAddress, nil, f)
genesis.Alloc[common.HexToAddress(common.RandomizeSMC)] = core.GenesisAccount{ genesis.Alloc[common.RandomizeSMCBinary] = core.GenesisAccount{
Balance: big.NewInt(0), Balance: big.NewInt(0),
Code: code, Code: code,
Storage: storage, Storage: storage,
@ -330,7 +330,7 @@ func (w *wizard) makeGenesis() {
subBalance.Add(subBalance, big.NewInt(int64(len(signers))*50*1000)) subBalance.Add(subBalance, big.NewInt(int64(len(signers))*50*1000))
subBalance.Mul(subBalance, big.NewInt(1000000000000000000)) subBalance.Mul(subBalance, big.NewInt(1000000000000000000))
balance.Sub(balance, subBalance) // 12m - i * 50k balance.Sub(balance, subBalance) // 12m - i * 50k
genesis.Alloc[common.HexToAddress(common.TeamAddr)] = core.GenesisAccount{ genesis.Alloc[common.TeamAddrBinary] = core.GenesisAccount{
Balance: balance, Balance: balance,
Code: code, Code: code,
Storage: storage, Storage: storage,

View file

@ -50,6 +50,20 @@ const (
XDCZApplyMethod = "0xc6b32f34" XDCZApplyMethod = "0xc6b32f34"
) )
var (
BlockSignersBinary = Address{19: 0x89} // xdc0000000000000000000000000000000000000089
MasternodeVotingSMCBinary = Address{19: 0x88} // xdc0000000000000000000000000000000000000088
RandomizeSMCBinary = Address{19: 0x90} // xdc0000000000000000000000000000000000000090
FoudationAddrBinary = Address{19: 0x68} // xdc0000000000000000000000000000000000000068
TeamAddrBinary = Address{19: 0x99} // xdc0000000000000000000000000000000000000099
XDCXAddrBinary = Address{19: 0x91} // xdc0000000000000000000000000000000000000091
TradingStateAddrBinary = Address{19: 0x92} // xdc0000000000000000000000000000000000000092
XDCXLendingAddressBinary = Address{19: 0x93} // xdc0000000000000000000000000000000000000093
XDCXLendingFinalizedTradeAddressBinary = Address{19: 0x94} // xdc0000000000000000000000000000000000000094
XDCNativeAddressBinary = Address{19: 0x01} // xdc0000000000000000000000000000000000000001
LendingLockAddressBinary = Address{19: 0x11} // xdc0000000000000000000000000000000000000011
)
var ( var (
hashT = reflect.TypeOf(Hash{}) hashT = reflect.TypeOf(Hash{})
addressT = reflect.TypeOf(Address{}) addressT = reflect.TypeOf(Address{})
@ -256,7 +270,7 @@ func (a *Address) Set(other Address) {
// MarshalText returns the hex representation of a. // MarshalText returns the hex representation of a.
func (a Address) MarshalText() ([]byte, error) { func (a Address) MarshalText() ([]byte, error) {
// Handle '0x' or 'xdc' prefix here. // Handle '0x' or 'xdc' prefix here.
if (Enable0xPrefix) { if Enable0xPrefix {
return hexutil.Bytes(a[:]).MarshalText() return hexutil.Bytes(a[:]).MarshalText()
} else { } else {
return hexutil.Bytes(a[:]).MarshalXDCText() return hexutil.Bytes(a[:]).MarshalXDCText()

View file

@ -167,3 +167,39 @@ func TestRemoveItemInArray(t *testing.T) {
t.Error("fail remove item from array address") t.Error("fail remove item from array address")
} }
} }
var testCases = []struct {
bin Address
str string
}{
{BlockSignersBinary, BlockSigners},
{MasternodeVotingSMCBinary, MasternodeVotingSMC},
{RandomizeSMCBinary, RandomizeSMC},
{FoudationAddrBinary, FoudationAddr},
{TeamAddrBinary, TeamAddr},
{XDCXAddrBinary, XDCXAddr},
{TradingStateAddrBinary, TradingStateAddr},
{XDCXLendingAddressBinary, XDCXLendingAddress},
{XDCXLendingFinalizedTradeAddressBinary, XDCXLendingFinalizedTradeAddress},
{XDCNativeAddressBinary, XDCNativeAddress},
{LendingLockAddressBinary, LendingLockAddress},
}
func TestBinaryAddressToString(t *testing.T) {
for _, tt := range testCases {
have := tt.bin.String()
want := tt.str
if have != want {
t.Errorf("fail to convert binary address to string address\nwant:%s\nhave:%s", have, want)
}
}
}
func TestStringToBinaryAddress(t *testing.T) {
for _, tt := range testCases {
want := tt.bin
have := HexToAddress(tt.str)
if have != want {
t.Errorf("fail to convert string address to binary address\nwant:%s\nhave:%s", have, want)
}
}
}

View file

@ -259,7 +259,7 @@ func (api *API) GetV2BlockByHash(blockHash common.Hash) *V2BlockInfo {
func (api *API) NetworkInformation() NetworkInformation { func (api *API) NetworkInformation() NetworkInformation {
info := NetworkInformation{} info := NetworkInformation{}
info.NetworkId = api.chain.Config().ChainId info.NetworkId = api.chain.Config().ChainId
info.XDCValidatorAddress = common.HexToAddress(common.MasternodeVotingSMC) info.XDCValidatorAddress = common.MasternodeVotingSMCBinary
if common.IsTestnet { if common.IsTestnet {
info.LendingAddress = common.HexToAddress(common.LendingRegistrationSMCTestnet) info.LendingAddress = common.HexToAddress(common.LendingRegistrationSMCTestnet)
info.RelayerRegistrationAddress = common.HexToAddress(common.RelayerRegistrationSMCTestnet) info.RelayerRegistrationAddress = common.HexToAddress(common.RelayerRegistrationSMCTestnet)

View file

@ -144,11 +144,11 @@ func getCommonBackend(t *testing.T, chainConfig *params.ChainConfig) *backends.S
// create test backend with smart contract in it // create test backend with smart contract in it
contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{
acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)},
voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, voterAddr: {Balance: new(big.Int).SetUint64(10000000000)},
common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution
}, 10000000, chainConfig) }, 10000000, chainConfig)
return contractBackend2 return contractBackend2
@ -180,7 +180,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err
if !ok { if !ok {
return nil, fmt.Errorf("big int init failed") return nil, fmt.Errorf("big int init failed")
} }
to := common.HexToAddress(common.MasternodeVotingSMC) to := common.MasternodeVotingSMCBinary
tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data)
signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey) signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey)
@ -213,7 +213,7 @@ func GetSnapshotSigner(bc *BlockChain, header *types.Header) (signersList, error
} }
func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes { func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes {
addr := common.HexToAddress(common.MasternodeVotingSMC) addr := common.MasternodeVotingSMCBinary
validator, err := contractValidator.NewXDCValidator(addr, backend) validator, err := contractValidator.NewXDCValidator(addr, backend)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -105,7 +105,7 @@ func voteTX(gasLimit uint64, nonce uint64, addr string) (*types.Transaction, err
if !ok { if !ok {
return nil, fmt.Errorf("big int init failed") return nil, fmt.Errorf("big int init failed")
} }
to := common.HexToAddress(common.MasternodeVotingSMC) to := common.MasternodeVotingSMCBinary
tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data) tx := types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data)
signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey) signedTX, err := types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(chainID)), voterKey)
@ -189,11 +189,11 @@ func getCommonBackend(t *testing.T, chainConfig *params.ChainConfig) *backends.S
// create test backend with smart contract in it // create test backend with smart contract in it
contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{
acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)},
voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, voterAddr: {Balance: new(big.Int).SetUint64(10000000000)},
common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution
}, 10000000, chainConfig) }, 10000000, chainConfig)
return contractBackend2 return contractBackend2
@ -273,18 +273,18 @@ func getMultiCandidatesBackend(t *testing.T, chainConfig *params.ChainConfig, n
// create test backend with smart contract in it // create test backend with smart contract in it
contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{ contractBackend2 := backends.NewXDCSimulatedBackend(core.GenesisAlloc{
acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc1Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc2Addr: {Balance: new(big.Int).SetUint64(10000000000)},
acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)}, acc3Addr: {Balance: new(big.Int).SetUint64(10000000000)},
voterAddr: {Balance: new(big.Int).SetUint64(10000000000)}, voterAddr: {Balance: new(big.Int).SetUint64(10000000000)},
common.HexToAddress(common.MasternodeVotingSMC): {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution common.MasternodeVotingSMCBinary: {Balance: new(big.Int).SetUint64(1), Code: code, Storage: storage}, // Binding the MasternodeVotingSMC with newly created 'code' for SC execution
}, 10000000, chainConfig) }, 10000000, chainConfig)
return contractBackend2 return contractBackend2
} }
func signingTxWithKey(header *types.Header, nonce uint64, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { func signingTxWithKey(header *types.Header, nonce uint64, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) {
tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.HexToAddress(common.BlockSigners)) tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.BlockSignersBinary)
s := types.LatestSignerForChainID(big.NewInt(chainID)) s := types.LatestSignerForChainID(big.NewInt(chainID))
h := s.Hash(tx) h := s.Hash(tx)
sig, err := crypto.Sign(h[:], privateKey) sig, err := crypto.Sign(h[:], privateKey)
@ -299,7 +299,7 @@ func signingTxWithKey(header *types.Header, nonce uint64, privateKey *ecdsa.Priv
} }
func signingTxWithSignerFn(header *types.Header, nonce uint64, signer common.Address, signFn func(account accounts.Account, hash []byte) ([]byte, error)) (*types.Transaction, error) { func signingTxWithSignerFn(header *types.Header, nonce uint64, signer common.Address, signFn func(account accounts.Account, hash []byte) ([]byte, error)) (*types.Transaction, error) {
tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.HexToAddress(common.BlockSigners)) tx := contracts.CreateTxSign(header.Number, header.Hash(), nonce, common.BlockSignersBinary)
s := types.LatestSignerForChainID(big.NewInt(chainID)) s := types.LatestSignerForChainID(big.NewInt(chainID))
h := s.Hash(tx) h := s.Hash(tx)
sig, err := signFn(accounts.Account{Address: signer}, h[:]) sig, err := signFn(accounts.Account{Address: signer}, h[:])
@ -335,7 +335,7 @@ func GetSnapshotSigner(bc *BlockChain, header *types.Header) (signersList, error
} }
func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes { func GetCandidateFromCurrentSmartContract(backend bind.ContractBackend, t *testing.T) masterNodes {
addr := common.HexToAddress(common.MasternodeVotingSMC) addr := common.MasternodeVotingSMCBinary
validator, err := contractValidator.NewXDCValidator(addr, backend) validator, err := contractValidator.NewXDCValidator(addr, backend)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -87,7 +87,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m
// Create and send tx to smart contract for sign validate block. // Create and send tx to smart contract for sign validate block.
nonce := pool.Nonce(account.Address) nonce := pool.Nonce(account.Address)
tx := CreateTxSign(block.Number(), block.Hash(), nonce, common.HexToAddress(common.BlockSigners)) tx := CreateTxSign(block.Number(), block.Hash(), nonce, common.BlockSignersBinary)
txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId)
if err != nil { if err != nil {
log.Error("Fail to create tx sign", "error", err) log.Error("Fail to create tx sign", "error", err)
@ -112,7 +112,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m
// Only process when private key empty in state db. // Only process when private key empty in state db.
// Save randomize key into state db. // Save randomize key into state db.
randomizeKeyValue := RandStringByte(32) randomizeKeyValue := RandStringByte(32)
tx, err := BuildTxSecretRandomize(nonce+1, common.HexToAddress(common.RandomizeSMC), chainConfig.XDPoS.Epoch, randomizeKeyValue) tx, err := BuildTxSecretRandomize(nonce+1, common.RandomizeSMCBinary, chainConfig.XDPoS.Epoch, randomizeKeyValue)
if err != nil { if err != nil {
log.Error("Fail to get tx opening for randomize", "error", err) log.Error("Fail to get tx opening for randomize", "error", err)
return err return err
@ -141,7 +141,7 @@ func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, m
return err return err
} }
tx, err := BuildTxOpeningRandomize(nonce+1, common.HexToAddress(common.RandomizeSMC), randomizeKeyValue) tx, err := BuildTxOpeningRandomize(nonce+1, common.RandomizeSMCBinary, randomizeKeyValue)
if err != nil { if err != nil {
log.Error("Fail to get tx opening for randomize", "error", err) log.Error("Fail to get tx opening for randomize", "error", err)
return err return err
@ -232,7 +232,7 @@ func GetSignersByExecutingEVM(addrBlockSigner common.Address, client bind.Contra
// Get random from randomize contract. // Get random from randomize contract.
func GetRandomizeFromContract(client bind.ContractBackend, addrMasternode common.Address) (int64, error) { func GetRandomizeFromContract(client bind.ContractBackend, addrMasternode common.Address) (int64, error) {
randomize, err := randomizeContract.NewXDCRandomize(common.HexToAddress(common.RandomizeSMC), client) randomize, err := randomizeContract.NewXDCRandomize(common.RandomizeSMCBinary, client)
if err != nil { if err != nil {
log.Error("Fail to get instance of randomize", "error", err) log.Error("Fail to get instance of randomize", "error", err)
} }

View file

@ -150,7 +150,7 @@ func TestRewardBalance(t *testing.T) {
logCaps[i] = &logCap{accounts[randIndex].From.String(), randCap} logCaps[i] = &logCap{accounts[randIndex].From.String(), randCap}
} }
foundationAddr := common.HexToAddress(common.FoudationAddr) foundationAddr := common.FoudationAddrBinary
totalReward := new(big.Int).SetInt64(15 * 1000) totalReward := new(big.Int).SetInt64(15 * 1000)
rewards, err := GetRewardBalancesRate(foundationAddr, acc3Addr, totalReward, baseValidator) rewards, err := GetRewardBalancesRate(foundationAddr, acc3Addr, totalReward, baseValidator)
if err != nil { if err != nil {
@ -309,13 +309,13 @@ func TestStatedbUtils(t *testing.T) {
return true return true
} }
contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f) contractBackend.ForEachStorageAt(ctx, validatorAddress, nil, f)
genesisAlloc[common.HexToAddress(common.MasternodeVotingSMC)] = core.GenesisAccount{ genesisAlloc[common.MasternodeVotingSMCBinary] = core.GenesisAccount{
Balance: validatorCap, Balance: validatorCap,
Code: code, Code: code,
Storage: storage, Storage: storage,
} }
contractBackendForValidator := backends.NewXDCSimulatedBackend(genesisAlloc, 10000000, params.TestXDPoSMockChainConfig) contractBackendForValidator := backends.NewXDCSimulatedBackend(genesisAlloc, 10000000, params.TestXDPoSMockChainConfig)
validator, err := NewValidator(transactOpts, common.HexToAddress(common.MasternodeVotingSMC), contractBackendForValidator) validator, err := NewValidator(transactOpts, common.MasternodeVotingSMCBinary, contractBackendForValidator)
if err != nil { if err != nil {
t.Fatalf("can't get validator object: %v", err) t.Fatalf("can't get validator object: %v", err)
} }

View file

@ -2562,7 +2562,7 @@ func (bc *BlockChain) UpdateM1() error {
if err != nil { if err != nil {
return err return err
} }
addr := common.HexToAddress(common.MasternodeVotingSMC) addr := common.MasternodeVotingSMCBinary
validator, err := contractValidator.NewXDCValidator(addr, client) validator, err := contractValidator.NewXDCValidator(addr, client)
if err != nil { if err != nil {
return err return err

View file

@ -554,10 +554,10 @@ func (pool *LendingPool) validateBalance(cloneStateDb *state.StateDB, cloneLendi
} }
} }
if lendTokenXDCPrice == nil || lendTokenXDCPrice.Sign() == 0 { if lendTokenXDCPrice == nil || lendTokenXDCPrice.Sign() == 0 {
if tx.LendingToken().String() == common.XDCNativeAddress { if tx.LendingToken() == common.XDCNativeAddressBinary {
lendTokenXDCPrice = common.BasePrice lendTokenXDCPrice = common.BasePrice
} else { } else {
lendTokenXDCPrice, err = lendingServ.GetMediumTradePriceBeforeEpoch(pool.chain, cloneStateDb, cloneTradingStateDb, tx.LendingToken(), common.HexToAddress(common.XDCNativeAddress)) lendTokenXDCPrice, err = lendingServ.GetMediumTradePriceBeforeEpoch(pool.chain, cloneStateDb, cloneTradingStateDb, tx.LendingToken(), common.XDCNativeAddressBinary)
if err != nil { if err != nil {
return err return err
} }

View file

@ -3,6 +3,13 @@ package core
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"math/big"
"strconv"
"strings"
"testing"
"time"
"github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate" "github.com/XinFinOrg/XDPoSChain/XDCxlending/lendingstate"
"github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/types" "github.com/XinFinOrg/XDPoSChain/core/types"
@ -10,12 +17,6 @@ import (
"github.com/XinFinOrg/XDPoSChain/crypto/sha3" "github.com/XinFinOrg/XDPoSChain/crypto/sha3"
"github.com/XinFinOrg/XDPoSChain/ethclient" "github.com/XinFinOrg/XDPoSChain/ethclient"
"github.com/XinFinOrg/XDPoSChain/rpc" "github.com/XinFinOrg/XDPoSChain/rpc"
"log"
"math/big"
"strconv"
"strings"
"testing"
"time"
) )
type LendingMsg struct { type LendingMsg struct {
@ -197,7 +198,7 @@ func TestSendLending(t *testing.T) {
testSendLending(key, nonce, USDAddress, common.Address{}, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, USDAddress, common.Address{}, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
testSendLending(key, nonce, USDAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, USDAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
@ -206,7 +207,7 @@ func TestSendLending(t *testing.T) {
testSendLending(key, nonce, BTCAddress, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, BTCAddress, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
testSendLending(key, nonce, BTCAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, BTCAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E18, big.NewInt(1)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
@ -221,19 +222,19 @@ func TestSendLending(t *testing.T) {
// lendToken: XDC, collateral: BTC // lendToken: XDC, collateral: BTC
// amount 1000 XDC // amount 1000 XDC
testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, common.XDCNativeAddressBinary, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), BTCAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, common.XDCNativeAddressBinary, BTCAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
// lendToken: XDC, collateral: ETH // lendToken: XDC, collateral: ETH
// amount 1000 XDC // amount 1000 XDC
testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, common.XDCNativeAddressBinary, common.Address{}, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Investing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
testSendLending(key, nonce, common.HexToAddress(common.XDCNativeAddress), ETHAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, common.XDCNativeAddressBinary, ETHAddress, new(big.Int).Mul(_1E18, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
nonce++ nonce++
time.Sleep(time.Second) time.Sleep(time.Second)
} }
@ -282,6 +283,6 @@ func TestRecallLending(t *testing.T) {
t.Error("fail to get nonce") t.Error("fail to get nonce")
t.FailNow() t.FailNow()
} }
testSendLending(key, nonce, USDAddress, common.HexToAddress(common.XDCNativeAddress), new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "") testSendLending(key, nonce, USDAddress, common.XDCNativeAddressBinary, new(big.Int).Mul(_1E8, big.NewInt(1000)), interestRate, lendingstate.Borrowing, lendingstate.LendingStatusNew, true, 0, 0, common.Hash{}, "")
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
} }

View file

@ -2,17 +2,18 @@ package core
import ( import (
"context" "context"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/crypto"
"github.com/XinFinOrg/XDPoSChain/ethclient"
"github.com/XinFinOrg/XDPoSChain/rpc"
"log" "log"
"math/big" "math/big"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/crypto"
"github.com/XinFinOrg/XDPoSChain/ethclient"
"github.com/XinFinOrg/XDPoSChain/rpc"
) )
type OrderMsg struct { type OrderMsg struct {
@ -89,7 +90,7 @@ func testSendOrder(t *testing.T, amount, price *big.Int, side string, status str
Price: price, Price: price,
ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"),
UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey),
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: BTCAddress, QuoteToken: BTCAddress,
Status: status, Status: status,
Side: side, Side: side,
@ -124,7 +125,7 @@ func testSendOrderXDCUSD(t *testing.T, amount, price *big.Int, side string, stat
Price: price, Price: price,
ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"),
UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey),
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: USDAddress, QuoteToken: USDAddress,
Status: status, Status: status,
Side: side, Side: side,
@ -194,7 +195,7 @@ func testSendOrderXDCBTC(t *testing.T, amount, price *big.Int, side string, stat
Price: price, Price: price,
ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"), ExchangeAddress: common.HexToAddress("0x0D3ab14BBaD3D99F4203bd7a11aCB94882050E7e"),
UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey), UserAddress: crypto.PubkeyToAddress(privateKey.PublicKey),
BaseToken: common.HexToAddress(common.XDCNativeAddress), BaseToken: common.XDCNativeAddressBinary,
QuoteToken: BTCAddress, QuoteToken: BTCAddress,
Status: status, Status: status,
Side: side, Side: side,

View file

@ -796,6 +796,6 @@ func (s *StateDB) GetOwner(candidate common.Address) common.Address {
// validatorsState[_candidate].owner; // validatorsState[_candidate].owner;
locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot)
locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0))) locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0)))
ret := s.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateOwner)) ret := s.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateOwner))
return common.HexToAddress(ret.Hex()) return common.HexToAddress(ret.Hex())
} }

View file

@ -20,7 +20,7 @@ func GetSigners(statedb *StateDB, block *types.Block) []common.Address {
slot := slotBlockSignerMapping["blockSigners"] slot := slotBlockSignerMapping["blockSigners"]
keys := []common.Hash{} keys := []common.Hash{}
keyArrSlot := GetLocMappingAtKey(block.Hash(), slot) keyArrSlot := GetLocMappingAtKey(block.Hash(), slot)
arrSlot := statedb.GetState(common.HexToAddress(common.BlockSigners), common.BigToHash(keyArrSlot)) arrSlot := statedb.GetState(common.BlockSignersBinary, common.BigToHash(keyArrSlot))
arrLength := arrSlot.Big().Uint64() arrLength := arrSlot.Big().Uint64()
for i := uint64(0); i < arrLength; i++ { for i := uint64(0); i < arrLength; i++ {
key := GetLocDynamicArrAtElement(common.BigToHash(keyArrSlot), i, 1) key := GetLocDynamicArrAtElement(common.BigToHash(keyArrSlot), i, 1)
@ -28,7 +28,7 @@ func GetSigners(statedb *StateDB, block *types.Block) []common.Address {
} }
rets := []common.Address{} rets := []common.Address{}
for _, key := range keys { for _, key := range keys {
ret := statedb.GetState(common.HexToAddress(common.BlockSigners), key) ret := statedb.GetState(common.BlockSignersBinary, key)
rets = append(rets, common.HexToAddress(ret.Hex())) rets = append(rets, common.HexToAddress(ret.Hex()))
} }
@ -45,7 +45,7 @@ var (
func GetSecret(statedb *StateDB, address common.Address) [][32]byte { func GetSecret(statedb *StateDB, address common.Address) [][32]byte {
slot := slotRandomizeMapping["randomSecret"] slot := slotRandomizeMapping["randomSecret"]
locSecret := GetLocMappingAtKey(address.Hash(), slot) locSecret := GetLocMappingAtKey(address.Hash(), slot)
arrLength := statedb.GetState(common.HexToAddress(common.RandomizeSMC), common.BigToHash(locSecret)) arrLength := statedb.GetState(common.RandomizeSMCBinary, common.BigToHash(locSecret))
keys := []common.Hash{} keys := []common.Hash{}
for i := uint64(0); i < arrLength.Big().Uint64(); i++ { for i := uint64(0); i < arrLength.Big().Uint64(); i++ {
key := GetLocDynamicArrAtElement(common.BigToHash(locSecret), i, 1) key := GetLocDynamicArrAtElement(common.BigToHash(locSecret), i, 1)
@ -53,7 +53,7 @@ func GetSecret(statedb *StateDB, address common.Address) [][32]byte {
} }
rets := [][32]byte{} rets := [][32]byte{}
for _, key := range keys { for _, key := range keys {
ret := statedb.GetState(common.HexToAddress(common.RandomizeSMC), key) ret := statedb.GetState(common.RandomizeSMCBinary, key)
rets = append(rets, ret) rets = append(rets, ret)
} }
return rets return rets
@ -62,7 +62,7 @@ func GetSecret(statedb *StateDB, address common.Address) [][32]byte {
func GetOpening(statedb *StateDB, address common.Address) [32]byte { func GetOpening(statedb *StateDB, address common.Address) [32]byte {
slot := slotRandomizeMapping["randomOpening"] slot := slotRandomizeMapping["randomOpening"]
locOpening := GetLocMappingAtKey(address.Hash(), slot) locOpening := GetLocMappingAtKey(address.Hash(), slot)
ret := statedb.GetState(common.HexToAddress(common.RandomizeSMC), common.BigToHash(locOpening)) ret := statedb.GetState(common.RandomizeSMCBinary, common.BigToHash(locOpening))
return ret return ret
} }
@ -92,13 +92,13 @@ var (
func GetCandidates(statedb *StateDB) []common.Address { func GetCandidates(statedb *StateDB) []common.Address {
slot := slotValidatorMapping["candidates"] slot := slotValidatorMapping["candidates"]
slotHash := common.BigToHash(new(big.Int).SetUint64(slot)) slotHash := common.BigToHash(new(big.Int).SetUint64(slot))
arrLength := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), slotHash) arrLength := statedb.GetState(common.MasternodeVotingSMCBinary, slotHash)
count := arrLength.Big().Uint64() count := arrLength.Big().Uint64()
rets := make([]common.Address, 0, count) rets := make([]common.Address, 0, count)
for i := uint64(0); i < count; i++ { for i := uint64(0); i < count; i++ {
key := GetLocDynamicArrAtElement(slotHash, i, 1) key := GetLocDynamicArrAtElement(slotHash, i, 1)
ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), key) ret := statedb.GetState(common.MasternodeVotingSMCBinary, key)
if !ret.IsZero() { if !ret.IsZero() {
rets = append(rets, common.HexToAddress(ret.Hex())) rets = append(rets, common.HexToAddress(ret.Hex()))
} }
@ -112,7 +112,7 @@ func GetCandidateOwner(statedb *StateDB, candidate common.Address) common.Addres
// validatorsState[_candidate].owner; // validatorsState[_candidate].owner;
locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot)
locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0))) locCandidateOwner := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(0)))
ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateOwner)) ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateOwner))
return common.HexToAddress(ret.Hex()) return common.HexToAddress(ret.Hex())
} }
@ -121,7 +121,7 @@ func GetCandidateCap(statedb *StateDB, candidate common.Address) *big.Int {
// validatorsState[_candidate].cap; // validatorsState[_candidate].cap;
locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot)
locCandidateCap := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(1))) locCandidateCap := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(1)))
ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locCandidateCap)) ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locCandidateCap))
return ret.Big() return ret.Big()
} }
@ -129,7 +129,7 @@ func GetVoters(statedb *StateDB, candidate common.Address) []common.Address {
//mapping(address => address[]) voters; //mapping(address => address[]) voters;
slot := slotValidatorMapping["voters"] slot := slotValidatorMapping["voters"]
locVoters := GetLocMappingAtKey(candidate.Hash(), slot) locVoters := GetLocMappingAtKey(candidate.Hash(), slot)
arrLength := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BigToHash(locVoters)) arrLength := statedb.GetState(common.MasternodeVotingSMCBinary, common.BigToHash(locVoters))
keys := []common.Hash{} keys := []common.Hash{}
for i := uint64(0); i < arrLength.Big().Uint64(); i++ { for i := uint64(0); i < arrLength.Big().Uint64(); i++ {
key := GetLocDynamicArrAtElement(common.BigToHash(locVoters), i, 1) key := GetLocDynamicArrAtElement(common.BigToHash(locVoters), i, 1)
@ -137,7 +137,7 @@ func GetVoters(statedb *StateDB, candidate common.Address) []common.Address {
} }
rets := []common.Address{} rets := []common.Address{}
for _, key := range keys { for _, key := range keys {
ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), key) ret := statedb.GetState(common.MasternodeVotingSMCBinary, key)
rets = append(rets, common.HexToAddress(ret.Hex())) rets = append(rets, common.HexToAddress(ret.Hex()))
} }
@ -149,6 +149,6 @@ func GetVoterCap(statedb *StateDB, candidate, voter common.Address) *big.Int {
locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot) locValidatorsState := GetLocMappingAtKey(candidate.Hash(), slot)
locCandidateVoters := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(2))) locCandidateVoters := locValidatorsState.Add(locValidatorsState, new(big.Int).SetUint64(uint64(2)))
retByte := crypto.Keccak256(voter.Hash().Bytes(), common.BigToHash(locCandidateVoters).Bytes()) retByte := crypto.Keccak256(voter.Hash().Bytes(), common.BigToHash(locCandidateVoters).Bytes())
ret := statedb.GetState(common.HexToAddress(common.MasternodeVotingSMC), common.BytesToHash(retByte)) ret := statedb.GetState(common.MasternodeVotingSMCBinary, common.BytesToHash(retByte))
return ret.Big() return ret.Big()
} }

View file

@ -80,7 +80,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, tra
misc.ApplyDAOHardFork(statedb) misc.ApplyDAOHardFork(statedb)
} }
if common.TIPSigning.Cmp(header.Number) == 0 { if common.TIPSigning.Cmp(header.Number) == 0 {
statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) statedb.DeleteAddress(common.BlockSignersBinary)
} }
parentState := statedb.Copy() parentState := statedb.Copy()
InitSignerInTransactions(p.config, header, block.Transactions()) InitSignerInTransactions(p.config, header, block.Transactions())
@ -146,7 +146,7 @@ func (p *StateProcessor) ProcessBlockNoValidator(cBlock *CalculatedBlock, stated
misc.ApplyDAOHardFork(statedb) misc.ApplyDAOHardFork(statedb)
} }
if common.TIPSigning.Cmp(header.Number) == 0 { if common.TIPSigning.Cmp(header.Number) == 0 {
statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) statedb.DeleteAddress(common.BlockSignersBinary)
} }
if cBlock.stop { if cBlock.stop {
return nil, nil, 0, ErrStopPreparingBlock return nil, nil, 0, ErrStopPreparingBlock
@ -215,13 +215,13 @@ func (p *StateProcessor) ProcessBlockNoValidator(cBlock *CalculatedBlock, stated
// for the transaction, gas used and an error if the transaction failed, // for the transaction, gas used and an error if the transaction failed,
// indicating the block was invalid. // indicating the block was invalid.
func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*big.Int, bc *BlockChain, author *common.Address, gp *GasPool, statedb *state.StateDB, XDCxState *tradingstate.TradingStateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error, bool) { func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*big.Int, bc *BlockChain, author *common.Address, gp *GasPool, statedb *state.StateDB, XDCxState *tradingstate.TradingStateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error, bool) {
if tx.To() != nil && tx.To().String() == common.BlockSigners && config.IsTIPSigning(header.Number) { if tx.To() != nil && *tx.To() == common.BlockSignersBinary && config.IsTIPSigning(header.Number) {
return ApplySignTransaction(config, statedb, header, tx, usedGas) return ApplySignTransaction(config, statedb, header, tx, usedGas)
} }
if tx.To() != nil && tx.To().String() == common.TradingStateAddr && config.IsTIPXDCXReceiver(header.Number) { if tx.To() != nil && *tx.To() == common.TradingStateAddrBinary && config.IsTIPXDCXReceiver(header.Number) {
return ApplyEmptyTransaction(config, statedb, header, tx, usedGas) return ApplyEmptyTransaction(config, statedb, header, tx, usedGas)
} }
if tx.To() != nil && tx.To().String() == common.XDCXLendingAddress && config.IsTIPXDCXReceiver(header.Number) { if tx.To() != nil && *tx.To() == common.XDCXLendingAddressBinary && config.IsTIPXDCXReceiver(header.Number) {
return ApplyEmptyTransaction(config, statedb, header, tx, usedGas) return ApplyEmptyTransaction(config, statedb, header, tx, usedGas)
} }
if tx.IsTradingTransaction() && config.IsTIPXDCXReceiver(header.Number) { if tx.IsTradingTransaction() && config.IsTIPXDCXReceiver(header.Number) {
@ -473,7 +473,7 @@ func ApplySignTransaction(config *params.ChainConfig, statedb *state.StateDB, he
// if the transaction created a contract, store the creation address in the receipt. // if the transaction created a contract, store the creation address in the receipt.
// Set the receipt logs and create a bloom for filtering // Set the receipt logs and create a bloom for filtering
log := &types.Log{} log := &types.Log{}
log.Address = common.HexToAddress(common.BlockSigners) log.Address = common.BlockSignersBinary
log.BlockNumber = header.Number.Uint64() log.BlockNumber = header.Number.Uint64()
statedb.AddLog(log) statedb.AddLog(log)
receipt.Logs = statedb.GetLogs(tx.Hash()) receipt.Logs = statedb.GetLogs(tx.Hash())

View file

@ -410,8 +410,8 @@ func (tx *Transaction) IsSpecialTransaction() bool {
return false return false
} }
toBytes := tx.To().Bytes() toBytes := tx.To().Bytes()
randomizeSMCBytes := common.HexToAddress(common.RandomizeSMC).Bytes() randomizeSMCBytes := common.RandomizeSMCBinary.Bytes()
blockSignersBytes := common.HexToAddress(common.BlockSigners).Bytes() blockSignersBytes := common.BlockSignersBinary.Bytes()
return bytes.Equal(toBytes, randomizeSMCBytes) || bytes.Equal(toBytes, blockSignersBytes) return bytes.Equal(toBytes, randomizeSMCBytes) || bytes.Equal(toBytes, blockSignersBytes)
} }
@ -420,7 +420,7 @@ func (tx *Transaction) IsTradingTransaction() bool {
return false return false
} }
if tx.To().String() != common.XDCXAddr { if *tx.To() != common.XDCXAddrBinary {
return false return false
} }
@ -432,7 +432,7 @@ func (tx *Transaction) IsLendingTransaction() bool {
return false return false
} }
if tx.To().String() != common.XDCXLendingAddress { if *tx.To() != common.XDCXLendingAddressBinary {
return false return false
} }
return true return true
@ -443,7 +443,7 @@ func (tx *Transaction) IsLendingFinalizedTradeTransaction() bool {
return false return false
} }
if tx.To().String() != common.XDCXLendingFinalizedTradeAddress { if *tx.To() != common.XDCXLendingFinalizedTradeAddressBinary {
return false return false
} }
return true return true
@ -464,7 +464,7 @@ func (tx *Transaction) IsSigningTransaction() bool {
return false return false
} }
if tx.To().String() != common.BlockSigners { if *tx.To() != common.BlockSignersBinary {
return false return false
} }
@ -485,7 +485,7 @@ func (tx *Transaction) IsVotingTransaction() (bool, *common.Address) {
if tx.To() == nil { if tx.To() == nil {
return false, nil return false, nil
} }
b := (tx.To().String() == common.MasternodeVotingSMC) b := (*tx.To() == common.MasternodeVotingSMCBinary)
if !b { if !b {
return b, nil return b, nil

View file

@ -765,7 +765,7 @@ func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, ree
// Recompute transactions up to the target index. // Recompute transactions up to the target index.
feeCapacity := state.GetTRC21FeeCapacityFromState(statedb) feeCapacity := state.GetTRC21FeeCapacityFromState(statedb)
if common.TIPSigning.Cmp(block.Header().Number) == 0 { if common.TIPSigning.Cmp(block.Header().Number) == 0 {
statedb.DeleteAddress(common.HexToAddress(common.BlockSigners)) statedb.DeleteAddress(common.BlockSignersBinary)
} }
core.InitSignerInTransactions(api.config, block.Header(), block.Transactions()) core.InitSignerInTransactions(api.config, block.Header(), block.Transactions())
balanceUpdated := map[common.Address]*big.Int{} balanceUpdated := map[common.Address]*big.Int{}

View file

@ -216,7 +216,7 @@ func AttachConsensusV1Hooks(adaptor *XDPoS.XDPoS, bc *core.BlockChain, chainConf
if err != nil { if err != nil {
return nil, err return nil, err
} }
addr := common.HexToAddress(common.MasternodeVotingSMC) addr := common.MasternodeVotingSMCBinary
validator, err := contractValidator.NewXDCValidator(addr, client) validator, err := contractValidator.NewXDCValidator(addr, client)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -1197,7 +1197,7 @@ func (s *PublicBlockChainAPI) getCandidatesFromSmartContract() ([]utils.Masterno
return []utils.Masternode{}, err return []utils.Masternode{}, err
} }
addr := common.HexToAddress(common.MasternodeVotingSMC) addr := common.MasternodeVotingSMCBinary
validator, err := contractValidator.NewXDCValidator(addr, client) validator, err := contractValidator.NewXDCValidator(addr, client)
if err != nil { if err != nil {
return []utils.Masternode{}, err return []utils.Masternode{}, err

View file

@ -614,7 +614,7 @@ func (self *worker) commitNewWork() {
misc.ApplyDAOHardFork(work.state) misc.ApplyDAOHardFork(work.state)
} }
if common.TIPSigning.Cmp(header.Number) == 0 { if common.TIPSigning.Cmp(header.Number) == 0 {
work.state.DeleteAddress(common.HexToAddress(common.BlockSigners)) work.state.DeleteAddress(common.BlockSignersBinary)
} }
// won't grasp txs at checkpoint // won't grasp txs at checkpoint
var ( var (
@ -699,7 +699,7 @@ func (self *worker) commitNewWork() {
return return
} }
nonce := work.state.GetNonce(self.coinbase) nonce := work.state.GetNonce(self.coinbase)
tx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXAddr), big.NewInt(0), txMatchGasLimit, big.NewInt(0), txMatchBytes) tx := types.NewTransaction(nonce, common.XDCXAddrBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), txMatchBytes)
txM, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId) txM, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId)
if err != nil { if err != nil {
log.Error("Fail to create tx matches", "error", err) log.Error("Fail to create tx matches", "error", err)
@ -729,7 +729,7 @@ func (self *worker) commitNewWork() {
return return
} }
nonce := work.state.GetNonce(self.coinbase) nonce := work.state.GetNonce(self.coinbase)
lendingTx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXLendingAddress), big.NewInt(0), txMatchGasLimit, big.NewInt(0), lendingDataBytes) lendingTx := types.NewTransaction(nonce, common.XDCXLendingAddressBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), lendingDataBytes)
signedLendingTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, lendingTx, self.config.ChainId) signedLendingTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, lendingTx, self.config.ChainId)
if err != nil { if err != nil {
log.Error("Fail to create lending tx", "error", err) log.Error("Fail to create lending tx", "error", err)
@ -753,7 +753,7 @@ func (self *worker) commitNewWork() {
return return
} }
nonce := work.state.GetNonce(self.coinbase) nonce := work.state.GetNonce(self.coinbase)
finalizedTx := types.NewTransaction(nonce, common.HexToAddress(common.XDCXLendingFinalizedTradeAddress), big.NewInt(0), txMatchGasLimit, big.NewInt(0), finalizedTradeData) finalizedTx := types.NewTransaction(nonce, common.XDCXLendingFinalizedTradeAddressBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), finalizedTradeData)
signedFinalizedTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, finalizedTx, self.config.ChainId) signedFinalizedTx, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, finalizedTx, self.config.ChainId)
if err != nil { if err != nil {
log.Error("Fail to create lending tx", "error", err) log.Error("Fail to create lending tx", "error", err)
@ -772,7 +772,7 @@ func (self *worker) commitNewWork() {
XDCxStateRoot := work.tradingState.IntermediateRoot() XDCxStateRoot := work.tradingState.IntermediateRoot()
LendingStateRoot := work.lendingState.IntermediateRoot() LendingStateRoot := work.lendingState.IntermediateRoot()
txData := append(XDCxStateRoot.Bytes(), LendingStateRoot.Bytes()...) txData := append(XDCxStateRoot.Bytes(), LendingStateRoot.Bytes()...)
tx := types.NewTransaction(work.state.GetNonce(self.coinbase), common.HexToAddress(common.TradingStateAddr), big.NewInt(0), txMatchGasLimit, big.NewInt(0), txData) tx := types.NewTransaction(work.state.GetNonce(self.coinbase), common.TradingStateAddrBinary, big.NewInt(0), txMatchGasLimit, big.NewInt(0), txData)
txStateRoot, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId) txStateRoot, err := wallet.SignTx(accounts.Account{Address: self.coinbase}, tx, self.config.ChainId)
if err != nil { if err != nil {
log.Error("Fail to create tx state root", "error", err) log.Error("Fail to create tx state root", "error", err)
@ -857,7 +857,7 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
log.Trace("Ignoring reply protected special transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block) log.Trace("Ignoring reply protected special transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
continue continue
} }
if tx.To().Hex() == common.BlockSigners { if *tx.To() == common.BlockSignersBinary {
if len(tx.Data()) < 68 { if len(tx.Data()) < 68 {
log.Trace("Data special transaction invalid length", "hash", tx.Hash(), "data", len(tx.Data())) log.Trace("Data special transaction invalid length", "hash", tx.Hash(), "data", len(tx.Data()))
continue continue