Merge pull request #553 from JukLee0ira/noString

performance: remove extra conversions and optimize functions
This commit is contained in:
Daniel Liu 2024-06-11 21:10:05 +08:00 committed by GitHub
commit b718f3593c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 373 additions and 372 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
} }
@ -595,10 +595,11 @@ 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()) to := tx.To()
if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from.String() == author.String() { if to != nil && *to == common.TradingStateAddrBinary && *tx.From() == author {
if len(tx.Data()) >= 32 { data := tx.Data()
return common.BytesToHash(tx.Data()[:32]), nil if len(data) >= 32 {
return common.BytesToHash(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,10 +374,10 @@ 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.String() == makerOrder.ExchangeAddress.String() { if takerOrder.ExchangeAddress == makerOrder.ExchangeAddress {
if err := tradingstate.CheckRelayerFee(takerOrder.ExchangeAddress, new(big.Int).Mul(common.RelayerFee, big.NewInt(2)), statedb); err != nil { if err := tradingstate.CheckRelayerFee(takerOrder.ExchangeAddress, new(big.Int).Mul(common.RelayerFee, big.NewInt(2)), statedb); err != nil {
log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err) log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err)
return tradingstate.Zero, false, nil, nil return tradingstate.Zero, false, nil, nil

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,9 +159,9 @@ 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", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
statedb.AddBalance(addr, value) statedb.AddBalance(addr, value)
balance = statedb.GetBalance(addr) balance = statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value)
@ -186,10 +186,9 @@ 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", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
if balance.Cmp(value) < 0 { if balance.Cmp(value) < 0 {
return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value)
} }
@ -219,7 +218,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 +255,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 +307,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 +322,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

@ -696,10 +696,11 @@ 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()) to := tx.To()
if tx.To() != nil && tx.To().Hex() == common.TradingStateAddr && from.String() == author.String() { if to != nil && *to == common.TradingStateAddrBinary && *tx.From() == author {
if len(tx.Data()) >= 64 { data := tx.Data()
return common.BytesToHash(tx.Data()[32:]), nil if len(data) >= 64 {
return common.BytesToHash(data[32:]), nil
} }
} }
} }

View file

@ -260,7 +260,7 @@ func (l *LendingItem) VerifyCollateral(state *state.StateDB) error {
validCollateral := false validCollateral := false
collateralList := GetCollaterals(state, l.Relayer, l.LendingToken, l.Term) collateralList := GetCollaterals(state, l.Relayer, l.LendingToken, l.Term)
for _, collateral := range collateralList { for _, collateral := range collateralList {
if l.CollateralToken.String() == collateral.String() { if l.CollateralToken == collateral {
validCollateral = true validCollateral = true
break break
} }
@ -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,12 +114,12 @@ 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", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
statedb.AddBalance(addr, value) statedb.AddBalance(addr, value)
balance = statedb.GetBalance(addr) balance = statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: ADD XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
return nil return nil
} }
@ -141,15 +141,15 @@ 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", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
if balance.Cmp(value) < 0 { if balance.Cmp(value) < 0 {
return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) return errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value)
} }
statedb.SubBalance(addr, value) statedb.SubBalance(addr, value)
balance = statedb.GetBalance(addr) balance = statedb.GetBalance(addr)
log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE AFTER", "token", token.String(), "address", addr.String(), "balance", balance, "orderValue", value) log.Debug("ApplyXDCXMatchedTransaction settle balance: SUB XDC NATIVE BALANCE AFTER", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "orderValue", value)
return nil return nil
} }
@ -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
@ -182,10 +182,10 @@ func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Addr
balance = statedb.GetBalance(addr) balance = statedb.GetBalance(addr)
} }
if balance.Cmp(value) < 0 { if balance.Cmp(value) < 0 {
return nil, errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), token.String(), balance, value) return nil, errors.Errorf("value %s in token %s not enough , have : %s , want : %s ", addr.String(), common.XDCNativeAddress, balance, value)
} }
newBalance := new(big.Int).Sub(balance, value) newBalance := new(big.Int).Sub(balance, value)
log.Debug("CheckSubTokenBalance settle balance: SUB XDC NATIVE BALANCE ", "token", token.String(), "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) log.Debug("CheckSubTokenBalance settle balance: SUB XDC NATIVE BALANCE ", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance)
return newBalance, nil return newBalance, nil
} }
// TRC tokens // TRC tokens
@ -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
@ -219,7 +219,7 @@ func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Addr
balance = statedb.GetBalance(addr) balance = statedb.GetBalance(addr)
} }
newBalance := new(big.Int).Add(balance, value) newBalance := new(big.Int).Add(balance, value)
log.Debug("CheckAddTokenBalance settle balance: ADD XDC NATIVE BALANCE ", "token", token.String(), "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance) log.Debug("CheckAddTokenBalance settle balance: ADD XDC NATIVE BALANCE ", "token", common.XDCNativeAddress, "address", addr.String(), "balance", balance, "value", value, "newBalance", newBalance)
return newBalance, nil return newBalance, nil
} }
// TRC tokens // TRC tokens
@ -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

@ -447,7 +447,7 @@ func (l *Lending) getLendQuantity(
if err != nil || collateralTokenDecimal.Sign() == 0 { if err != nil || collateralTokenDecimal.Sign() == 0 {
return lendingstate.Zero, lendingstate.Zero, false, nil, fmt.Errorf("fail to get tokenDecimal. Token: %v . Err: %v", collateralToken.String(), err) return lendingstate.Zero, lendingstate.Zero, false, nil, fmt.Errorf("fail to get tokenDecimal. Token: %v . Err: %v", collateralToken.String(), err)
} }
if takerOrder.Relayer.String() == makerOrder.Relayer.String() { if takerOrder.Relayer == makerOrder.Relayer {
if err := lendingstate.CheckRelayerFee(takerOrder.Relayer, new(big.Int).Mul(common.RelayerLendingFee, big.NewInt(2)), statedb); err != nil { if err := lendingstate.CheckRelayerFee(takerOrder.Relayer, new(big.Int).Mul(common.RelayerLendingFee, big.NewInt(2)), statedb); err != nil {
log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err) log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err)
return lendingstate.Zero, lendingstate.Zero, false, nil, nil return lendingstate.Zero, lendingstate.Zero, false, nil, nil
@ -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)
@ -789,10 +789,10 @@ func (l *Lending) ProcessTopUp(lendingStateDB *lendingstate.LendingStateDB, stat
if lendingTrade == lendingstate.EmptyLendingTrade { if lendingTrade == lendingstate.EmptyLendingTrade {
return fmt.Errorf("process deposit for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId.Hex()), true, nil return fmt.Errorf("process deposit for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId.Hex()), true, nil
} }
if order.UserAddress.String() != lendingTrade.Borrower.String() { if order.UserAddress != lendingTrade.Borrower {
return fmt.Errorf("ProcessTopUp: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex()), true, nil return fmt.Errorf("ProcessTopUp: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex()), true, nil
} }
if order.Relayer.String() != lendingTrade.BorrowingRelayer.String() { if order.Relayer != lendingTrade.BorrowingRelayer {
return fmt.Errorf("ProcessTopUp: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex()), true, nil return fmt.Errorf("ProcessTopUp: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex()), true, nil
} }
if order.Quantity.Sign() <= 0 || lendingTrade.TradeId != lendingTradeId.Big().Uint64() { if order.Quantity.Sign() <= 0 || lendingTrade.TradeId != lendingTradeId.Big().Uint64() {
@ -810,10 +810,10 @@ func (l *Lending) ProcessRepay(header *types.Header, chain consensus.ChainContex
if lendingTrade == lendingstate.EmptyLendingTrade || lendingTrade.TradeId != lendingTradeIdHash.Big().Uint64() { if lendingTrade == lendingstate.EmptyLendingTrade || lendingTrade.TradeId != lendingTradeIdHash.Big().Uint64() {
return nil, fmt.Errorf("ProcessRepay for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId) return nil, fmt.Errorf("ProcessRepay for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId)
} }
if order.UserAddress.String() != lendingTrade.Borrower.String() { if order.UserAddress != lendingTrade.Borrower {
return nil, fmt.Errorf("ProcessRepay: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex()) return nil, fmt.Errorf("ProcessRepay: invalid userAddress . UserAddress: %s . Borrower: %s", order.UserAddress.Hex(), lendingTrade.Borrower.Hex())
} }
if order.Relayer.String() != lendingTrade.BorrowingRelayer.String() { if order.Relayer != lendingTrade.BorrowingRelayer {
return nil, fmt.Errorf("ProcessRepay: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex()) return nil, fmt.Errorf("ProcessRepay: invalid relayerAddress . Got: %s . Expect: %s", order.Relayer.Hex(), lendingTrade.BorrowingRelayer.Hex())
} }
return l.ProcessRepayLendingTrade(header, chain, lendingStateDB, statedb, tradingstateDB, lendingBook, lendingTradeId) return l.ProcessRepayLendingTrade(header, chain, lendingStateDB, statedb, tradingstateDB, lendingBook, lendingTradeId)
@ -854,9 +854,9 @@ 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.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
err = lendingstate.AddTokenBalance(lendingTrade.Investor, repayAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.AddTokenBalance(lendingTrade.Investor, repayAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
@ -897,9 +897,9 @@ 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.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
err = lendingstate.AddTokenBalance(lendingTrade.Investor, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.AddTokenBalance(lendingTrade.Investor, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
@ -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,9 +1133,9 @@ 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.LendingLockAddress, "quantity", *quantity, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
oldLockedAmount := lendingTrade.CollateralLockedAmount oldLockedAmount := lendingTrade.CollateralLockedAmount
newLockedAmount := new(big.Int).Add(quantity, oldLockedAmount) newLockedAmount := new(big.Int).Add(quantity, oldLockedAmount)
@ -1199,9 +1199,9 @@ 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.LendingLockAddress, "lendingTrade.CollateralLockedAmount", *lendingTrade.CollateralLockedAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
err = lendingstate.AddTokenBalance(lendingTrade.Borrower, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb) err = lendingstate.AddTokenBalance(lendingTrade.Borrower, lendingTrade.CollateralLockedAmount, lendingTrade.CollateralToken, statedb)
if err != nil { if err != nil {
@ -1255,9 +1255,9 @@ 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.LendingLockAddress, "recallAmount", *recallAmount, "lendingTrade.CollateralToken", lendingTrade.CollateralToken)
} }
lendingStateDB.UpdateLiquidationPrice(lendingBook, lendingTrade.TradeId, newLiquidationPrice) lendingStateDB.UpdateLiquidationPrice(lendingBook, lendingTrade.TradeId, newLiquidationPrice)

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

@ -64,7 +64,7 @@ func (s *SnapshotV2) GetMappedCandidates() map[common.Address]struct{} {
func (s *SnapshotV2) IsCandidates(address common.Address) bool { func (s *SnapshotV2) IsCandidates(address common.Address) bool {
for _, n := range s.NextEpochCandidates { for _, n := range s.NextEpochCandidates {
if n.String() == address.String() { if n == address {
return true return true
} }
} }

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

@ -435,7 +435,7 @@ func (pool *LendingPool) validateNewLending(cloneStateDb *state.StateDB, cloneLe
validCollateral := false validCollateral := false
collateralList := lendingstate.GetCollaterals(cloneStateDb, tx.RelayerAddress(), tx.LendingToken(), tx.Term()) collateralList := lendingstate.GetCollaterals(cloneStateDb, tx.RelayerAddress(), tx.LendingToken(), tx.Term())
for _, collateral := range collateralList { for _, collateral := range collateralList {
if tx.CollateralToken().String() == collateral.String() { if tx.CollateralToken() == collateral {
validCollateral = true validCollateral = true
break break
} }
@ -476,10 +476,10 @@ func (pool *LendingPool) validateRepayLending(cloneStateDb *state.StateDB, clone
if lendingTrade == lendingstate.EmptyLendingTrade { if lendingTrade == lendingstate.EmptyLendingTrade {
return ErrInvalidLendingTradeID return ErrInvalidLendingTradeID
} }
if tx.UserAddress().String() != lendingTrade.Borrower.String() { if tx.UserAddress() != lendingTrade.Borrower {
return ErrInvalidLendingUserAddress return ErrInvalidLendingUserAddress
} }
if tx.RelayerAddress().String() != lendingTrade.BorrowingRelayer.String() { if tx.RelayerAddress() != lendingTrade.BorrowingRelayer {
return ErrInvalidLendingRelayer return ErrInvalidLendingRelayer
} }
if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, tx.CollateralToken()); err != nil { if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, tx.CollateralToken()); err != nil {
@ -499,10 +499,10 @@ func (pool *LendingPool) validateTopupLending(cloneStateDb *state.StateDB, clone
if lendingTrade == lendingstate.EmptyLendingTrade { if lendingTrade == lendingstate.EmptyLendingTrade {
return ErrInvalidLendingTradeID return ErrInvalidLendingTradeID
} }
if tx.UserAddress().String() != lendingTrade.Borrower.String() { if tx.UserAddress() != lendingTrade.Borrower {
return ErrInvalidLendingUserAddress return ErrInvalidLendingUserAddress
} }
if tx.RelayerAddress().String() != lendingTrade.BorrowingRelayer.String() { if tx.RelayerAddress() != lendingTrade.BorrowingRelayer {
return ErrInvalidLendingRelayer return ErrInvalidLendingRelayer
} }
if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, lendingTrade.CollateralToken); err != nil { if err := pool.validateBalance(cloneStateDb, cloneLendingStateDb, tx, lendingTrade.CollateralToken); err != nil {
@ -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,14 @@ 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) { to := tx.To()
if to != nil && *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 to != nil && *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 to != nil && *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) {
@ -233,8 +234,8 @@ func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*
} }
var balanceFee *big.Int var balanceFee *big.Int
if tx.To() != nil { if to != nil {
if value, ok := tokensFee[*tx.To()]; ok { if value, ok := tokensFee[*to]; ok {
balanceFee = value balanceFee = value
} }
} }
@ -441,7 +442,7 @@ func ApplyTransaction(config *params.ChainConfig, tokensFee map[common.Address]*
receipt.BlockNumber = header.Number receipt.BlockNumber = header.Number
receipt.TransactionIndex = uint(statedb.TxIndex()) receipt.TransactionIndex = uint(statedb.TxIndex())
if balanceFee != nil && failed { if balanceFee != nil && failed {
state.PayFeeWithTRC21TxFail(statedb, msg.From(), *tx.To()) state.PayFeeWithTRC21TxFail(statedb, msg.From(), *to)
} }
return receipt, gas, err, balanceFee != nil return receipt, gas, err, balanceFee != nil
} }
@ -473,7 +474,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

@ -32,7 +32,6 @@ import (
) )
//go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go
var ( var (
ErrInvalidSig = errors.New("invalid transaction v, r, s values") ErrInvalidSig = errors.New("invalid transaction v, r, s values")
ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures") ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures")
@ -45,11 +44,11 @@ var (
errVYParityMissing = errors.New("missing 'yParity' or 'v' field in transaction") errVYParityMissing = errors.New("missing 'yParity' or 'v' field in transaction")
errEmptyTypedTx = errors.New("empty typed transaction bytes") errEmptyTypedTx = errors.New("empty typed transaction bytes")
errNoSigner = errors.New("missing signing methods") errNoSigner = errors.New("missing signing methods")
skipNonceDestinationAddress = map[string]bool{ skipNonceDestinationAddress = map[common.Address]bool{
common.XDCXAddr: true, common.XDCXAddrBinary: true,
common.TradingStateAddr: true, common.TradingStateAddrBinary: true,
common.XDCXLendingAddress: true, common.XDCXLendingAddressBinary: true,
common.XDCXLendingFinalizedTradeAddress: true, common.XDCXLendingFinalizedTradeAddressBinary: true,
} }
) )
@ -406,121 +405,68 @@ func (tx *Transaction) TxCost(number *big.Int) *big.Int {
} }
func (tx *Transaction) IsSpecialTransaction() bool { func (tx *Transaction) IsSpecialTransaction() bool {
if tx.To() == nil { to := tx.To()
return false return to != nil && (*to == common.RandomizeSMCBinary || *to == common.BlockSignersBinary)
}
toBytes := tx.To().Bytes()
randomizeSMCBytes := common.HexToAddress(common.RandomizeSMC).Bytes()
blockSignersBytes := common.HexToAddress(common.BlockSigners).Bytes()
return bytes.Equal(toBytes, randomizeSMCBytes) || bytes.Equal(toBytes, blockSignersBytes)
} }
func (tx *Transaction) IsTradingTransaction() bool { func (tx *Transaction) IsTradingTransaction() bool {
if tx.To() == nil { to := tx.To()
return false return to != nil && *to == common.XDCXAddrBinary
}
if tx.To().String() != common.XDCXAddr {
return false
}
return true
} }
func (tx *Transaction) IsLendingTransaction() bool { func (tx *Transaction) IsLendingTransaction() bool {
if tx.To() == nil { to := tx.To()
return false return to != nil && *to == common.XDCXLendingAddressBinary
}
if tx.To().String() != common.XDCXLendingAddress {
return false
}
return true
} }
func (tx *Transaction) IsLendingFinalizedTradeTransaction() bool { func (tx *Transaction) IsLendingFinalizedTradeTransaction() bool {
if tx.To() == nil { to := tx.To()
return false return to != nil && *to == common.XDCXLendingFinalizedTradeAddressBinary
}
if tx.To().String() != common.XDCXLendingFinalizedTradeAddress {
return false
}
return true
} }
func (tx *Transaction) IsSkipNonceTransaction() bool { func (tx *Transaction) IsSkipNonceTransaction() bool {
if tx.To() == nil { to := tx.To()
return false return to != nil && skipNonceDestinationAddress[*to]
}
if skip := skipNonceDestinationAddress[tx.To().String()]; skip {
return true
}
return false
} }
func (tx *Transaction) IsSigningTransaction() bool { func (tx *Transaction) IsSigningTransaction() bool {
if tx.To() == nil { to := tx.To()
if to == nil || *to != common.BlockSignersBinary {
return false return false
} }
data := tx.Data()
if tx.To().String() != common.BlockSigners { if len(data) != (32*2 + 4) {
return false return false
} }
method := common.ToHex(data[0:4])
method := common.ToHex(tx.Data()[0:4]) return method == common.SignMethod
if method != common.SignMethod {
return false
}
if len(tx.Data()) != (32*2 + 4) {
return false
}
return true
} }
func (tx *Transaction) IsVotingTransaction() (bool, *common.Address) { func (tx *Transaction) IsVotingTransaction() (bool, *common.Address) {
if tx.To() == nil { to := tx.To()
if to == nil || *to != common.MasternodeVotingSMCBinary {
return false, nil return false, nil
} }
b := (tx.To().String() == common.MasternodeVotingSMC) var end int
data := tx.Data()
if !b { method := common.ToHex(data[0:4])
return b, nil if method == common.VoteMethod || method == common.ProposeMethod || method == common.ResignMethod {
end = len(data)
} else if method == common.UnvoteMethod {
end = len(data) - 32
} else {
return false, nil
} }
method := common.ToHex(tx.Data()[0:4]) addr := data[end-20 : end]
if b = (method == common.VoteMethod); b { m := common.BytesToAddress(addr)
addr := tx.Data()[len(tx.Data())-20:] return true, &m
m := common.BytesToAddress(addr)
return b, &m
}
if b = (method == common.UnvoteMethod); b {
addr := tx.Data()[len(tx.Data())-32-20 : len(tx.Data())-32]
m := common.BytesToAddress(addr)
return b, &m
}
if b = (method == common.ProposeMethod); b {
addr := tx.Data()[len(tx.Data())-20:]
m := common.BytesToAddress(addr)
return b, &m
}
if b = (method == common.ResignMethod); b {
addr := tx.Data()[len(tx.Data())-20:]
m := common.BytesToAddress(addr)
return b, &m
}
return b, nil
} }
func (tx *Transaction) IsXDCXApplyTransaction() bool { func (tx *Transaction) IsXDCXApplyTransaction() bool {
if tx.To() == nil { to := tx.To()
if to == nil {
return false return false
} }
@ -528,26 +474,22 @@ func (tx *Transaction) IsXDCXApplyTransaction() bool {
if common.IsTestnet { if common.IsTestnet {
addr = common.XDCXListingSMCTestNet addr = common.XDCXListingSMCTestNet
} }
if tx.To().String() != addr.String() { if *to != addr {
return false return false
} }
data := tx.Data()
method := common.ToHex(tx.Data()[0:4])
if method != common.XDCXApplyMethod {
return false
}
// 4 bytes for function name // 4 bytes for function name
// 32 bytes for 1 parameter // 32 bytes for 1 parameter
if len(tx.Data()) != (32 + 4) { if len(data) != (32 + 4) {
return false return false
} }
return true method := common.ToHex(data[0:4])
return method == common.XDCXApplyMethod
} }
func (tx *Transaction) IsXDCZApplyTransaction() bool { func (tx *Transaction) IsXDCZApplyTransaction() bool {
if tx.To() == nil { to := tx.To()
if to == nil {
return false return false
} }
@ -555,22 +497,17 @@ func (tx *Transaction) IsXDCZApplyTransaction() bool {
if common.IsTestnet { if common.IsTestnet {
addr = common.TRC21IssuerSMCTestNet addr = common.TRC21IssuerSMCTestNet
} }
if tx.To().String() != addr.String() { if *to != addr {
return false return false
} }
data := tx.Data()
method := common.ToHex(tx.Data()[0:4])
if method != common.XDCZApplyMethod {
return false
}
// 4 bytes for function name // 4 bytes for function name
// 32 bytes for 1 parameter // 32 bytes for 1 parameter
if len(tx.Data()) != (32 + 4) { if len(data) != (32 + 4) {
return false return false
} }
method := common.ToHex(data[0:4])
return true return method == common.XDCZApplyMethod
} }
func (tx *Transaction) String() string { func (tx *Transaction) String() string {

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)
@ -808,26 +808,27 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
var coalescedLogs []*types.Log var coalescedLogs []*types.Log
// first priority for special Txs // first priority for special Txs
for _, tx := range specialTxs { for _, tx := range specialTxs {
to := tx.To()
//HF number for black-list //HF number for black-list
if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet { if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet {
from := tx.From()
// check if sender is in black list // check if sender is in black list
if tx.From() != nil && common.Blacklist[*tx.From()] { if from != nil && common.Blacklist[*from] {
log.Debug("Skipping transaction with sender in black-list", "sender", tx.From().Hex()) log.Debug("Skipping transaction with sender in black-list", "sender", from.Hex())
continue continue
} }
// check if receiver is in black list // check if receiver is in black list
if tx.To() != nil && common.Blacklist[*tx.To()] { if to != nil && common.Blacklist[*to] {
log.Debug("Skipping transaction with receiver in black-list", "receiver", tx.To().Hex()) log.Debug("Skipping transaction with receiver in black-list", "receiver", to.Hex())
continue continue
} }
} }
data := tx.Data()
// validate minFee slot for XDCZ // validate minFee slot for XDCZ
if tx.IsXDCZApplyTransaction() { if tx.IsXDCZApplyTransaction() {
copyState, _ := bc.State() copyState, _ := bc.State()
if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil {
log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex())
txs.Pop() txs.Pop()
continue continue
} }
@ -835,8 +836,8 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
// validate balance slot, token decimal for XDCX // validate balance slot, token decimal for XDCX
if tx.IsXDCXApplyTransaction() { if tx.IsXDCXApplyTransaction() {
copyState, _ := bc.State() copyState, _ := bc.State()
if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil {
log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex())
txs.Pop() txs.Pop()
continue continue
} }
@ -853,38 +854,39 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
from, _ := types.Sender(env.signer, tx) from, _ := types.Sender(env.signer, tx)
// Check whether the tx is replay protected. If we're not in the EIP155 hf // Check whether the tx is replay protected. If we're not in the EIP155 hf
// phase, start ignoring the sender until we do. // phase, start ignoring the sender until we do.
hash := tx.Hash()
if tx.Protected() && !env.config.IsEIP155(env.header.Number) { if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
log.Trace("Ignoring reply protected special transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block) log.Trace("Ignoring reply protected special transaction", "hash", hash, "eip155", env.config.EIP155Block)
continue continue
} }
if tx.To().Hex() == common.BlockSigners { if *to == common.BlockSignersBinary {
if len(tx.Data()) < 68 { if len(data) < 68 {
log.Trace("Data special transaction invalid length", "hash", tx.Hash(), "data", len(tx.Data())) log.Trace("Data special transaction invalid length", "hash", hash, "data", len(data))
continue continue
} }
blkNumber := binary.BigEndian.Uint64(tx.Data()[8:40]) blkNumber := binary.BigEndian.Uint64(data[8:40])
if blkNumber >= env.header.Number.Uint64() || blkNumber <= env.header.Number.Uint64()-env.config.XDPoS.Epoch*2 { if blkNumber >= env.header.Number.Uint64() || blkNumber <= env.header.Number.Uint64()-env.config.XDPoS.Epoch*2 {
log.Trace("Data special transaction invalid number", "hash", tx.Hash(), "blkNumber", blkNumber, "miner", env.header.Number) log.Trace("Data special transaction invalid number", "hash", hash, "blkNumber", blkNumber, "miner", env.header.Number)
continue continue
} }
} }
// Start executing the transaction // Start executing the transaction
env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount) env.state.Prepare(hash, common.Hash{}, env.tcount)
nonce := env.state.GetNonce(from) nonce := env.state.GetNonce(from)
if nonce != tx.Nonce() && !tx.IsSkipNonceTransaction() { if nonce != tx.Nonce() && !tx.IsSkipNonceTransaction() {
log.Trace("Skipping account with special transaction invalid nonce", "sender", from, "nonce", nonce, "tx nonce ", tx.Nonce(), "to", tx.To()) log.Trace("Skipping account with special transaction invalid nonce", "sender", from, "nonce", nonce, "tx nonce ", tx.Nonce(), "to", to)
continue continue
} }
err, logs, tokenFeeUsed, gas := env.commitTransaction(balanceFee, tx, bc, coinbase, gp) err, logs, tokenFeeUsed, gas := env.commitTransaction(balanceFee, tx, bc, coinbase, gp)
switch err { switch err {
case core.ErrNonceTooLow: case core.ErrNonceTooLow:
// New head notification data race between the transaction pool and miner, shift // New head notification data race between the transaction pool and miner, shift
log.Trace("Skipping special transaction with low nonce", "sender", from, "nonce", tx.Nonce(), "to", tx.To()) log.Trace("Skipping special transaction with low nonce", "sender", from, "nonce", tx.Nonce(), "to", to)
case core.ErrNonceTooHigh: case core.ErrNonceTooHigh:
// Reorg notification data race between the transaction pool and miner, skip account = // Reorg notification data race between the transaction pool and miner, skip account =
log.Trace("Skipping account with special transaction hight nonce", "sender", from, "nonce", tx.Nonce(), "to", tx.To()) log.Trace("Skipping account with special transaction hight nonce", "sender", from, "nonce", tx.Nonce(), "to", to)
case nil: case nil:
// Everything ok, collect the logs and shift in the next transaction from the same account // Everything ok, collect the logs and shift in the next transaction from the same account
coalescedLogs = append(coalescedLogs, logs...) coalescedLogs = append(coalescedLogs, logs...)
@ -893,12 +895,12 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
default: default:
// Strange error, discard the transaction and get the next in line (note, the // Strange error, discard the transaction and get the next in line (note, the
// nonce-too-high clause will prevent us from executing in vain). // nonce-too-high clause will prevent us from executing in vain).
log.Debug("Add Special Transaction failed, account skipped", "hash", tx.Hash(), "sender", from, "nonce", tx.Nonce(), "to", tx.To(), "err", err) log.Debug("Add Special Transaction failed, account skipped", "hash", hash, "sender", from, "nonce", tx.Nonce(), "to", to, "err", err)
} }
if tokenFeeUsed { if tokenFeeUsed {
fee := common.GetGasFee(env.header.Number.Uint64(), gas) fee := common.GetGasFee(env.header.Number.Uint64(), gas)
balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) balanceFee[*to] = new(big.Int).Sub(balanceFee[*to], fee)
balanceUpdated[*tx.To()] = balanceFee[*tx.To()] balanceUpdated[*to] = balanceFee[*to]
totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee)
} }
} }
@ -920,26 +922,28 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
} }
//HF number for black-list //HF number for black-list
to := tx.To()
if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet { if (env.header.Number.Uint64() >= common.BlackListHFNumber) && !common.IsTestnet {
from := tx.From()
// check if sender is in black list // check if sender is in black list
if tx.From() != nil && common.Blacklist[*tx.From()] { if from != nil && common.Blacklist[*from] {
log.Debug("Skipping transaction with sender in black-list", "sender", tx.From().Hex()) log.Debug("Skipping transaction with sender in black-list", "sender", from.Hex())
txs.Pop() txs.Pop()
continue continue
} }
// check if receiver is in black list // check if receiver is in black list
if tx.To() != nil && common.Blacklist[*tx.To()] { if to != nil && common.Blacklist[*to] {
log.Debug("Skipping transaction with receiver in black-list", "receiver", tx.To().Hex()) log.Debug("Skipping transaction with receiver in black-list", "receiver", to.Hex())
txs.Shift() txs.Shift()
continue continue
} }
} }
data := tx.Data()
// validate minFee slot for XDCZ // validate minFee slot for XDCZ
if tx.IsXDCZApplyTransaction() { if tx.IsXDCZApplyTransaction() {
copyState, _ := bc.State() copyState, _ := bc.State()
if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { if err := core.ValidateXDCZApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil {
log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) log.Debug("XDCZApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex())
txs.Pop() txs.Pop()
continue continue
} }
@ -947,8 +951,8 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
// validate balance slot, token decimal for XDCX // validate balance slot, token decimal for XDCX
if tx.IsXDCXApplyTransaction() { if tx.IsXDCXApplyTransaction() {
copyState, _ := bc.State() copyState, _ := bc.State()
if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(tx.Data()[4:])); err != nil { if err := core.ValidateXDCXApplyTransaction(bc, nil, copyState, common.BytesToAddress(data[4:])); err != nil {
log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(tx.Data()[4:]).Hex()) log.Debug("XDCXApply: invalid token", "token", common.BytesToAddress(data[4:]).Hex())
txs.Pop() txs.Pop()
continue continue
} }
@ -959,15 +963,16 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
// //
// We use the eip155 signer regardless of the current hf. // We use the eip155 signer regardless of the current hf.
from, _ := types.Sender(env.signer, tx) from, _ := types.Sender(env.signer, tx)
hash := tx.Hash()
// Check whether the tx is replay protected. If we're not in the EIP155 hf // Check whether the tx is replay protected. If we're not in the EIP155 hf
// phase, start ignoring the sender until we do. // phase, start ignoring the sender until we do.
if tx.Protected() && !env.config.IsEIP155(env.header.Number) { if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block) log.Trace("Ignoring reply protected transaction", "hash", hash, "eip155", env.config.EIP155Block)
txs.Pop() txs.Pop()
continue continue
} }
// Start executing the transaction // Start executing the transaction
env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount) env.state.Prepare(hash, common.Hash{}, env.tcount)
nonce := env.state.GetNonce(from) nonce := env.state.GetNonce(from)
if nonce > tx.Nonce() { if nonce > tx.Nonce() {
// New head notification data race between the transaction pool and miner, shift // New head notification data race between the transaction pool and miner, shift
@ -1012,13 +1017,13 @@ func (env *Work) commitTransactions(mux *event.TypeMux, balanceFee map[common.Ad
default: default:
// Strange error, discard the transaction and get the next in line (note, the // Strange error, discard the transaction and get the next in line (note, the
// nonce-too-high clause will prevent us from executing in vain). // nonce-too-high clause will prevent us from executing in vain).
log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err) log.Debug("Transaction failed, account skipped", "hash", hash, "err", err)
txs.Shift() txs.Shift()
} }
if tokenFeeUsed { if tokenFeeUsed {
fee := common.GetGasFee(env.header.Number.Uint64(), gas) fee := common.GetGasFee(env.header.Number.Uint64(), gas)
balanceFee[*tx.To()] = new(big.Int).Sub(balanceFee[*tx.To()], fee) balanceFee[*to] = new(big.Int).Sub(balanceFee[*to], fee)
balanceUpdated[*tx.To()] = balanceFee[*tx.To()] balanceUpdated[*to] = balanceFee[*to]
totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee) totalFeeUsed = totalFeeUsed.Add(totalFeeUsed, fee)
} }
} }