Skip to content
This repository has been archived by the owner on May 25, 2020. It is now read-only.

Commit

Permalink
update CallContractWithState
Browse files Browse the repository at this point in the history
Remove debug logs
  • Loading branch information
thanhnguyennguyen committed Nov 11, 2019
1 parent 89c4154 commit 01e322b
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 48 deletions.
32 changes: 30 additions & 2 deletions accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 20,7 @@ import (
"context"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/consensus"
"math/big"
"sync"
"time"
Expand Down Expand Up @@ -202,8 203,35 @@ func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallM


// CallContractWithState executes a contract call at the given state.
func (b *SimulatedBackend) CallContractWithState(ctx context.Context, call ethereum.CallMsg, block *types.Block, db *state.StateDB) ([]byte, error) {
rval, _, _, err := b.callContract(ctx, call, block, db)
func (b *SimulatedBackend) CallContractWithState(ctx context.Context, call ethereum.CallMsg, chain consensus.ChainContext, statedb *state.StateDB) ([]byte, error) {
// Ensure message is initialized properly.
if call.GasPrice == nil {
call.GasPrice = big.NewInt(1)
}
if call.Gas == 0 {
call.Gas = 1000000
}
if call.Value == nil {
call.Value = new(big.Int)
}
// Execute the call.
msg := callmsg{call}
feeCapacity := state.GetTRC21FeeCapacityFromState(statedb)
if msg.To() != nil {
if value, ok := feeCapacity[*msg.To()]; ok {
msg.CallMsg.BalanceTokenFee = value
}
}
evmContext := core.NewEVMContext(msg, chain.CurrentHeader(), chain, nil)
// Create a new environment which holds all relevant information
// about the transaction and calling mechanisms.
vmenv := vm.NewEVM(evmContext, statedb, chain.Config(), vm.Config{})
gaspool := new(core.GasPool).AddGas(1000000)
owner := common.Address{}
rval, _, _ , err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb(owner)
if err != nil {
return nil, err
}
return rval, err
}

Expand Down
1 change: 0 additions & 1 deletion common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 22,6 @@ const (
MergeSignRange = 15
RangeReturnSigner = 150
MinimunMinerBlockPerEpoch = 1
TomoXSnapshotInterval = 100 // 100 blocks
)

var TIP2019Block = big.NewInt(1050000)
Expand Down
16 changes: 16 additions & 0 deletions consensus/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 104,19 @@ type PoW interface {
// Hashrate returns the current mining hashrate of a PoW consensus engine.
Hashrate() float64
}

// ChainContext supports retrieving headers and consensus parameters from the
// current blockchain to be used during transaction processing.
type ChainContext interface {
// Engine retrieves the chain's consensus engine.
Engine() Engine

// GetHeader returns the hash corresponding to their hash.
GetHeader(common.Hash, uint64) *types.Header

// CurrentHeader retrieves the current header from the local chain.
CurrentHeader() *types.Header

// Config retrieves the blockchain's chain configuration.
Config() *params.ChainConfig
}
2 changes: 1 addition & 1 deletion consensus/posv/posv.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 67,7 @@ type TomoXService interface {
GetTomoxState(block *types.Block) (*tomox_state.TomoXStateDB, error)
GetStateCache() tomox_state.Database
GetTriegc() *prque.Prque
ApplyOrder(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error)
ApplyOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error)
IsSDKNode() bool
SyncDataToSDKNode(txDataMatch tomox_state.TxDataMatch, txHash common.Hash, txMatchTime time.Time, statedb *state.StateDB) error
RollbackReorgTxMatch(txhash common.Hash)
Expand Down
2 changes: 1 addition & 1 deletion core/block_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 123,7 @@ func (v *BlockValidator) ValidateMatchingOrder(statedb *state.StateDB, tomoxStat
posvEngine, _ := v.bc.Engine().(*posv.Posv)
if posvEngine != nil {
if tomoXService := posvEngine.GetTomoXService(); tomoXService != nil {
if _, _, err := tomoXService.ApplyOrder(coinbase, v.bc.CurrentBlock(), statedb, tomoxStatedb, GetOrderBookHash(order.BaseToken,order.QuoteToken), order); err != nil {
if _, _, err := tomoXService.ApplyOrder(coinbase, v.bc, statedb, tomoxStatedb, GetOrderBookHash(order.BaseToken,order.QuoteToken), order); err != nil {
return err
}
}
Expand Down
13 changes: 2 additions & 11 deletions core/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 25,9 @@ import (
"github.com/ethereum/go-ethereum/core/vm"
)

// ChainContext supports retrieving headers and consensus parameters from the
// current blockchain to be used during transaction processing.
type ChainContext interface {
// Engine retrieves the chain's consensus engine.
Engine() consensus.Engine

// GetHeader returns the hash corresponding to their hash.
GetHeader(common.Hash, uint64) *types.Header
}

// NewEVMContext creates a new context for use in the EVM.
func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author *common.Address) vm.Context {
func NewEVMContext(msg Message, header *types.Header, chain consensus.ChainContext, author *common.Address) vm.Context {
// If we don't have an explicit author (i.e. not mining), extract from the header
var beneficiary common.Address
if author == nil {
Expand All @@ -59,7 50,7 @@ func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author
}

// GetHashFn returns a GetHashFunc which retrieves header hashes by number
func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
func GetHashFn(ref *types.Header, chain consensus.ChainContext) func(n uint64) common.Hash {
var cache map[uint64]common.Hash

return func(n uint64) common.Hash {
Expand Down
3 changes: 2 additions & 1 deletion light/odr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 20,7 @@ import (
"bytes"
"context"
"errors"
"github.com/ethereum/go-ethereum/consensus"
"math/big"
"testing"
"time"
Expand Down Expand Up @@ -162,7 163,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain
var (
st *state.StateDB
header *types.Header
chain core.ChainContext
chain consensus.ChainContext
)
if bc == nil {
chain = lc
Expand Down
34 changes: 17 additions & 17 deletions tomox/order_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 3,7 @@ package tomox
import (
"encoding/json"
"errors"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/consensus"
"math/big"
"strconv"
"time"
Expand All @@ -18,17 18,17 @@ import (
var emptyAddress = common.StringToAddress("")
var errQuantityTradeTooSmall = errors.New("Quantity trade too small")

func (tomox *TomoX) CommitOrder(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
func (tomox *TomoX) CommitOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
snap := tomoXstatedb.Snapshot()
trades, rejects, err := tomox.ApplyOrder(coinbase, currentBlock, statedb, tomoXstatedb, orderBook, order)
trades, rejects, err := tomox.ApplyOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
tomoXstatedb.RevertToSnapshot(snap)
return nil, nil, err
}
return trades, rejects, err
}

func (tomox *TomoX) ApplyOrder(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
func (tomox *TomoX) ApplyOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
rejects []*tomox_state.OrderItem
trades []map[string]string
Expand Down Expand Up @@ -68,13 68,13 @@ func (tomox *TomoX) ApplyOrder(coinbase common.Address, currentBlock *types.Bloc
// if we do not use auto-increment orderid, we must set price slot to avoid conflict
if orderType == Market {
log.Debug("Process maket order", "side", order.Side, "quantity", order.Quantity, "price", order.Price)
trades, rejects, err = tomox.processMarketOrder(coinbase, currentBlock, statedb, tomoXstatedb, orderBook, order)
trades, rejects, err = tomox.processMarketOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
return nil, nil, err
}
} else {
log.Debug("Process limit order", "side", order.Side, "quantity", order.Quantity, "price", order.Price)
trades, rejects, err = tomox.processLimitOrder(coinbase, currentBlock, statedb, tomoXstatedb, orderBook, order)
trades, rejects, err = tomox.processLimitOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
return nil, nil, err
}
Expand All @@ -86,7 86,7 @@ func (tomox *TomoX) ApplyOrder(coinbase common.Address, currentBlock *types.Bloc
}

// processMarketOrder : process the market order
func (tomox *TomoX) processMarketOrder(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
func (tomox *TomoX) processMarketOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
trades []map[string]string
newTrades []map[string]string
Expand All @@ -102,7 102,7 @@ func (tomox *TomoX) processMarketOrder(coinbase common.Address, currentBlock *ty
bestPrice, volume := tomoXstatedb.GetBestAskPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && bestPrice.Cmp(zero) > 0 {
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, currentBlock, statedb, tomoXstatedb, Ask, orderBook, bestPrice, quantityToTrade, order)
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, Ask, orderBook, bestPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
Expand All @@ -115,7 115,7 @@ func (tomox *TomoX) processMarketOrder(coinbase common.Address, currentBlock *ty
bestPrice, volume := tomoXstatedb.GetBestBidPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && bestPrice.Cmp(zero) > 0 {
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, currentBlock, statedb, tomoXstatedb, Bid, orderBook, bestPrice, quantityToTrade, order)
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, Bid, orderBook, bestPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
Expand All @@ -130,7 130,7 @@ func (tomox *TomoX) processMarketOrder(coinbase common.Address, currentBlock *ty

// processLimitOrder : process the limit order, can change the quote
// If not care for performance, we should make a copy of quote to prevent further reference problem
func (tomox *TomoX) processLimitOrder(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
func (tomox *TomoX) processLimitOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
trades []map[string]string
newTrades []map[string]string
Expand All @@ -150,7 150,7 @@ func (tomox *TomoX) processLimitOrder(coinbase common.Address, currentBlock *typ
log.Debug("processLimitOrder ", "side", side, "minPrice", minPrice, "orderPrice", price, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && price.Cmp(minPrice) >= 0 && minPrice.Cmp(zero) > 0 {
log.Debug("Min price in asks tree", "price", minPrice.String())
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, currentBlock, statedb, tomoXstatedb, Ask, orderBook, minPrice, quantityToTrade, order)
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, Ask, orderBook, minPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
Expand All @@ -165,7 165,7 @@ func (tomox *TomoX) processLimitOrder(coinbase common.Address, currentBlock *typ
log.Debug("processLimitOrder ", "side", side, "maxPrice", maxPrice, "orderPrice", price, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && price.Cmp(maxPrice) <= 0 && maxPrice.Cmp(zero) > 0 {
log.Debug("Max price in bids tree", "price", maxPrice.String())
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, currentBlock, statedb, tomoXstatedb, Bid, orderBook, maxPrice, quantityToTrade, order)
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, Bid, orderBook, maxPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
Expand All @@ -189,7 189,7 @@ func (tomox *TomoX) processLimitOrder(coinbase common.Address, currentBlock *typ
}

// processOrderList : process the order list
func (tomox *TomoX) processOrderList(coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, side string, orderBook common.Hash, price *big.Int, quantityStillToTrade *big.Int, order *tomox_state.OrderItem) (*big.Int, []map[string]string, []*tomox_state.OrderItem, error) {
func (tomox *TomoX) processOrderList(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, side string, orderBook common.Hash, price *big.Int, quantityStillToTrade *big.Int, order *tomox_state.OrderItem) (*big.Int, []map[string]string, []*tomox_state.OrderItem, error) {
quantityToTrade := CloneBigInt(quantityStillToTrade)
log.Debug("Process matching between order and orderlist", "quantityToTrade", quantityToTrade)
var (
Expand Down Expand Up @@ -220,7 220,7 @@ func (tomox *TomoX) processOrderList(coinbase common.Address, currentBlock *type
if oldestOrder.QuoteToken.String() != common.TomoNativeAddress {
quotePrice = tomoXstatedb.GetPrice(GetOrderBookHash(oldestOrder.QuoteToken, common.HexToAddress(common.TomoNativeAddress)))
}
tradedQuantity, rejectMaker, err := tomox.getTradeQuantity(quotePrice, coinbase, currentBlock, statedb, order, &oldestOrder, maxTradedQuantity)
tradedQuantity, rejectMaker, err := tomox.getTradeQuantity(quotePrice, coinbase, chain, statedb, order, &oldestOrder, maxTradedQuantity)
if err != nil && err == errQuantityTradeTooSmall {
if tradedQuantity.Cmp(maxTradedQuantity) == 0 {
if quantityToTrade.Cmp(amount) == 0 { // reject Taker & maker
Expand Down Expand Up @@ -303,12 303,12 @@ func (tomox *TomoX) processOrderList(coinbase common.Address, currentBlock *type
return quantityToTrade, trades, rejects, nil
}

func (tomox *TomoX) getTradeQuantity(quotePrice *big.Int, coinbase common.Address, currentBlock *types.Block, statedb *state.StateDB, takerOrder *tomox_state.OrderItem, makerOrder *tomox_state.OrderItem, quantityToTrade *big.Int) (*big.Int, bool, error) {
baseTokenDecimal, err := tomox.GetTokenDecimal(currentBlock, statedb, makerOrder.BaseToken)
func (tomox *TomoX) getTradeQuantity(quotePrice *big.Int, coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, takerOrder *tomox_state.OrderItem, makerOrder *tomox_state.OrderItem, quantityToTrade *big.Int) (*big.Int, bool, error) {
baseTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, makerOrder.BaseToken)
if err != nil || baseTokenDecimal.Sign() == 0 {
return Zero(), false, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.BaseToken.String(), err)
}
quoteTokenDecimal, err := tomox.GetTokenDecimal(currentBlock, statedb, makerOrder.QuoteToken)
quoteTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, makerOrder.QuoteToken)
if err != nil || quoteTokenDecimal.Sign() == 0 {
return Zero(), false, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.QuoteToken.String(), err)
}
Expand Down
24 changes: 12 additions & 12 deletions tomox/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 2,16 @@ package tomox

import (
"context"
"math/big"
"strings"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
"strings"
)
import "github.com/ethereum/go-ethereum/accounts/abi"

const tokenAbi = `
[
Expand Down Expand Up @@ -433,16 434,15 @@ func GetTokenAbi() (*abi.ABI, error) {
return &contractABI, nil
}


// RunContract run smart contract
func RunContract(block *types.Block, statedb *state.StateDB, contractAddr common.Address, abi *abi.ABI, method string, args ...interface{}) (interface{}, error) {
input, err := abi.Pack(method, args)
func RunContract(chain consensus.ChainContext, statedb *state.StateDB, coinbase common.Address, contractAddr common.Address, abi *abi.ABI, method string, args ...interface{}) (interface{}, error) {
input, err := abi.Pack(method)
if err != nil {
return nil, err
}
backend := (*backends.SimulatedBackend)(nil)
msg := ethereum.CallMsg{To: &contractAddr, Data: input}
result, err := backend.CallContractWithState(context.Background(), msg, block, statedb)
msg := ethereum.CallMsg{To: &contractAddr, Data: input, From: coinbase}
result, err := backend.CallContractWithState(context.Background(), msg, chain, statedb)
if err != nil {
return nil, err
}
Expand All @@ -454,7 454,7 @@ func RunContract(block *types.Block, statedb *state.StateDB, contractAddr common
return unpackResult, nil
}

func (tomox *TomoX) GetTokenDecimal(block *types.Block, statedb *state.StateDB, tokenAddr common.Address) (*big.Int, error) {
func (tomox *TomoX) GetTokenDecimal(chain consensus.ChainContext, statedb *state.StateDB, coinbase common.Address, tokenAddr common.Address) (*big.Int, error) {
if tokenDecimal, ok := tomox.tokenDecimalCache.Get(tokenAddr); ok {
return tokenDecimal.(*big.Int), nil
}
Expand All @@ -466,7 466,7 @@ func (tomox *TomoX) GetTokenDecimal(block *types.Block, statedb *state.StateDB,
if err != nil {
return nil, err
}
result, err := RunContract(block, statedb, tokenAddr, contractABI, "decimals")
result, err := RunContract(chain, statedb, coinbase, tokenAddr, contractABI, "decimals")
if err != nil {
return nil, err
}
Expand All @@ -475,4 475,4 @@ func (tomox *TomoX) GetTokenDecimal(block *types.Block, statedb *state.StateDB,
tokenDecimal := new(big.Int).SetUint64(0).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil)
tomox.tokenDecimalCache.Add(tokenAddr, tokenDecimal)
return tokenDecimal, nil
}
}
Loading

0 comments on commit 01e322b

Please sign in to comment.