arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/test/ethclient.go
test/ethclient.goRaw
   1package test
   2
   3import (
   4	"context"
   5	"encoding/binary"
   6	"encoding/json"
   7	"fmt"
   8	"math/big"
   9	"reflect"
  10	"sync"
  11	"time"
  12
  13	"github.com/ethereum/go-ethereum"
  14	ethCommon "github.com/ethereum/go-ethereum/common"
  15	"github.com/ethereum/go-ethereum/core/types"
  16	"github.com/hermeznetwork/hermez-node/common"
  17	"github.com/hermeznetwork/hermez-node/eth"
  18	"github.com/hermeznetwork/hermez-node/log"
  19	"github.com/iden3/go-iden3-crypto/babyjub"
  20	"github.com/mitchellh/copystructure"
  21)
  22
  23func init() {
  24	copystructure.Copiers[reflect.TypeOf(big.Int{})] =
  25		func(raw interface{}) (interface{}, error) {
  26			in := raw.(big.Int)
  27			out := new(big.Int).Set(&in)
  28			return *out, nil
  29		}
  30}
  31
  32// WDelayerBlock stores all the data related to the WDelayer SC from an ethereum block
  33type WDelayerBlock struct {
  34	// State     eth.WDelayerState // TODO
  35	Vars      common.WDelayerVariables
  36	Events    eth.WDelayerEvents
  37	Txs       map[ethCommon.Hash]*types.Transaction
  38	Constants *common.WDelayerConstants
  39	Eth       *EthereumBlock
  40}
  41
  42func (w *WDelayerBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  43	txHash := tx.Hash()
  44	w.Txs[txHash] = tx
  45	return tx
  46}
  47
  48func (w *WDelayerBlock) deposit(txHash ethCommon.Hash, owner, token ethCommon.Address, amount *big.Int) {
  49	w.Events.Deposit = append(w.Events.Deposit, eth.WDelayerEventDeposit{
  50		Owner:            owner,
  51		Token:            token,
  52		Amount:           amount,
  53		DepositTimestamp: uint64(w.Eth.Time),
  54		TxHash:           txHash,
  55	})
  56}
  57
  58// RollupBlock stores all the data related to the Rollup SC from an ethereum block
  59type RollupBlock struct {
  60	State     eth.RollupState
  61	Vars      common.RollupVariables
  62	Events    eth.RollupEvents
  63	Txs       map[ethCommon.Hash]*types.Transaction
  64	Constants *common.RollupConstants
  65	Eth       *EthereumBlock
  66}
  67
  68func (r *RollupBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  69	txHash := tx.Hash()
  70	r.Txs[txHash] = tx
  71	return tx
  72}
  73
  74var (
  75	errBidClosed   = fmt.Errorf("Bid has already been closed")
  76	errBidNotOpen  = fmt.Errorf("Bid has not been opened yet")
  77	errBidBelowMin = fmt.Errorf("Bid below minimum")
  78	errCoordNotReg = fmt.Errorf("Coordinator not registered")
  79)
  80
  81// AuctionBlock stores all the data related to the Auction SC from an ethereum block
  82type AuctionBlock struct {
  83	State     eth.AuctionState
  84	Vars      common.AuctionVariables
  85	Events    eth.AuctionEvents
  86	Txs       map[ethCommon.Hash]*types.Transaction
  87	Constants *common.AuctionConstants
  88	Eth       *EthereumBlock
  89}
  90
  91func (a *AuctionBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  92	txHash := tx.Hash()
  93	a.Txs[txHash] = tx
  94	return tx
  95}
  96
  97func (a *AuctionBlock) getSlotNumber(blockNumber int64) int64 {
  98	if a.Eth.BlockNum >= a.Constants.GenesisBlockNum {
  99		return (blockNumber - a.Constants.GenesisBlockNum) / int64(a.Constants.BlocksPerSlot)
 100	}
 101	return 0
 102}
 103
 104func (a *AuctionBlock) getCurrentSlotNumber() int64 {
 105	return a.getSlotNumber(a.Eth.BlockNum)
 106}
 107
 108func (a *AuctionBlock) getSlotSet(slot int64) int64 {
 109	return slot % int64(len(a.Vars.DefaultSlotSetBid))
 110}
 111
 112func (a *AuctionBlock) getMinBidBySlot(slot int64) (*big.Int, error) {
 113	if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
 114		return nil, errBidClosed
 115	}
 116
 117	slotSet := a.getSlotSet(slot)
 118	// fmt.Println("slot:", slot, "slotSet:", slotSet)
 119	var prevBid *big.Int
 120	slotState, ok := a.State.Slots[slot]
 121	if !ok {
 122		slotState = eth.NewSlotState()
 123		a.State.Slots[slot] = slotState
 124	}
 125	// If the bidAmount for a slot is 0 it means that it has not yet been bid, so the midBid will be the minimum
 126	// bid for the slot time plus the outbidding set, otherwise it will be the bidAmount plus the outbidding
 127	if slotState.BidAmount.Cmp(big.NewInt(0)) == 0 {
 128		prevBid = a.Vars.DefaultSlotSetBid[slotSet]
 129	} else {
 130		prevBid = slotState.BidAmount
 131	}
 132	outBid := new(big.Int).Set(prevBid)
 133	// fmt.Println("outBid:", outBid)
 134	outBid.Mul(outBid, big.NewInt(int64(a.Vars.Outbidding)))
 135	outBid.Div(outBid, big.NewInt(10000)) //nolint:gomnd
 136	outBid.Add(prevBid, outBid)
 137	// fmt.Println("minBid:", outBid)
 138	return outBid, nil
 139}
 140
 141func (a *AuctionBlock) forge(forger ethCommon.Address) error {
 142	if ok, err := a.canForge(forger, a.Eth.BlockNum); err != nil {
 143		return err
 144	} else if !ok {
 145		return fmt.Errorf("Can't forge")
 146	}
 147
 148	slotToForge := a.getSlotNumber(a.Eth.BlockNum)
 149	slotState, ok := a.State.Slots[slotToForge]
 150	if !ok {
 151		slotState = eth.NewSlotState()
 152		a.State.Slots[slotToForge] = slotState
 153	}
 154	slotState.Fulfilled = true
 155
 156	a.Events.NewForge = append(a.Events.NewForge, eth.AuctionEventNewForge{
 157		Forger:      forger,
 158		SlotToForge: slotToForge,
 159	})
 160	return nil
 161}
 162
 163func (a *AuctionBlock) canForge(forger ethCommon.Address, blockNum int64) (bool, error) {
 164	if blockNum < a.Constants.GenesisBlockNum {
 165		return false, fmt.Errorf("Auction has not started yet")
 166	}
 167
 168	slotToForge := a.getSlotNumber(blockNum)
 169	// Get the relativeBlock to check if the slotDeadline has been exceeded
 170	relativeBlock := blockNum - (a.Constants.GenesisBlockNum + (slotToForge * int64(a.Constants.BlocksPerSlot)))
 171
 172	// If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set,
 173	// otherwise the one that has been saved will be used
 174	var minBid *big.Int
 175	slotState, ok := a.State.Slots[slotToForge]
 176	if !ok {
 177		slotState = eth.NewSlotState()
 178		a.State.Slots[slotToForge] = slotState
 179	}
 180	if slotState.ClosedMinBid.Cmp(big.NewInt(0)) == 0 {
 181		minBid = a.Vars.DefaultSlotSetBid[a.getSlotSet(slotToForge)]
 182	} else {
 183		minBid = slotState.ClosedMinBid
 184	}
 185
 186	if !slotState.Fulfilled && (relativeBlock >= int64(a.Vars.SlotDeadline)) {
 187		// if the relative block has exceeded the slotDeadline and no batch has been forged, anyone can forge
 188		return true, nil
 189		// TODO, find the forger set by the Bidder
 190	} else if coord, ok := a.State.Coordinators[slotState.Bidder]; ok &&
 191		coord.Forger == forger && slotState.BidAmount.Cmp(minBid) >= 0 {
 192		// if forger bidAmount has exceeded the minBid it can forge
 193		return true, nil
 194	} else if a.Vars.BootCoordinator == forger && slotState.BidAmount.Cmp(minBid) == -1 {
 195		// if it's the boot coordinator and it has not been bid or the bid is below the minimum it can forge
 196		return true, nil
 197	} else {
 198		return false, nil
 199	}
 200}
 201
 202// EthereumBlock stores all the generic data related to the an ethereum block
 203type EthereumBlock struct {
 204	BlockNum   int64
 205	Time       int64
 206	Hash       ethCommon.Hash
 207	ParentHash ethCommon.Hash
 208	Tokens     map[ethCommon.Address]eth.ERC20Consts
 209	// state      ethState
 210}
 211
 212// Block represents a ethereum block
 213type Block struct {
 214	Rollup   *RollupBlock
 215	Auction  *AuctionBlock
 216	WDelayer *WDelayerBlock
 217	Eth      *EthereumBlock
 218}
 219
 220func (b *Block) copy() *Block {
 221	bCopyRaw, err := copystructure.Copy(b)
 222	if err != nil {
 223		panic(err)
 224	}
 225	bCopy := bCopyRaw.(*Block)
 226	return bCopy
 227}
 228
 229// Next prepares the successive block.
 230func (b *Block) Next() *Block {
 231	blockNext := b.copy()
 232	blockNext.Rollup.Events = eth.NewRollupEvents()
 233	blockNext.Auction.Events = eth.NewAuctionEvents()
 234
 235	blockNext.Eth.BlockNum = b.Eth.BlockNum + 1
 236	blockNext.Eth.ParentHash = b.Eth.Hash
 237
 238	blockNext.Rollup.Constants = b.Rollup.Constants
 239	blockNext.Auction.Constants = b.Auction.Constants
 240	blockNext.WDelayer.Constants = b.WDelayer.Constants
 241	blockNext.Rollup.Eth = blockNext.Eth
 242	blockNext.Auction.Eth = blockNext.Eth
 243	blockNext.WDelayer.Eth = blockNext.Eth
 244
 245	return blockNext
 246}
 247
 248// ClientSetup is used to initialize the constants of the Smart Contracts and
 249// other details of the test Client
 250type ClientSetup struct {
 251	RollupConstants   *common.RollupConstants
 252	RollupVariables   *common.RollupVariables
 253	AuctionConstants  *common.AuctionConstants
 254	AuctionVariables  *common.AuctionVariables
 255	WDelayerConstants *common.WDelayerConstants
 256	WDelayerVariables *common.WDelayerVariables
 257	VerifyProof       bool
 258}
 259
 260// NewClientSetupExample returns a ClientSetup example with hardcoded realistic
 261// values.  With this setup, the rollup genesis will be block 1, and block 0
 262// and 1 will be premined.
 263//nolint:gomnd
 264func NewClientSetupExample() *ClientSetup {
 265	// rfield, ok := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
 266	// if !ok {
 267	// 	panic("bad rfield")
 268	// }
 269	initialMinimalBidding, ok := new(big.Int).SetString("10000000000000000000", 10) // 10 * (1e18)
 270	if !ok {
 271		panic("bad initialMinimalBidding")
 272	}
 273	tokenHEZ := ethCommon.HexToAddress("0x51D243D62852Bba334DD5cc33f242BAc8c698074")
 274	governanceAddress := ethCommon.HexToAddress("0x688EfD95BA4391f93717CF02A9aED9DBD2855cDd")
 275	rollupConstants := &common.RollupConstants{
 276		Verifiers: []common.RollupVerifierStruct{
 277			{
 278				MaxTx:   2048,
 279				NLevels: 32,
 280			},
 281		},
 282		TokenHEZ:                   tokenHEZ,
 283		HermezGovernanceDAOAddress: governanceAddress,
 284		SafetyAddress:              ethCommon.HexToAddress("0x84d8B79E84fe87B14ad61A554e740f6736bF4c20"),
 285		HermezAuctionContract:      ethCommon.HexToAddress("0x8E442975805fb1908f43050c9C1A522cB0e28D7b"),
 286		WithdrawDelayerContract:    ethCommon.HexToAddress("0x5CB7979cBdbf65719BEE92e4D15b7b7Ed3D79114"),
 287	}
 288	rollupVariables := &common.RollupVariables{
 289		FeeAddToken:           big.NewInt(11),
 290		ForgeL1L2BatchTimeout: 9,
 291		WithdrawalDelay:       80,
 292	}
 293	auctionConstants := &common.AuctionConstants{
 294		BlocksPerSlot:         40,
 295		InitialMinimalBidding: initialMinimalBidding,
 296		GenesisBlockNum:       1,
 297		GovernanceAddress:     governanceAddress,
 298		TokenHEZ:              tokenHEZ,
 299		HermezRollup:          ethCommon.HexToAddress("0x474B6e29852257491cf283EfB1A9C61eBFe48369"),
 300	}
 301	auctionVariables := &common.AuctionVariables{
 302		DonationAddress: ethCommon.HexToAddress("0x61Ed87CF0A1496b49A420DA6D84B58196b98f2e7"),
 303		BootCoordinator: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
 304		DefaultSlotSetBid: [6]*big.Int{
 305			big.NewInt(1000), big.NewInt(1100), big.NewInt(1200),
 306			big.NewInt(1300), big.NewInt(1400), big.NewInt(1500)},
 307		ClosedAuctionSlots: 2,
 308		OpenAuctionSlots:   4320,
 309		AllocationRatio:    [3]uint16{4000, 4000, 2000},
 310		Outbidding:         1000,
 311		SlotDeadline:       20,
 312	}
 313	wDelayerConstants := &common.WDelayerConstants{
 314		MaxWithdrawalDelay:   60 * 60 * 24 * 7 * 2,  // 2 weeks
 315		MaxEmergencyModeTime: 60 * 60 * 24 * 7 * 26, // 26 weeks
 316		HermezRollup:         auctionConstants.HermezRollup,
 317	}
 318	wDelayerVariables := &common.WDelayerVariables{
 319		HermezGovernanceDAOAddress: ethCommon.HexToAddress("0xcfD0d163AE6432a72682323E2C3A5a69e6B37D12"),
 320		WhiteHackGroupAddress:      ethCommon.HexToAddress("0x2730700932a4FDB97B9268A3Ca29f97Ea5fd7EA0"),
 321		HermezKeeperAddress:        ethCommon.HexToAddress("0x92aAD86176dC0f0046FE85Ed5dA008a828bE3868"),
 322		WithdrawalDelay:            60,
 323		EmergencyModeStartingTime:  0,
 324		EmergencyMode:              false,
 325	}
 326	return &ClientSetup{
 327		RollupConstants:   rollupConstants,
 328		RollupVariables:   rollupVariables,
 329		AuctionConstants:  auctionConstants,
 330		AuctionVariables:  auctionVariables,
 331		WDelayerConstants: wDelayerConstants,
 332		WDelayerVariables: wDelayerVariables,
 333	}
 334}
 335
 336// Timer is an interface to simulate a source of time, useful to advance time
 337// virtually.
 338type Timer interface {
 339	Time() int64
 340}
 341
 342// type forgeBatchArgs struct {
 343// 	ethTx     *types.Transaction
 344// 	blockNum  int64
 345// 	blockHash ethCommon.Hash
 346// }
 347
 348type batch struct {
 349	ForgeBatchArgs eth.RollupForgeBatchArgs
 350	Sender         ethCommon.Address
 351}
 352
 353// Client implements the eth.ClientInterface interface, allowing to manipulate the
 354// values for testing, working with deterministic results.
 355type Client struct {
 356	rw                *sync.RWMutex
 357	log               bool
 358	addr              *ethCommon.Address
 359	rollupConstants   *common.RollupConstants
 360	auctionConstants  *common.AuctionConstants
 361	wDelayerConstants *common.WDelayerConstants
 362	blocks            map[int64]*Block
 363	// state            state
 364	blockNum    int64 // last mined block num
 365	maxBlockNum int64 // highest block num calculated
 366	timer       Timer
 367	hasher      hasher
 368
 369	forgeBatchArgsPending map[ethCommon.Hash]*batch
 370	forgeBatchArgs        map[ethCommon.Hash]*batch
 371}
 372
 373// NewClient returns a new test Client that implements the eth.IClient
 374// interface, at the given initialBlockNumber.
 375func NewClient(l bool, timer Timer, addr *ethCommon.Address, setup *ClientSetup) *Client {
 376	blocks := make(map[int64]*Block)
 377	blockNum := int64(0)
 378
 379	hasher := hasher{}
 380	// Add ethereum genesis block
 381	mapL1TxQueue := make(map[int64]*eth.QueueStruct)
 382	mapL1TxQueue[0] = eth.NewQueueStruct()
 383	mapL1TxQueue[1] = eth.NewQueueStruct()
 384	blockCurrent := &Block{
 385		Rollup: &RollupBlock{
 386			State: eth.RollupState{
 387				StateRoot:        big.NewInt(0),
 388				ExitRoots:        make([]*big.Int, 1),
 389				ExitNullifierMap: make(map[int64]map[int64]bool),
 390				// TokenID = 0 is ETH.  Set first entry in TokenList with 0x0 address for ETH.
 391				TokenList:              []ethCommon.Address{{}},
 392				TokenMap:               make(map[ethCommon.Address]bool),
 393				MapL1TxQueue:           mapL1TxQueue,
 394				LastL1L2Batch:          0,
 395				CurrentToForgeL1TxsNum: 0,
 396				LastToForgeL1TxsNum:    1,
 397				CurrentIdx:             0,
 398			},
 399			Vars:      *setup.RollupVariables,
 400			Txs:       make(map[ethCommon.Hash]*types.Transaction),
 401			Events:    eth.NewRollupEvents(),
 402			Constants: setup.RollupConstants,
 403		},
 404		Auction: &AuctionBlock{
 405			State: eth.AuctionState{
 406				Slots:           make(map[int64]*eth.SlotState),
 407				PendingBalances: make(map[ethCommon.Address]*big.Int),
 408				Coordinators:    make(map[ethCommon.Address]*eth.Coordinator),
 409			},
 410			Vars:      *setup.AuctionVariables,
 411			Txs:       make(map[ethCommon.Hash]*types.Transaction),
 412			Events:    eth.NewAuctionEvents(),
 413			Constants: setup.AuctionConstants,
 414		},
 415		WDelayer: &WDelayerBlock{
 416			// State: TODO
 417			Vars:      *setup.WDelayerVariables,
 418			Txs:       make(map[ethCommon.Hash]*types.Transaction),
 419			Events:    eth.NewWDelayerEvents(),
 420			Constants: setup.WDelayerConstants,
 421		},
 422		Eth: &EthereumBlock{
 423			BlockNum:   blockNum,
 424			Time:       timer.Time(),
 425			Hash:       hasher.Next(),
 426			ParentHash: ethCommon.Hash{},
 427			Tokens:     make(map[ethCommon.Address]eth.ERC20Consts),
 428		},
 429	}
 430	blockCurrent.Rollup.Eth = blockCurrent.Eth
 431	blockCurrent.Auction.Eth = blockCurrent.Eth
 432	blocks[blockNum] = blockCurrent
 433	blockNext := blockCurrent.Next()
 434	blocks[blockNum+1] = blockNext
 435
 436	c := Client{
 437		rw:                    &sync.RWMutex{},
 438		log:                   l,
 439		addr:                  addr,
 440		rollupConstants:       setup.RollupConstants,
 441		auctionConstants:      setup.AuctionConstants,
 442		wDelayerConstants:     setup.WDelayerConstants,
 443		blocks:                blocks,
 444		timer:                 timer,
 445		hasher:                hasher,
 446		forgeBatchArgsPending: make(map[ethCommon.Hash]*batch),
 447		forgeBatchArgs:        make(map[ethCommon.Hash]*batch),
 448		blockNum:              blockNum,
 449		maxBlockNum:           blockNum,
 450	}
 451
 452	for i := int64(1); i < setup.AuctionConstants.GenesisBlockNum+1; i++ {
 453		c.CtlMineBlock()
 454	}
 455
 456	return &c
 457}
 458
 459//
 460// Mock Control
 461//
 462
 463func (c *Client) setNextBlock(block *Block) {
 464	c.blocks[c.blockNum+1] = block
 465}
 466
 467func (c *Client) revertIfErr(err error, block *Block) {
 468	if err != nil {
 469		log.Infow("TestClient revert", "block", block.Eth.BlockNum, "err", err)
 470		c.setNextBlock(block)
 471	}
 472}
 473
 474// Debugf calls log.Debugf if c.log is true
 475func (c *Client) Debugf(template string, args ...interface{}) {
 476	if c.log {
 477		log.Debugf(template, args...)
 478	}
 479}
 480
 481// Debugw calls log.Debugw if c.log is true
 482func (c *Client) Debugw(template string, kv ...interface{}) {
 483	if c.log {
 484		log.Debugw(template, kv...)
 485	}
 486}
 487
 488type hasher struct {
 489	counter uint64
 490}
 491
 492// Next returns the next hash
 493func (h *hasher) Next() ethCommon.Hash {
 494	var hash ethCommon.Hash
 495	binary.LittleEndian.PutUint64(hash[:], h.counter)
 496	h.counter++
 497	return hash
 498}
 499
 500func (c *Client) nextBlock() *Block {
 501	return c.blocks[c.blockNum+1]
 502}
 503
 504func (c *Client) currentBlock() *Block {
 505	return c.blocks[c.blockNum]
 506}
 507
 508// CtlSetAddr sets the address of the client
 509func (c *Client) CtlSetAddr(addr ethCommon.Address) {
 510	c.addr = &addr
 511}
 512
 513// CtlMineBlock moves one block forward
 514func (c *Client) CtlMineBlock() {
 515	c.rw.Lock()
 516	defer c.rw.Unlock()
 517
 518	blockCurrent := c.nextBlock()
 519	c.blockNum++
 520	c.maxBlockNum = c.blockNum
 521	blockCurrent.Eth.Time = c.timer.Time()
 522	blockCurrent.Eth.Hash = c.hasher.Next()
 523	for ethTxHash, forgeBatchArgs := range c.forgeBatchArgsPending {
 524		c.forgeBatchArgs[ethTxHash] = forgeBatchArgs
 525	}
 526	c.forgeBatchArgsPending = make(map[ethCommon.Hash]*batch)
 527
 528	blockNext := blockCurrent.Next()
 529	c.blocks[c.blockNum+1] = blockNext
 530	c.Debugw("TestClient mined block", "blockNum", c.blockNum)
 531}
 532
 533// CtlRollback discards the last mined block.  Use this to replace a mined
 534// block to simulate reorgs.
 535func (c *Client) CtlRollback() {
 536	c.rw.Lock()
 537	defer c.rw.Unlock()
 538
 539	if c.blockNum == 0 {
 540		panic("Can't rollback at blockNum = 0")
 541	}
 542	delete(c.blocks, c.blockNum+1) // delete next block
 543	delete(c.blocks, c.blockNum)   // delete current block
 544	c.blockNum--
 545	blockCurrent := c.blocks[c.blockNum]
 546	blockNext := blockCurrent.Next()
 547	c.blocks[c.blockNum+1] = blockNext
 548}
 549
 550//
 551// Ethereum
 552//
 553
 554// CtlCurrentBlock returns the current blockNum without checks
 555func (c *Client) CtlCurrentBlock() int64 {
 556	c.rw.RLock()
 557	defer c.rw.RUnlock()
 558	return c.blockNum
 559}
 560
 561// EthCurrentBlock returns the current blockNum
 562func (c *Client) EthCurrentBlock() (int64, error) {
 563	c.rw.RLock()
 564	defer c.rw.RUnlock()
 565
 566	if c.blockNum < c.maxBlockNum {
 567		panic("blockNum has decreased.  " +
 568			"After a rollback you must mine to reach the same or higher blockNum")
 569	}
 570	return c.blockNum, nil
 571}
 572
 573// EthTransactionReceipt returns the transaction receipt of the given txHash
 574func (c *Client) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
 575	c.rw.RLock()
 576	defer c.rw.RUnlock()
 577
 578	for i := int64(0); i < c.blockNum; i++ {
 579		b := c.blocks[i]
 580		_, ok := b.Rollup.Txs[txHash]
 581		if !ok {
 582			_, ok = b.Auction.Txs[txHash]
 583		}
 584		if ok {
 585			return &types.Receipt{
 586				TxHash:      txHash,
 587				Status:      types.ReceiptStatusSuccessful,
 588				BlockHash:   b.Eth.Hash,
 589				BlockNumber: big.NewInt(b.Eth.BlockNum),
 590			}, nil
 591		}
 592	}
 593
 594	return nil, nil
 595}
 596
 597// CtlAddERC20 adds an ERC20 token to the blockchain.
 598func (c *Client) CtlAddERC20(tokenAddr ethCommon.Address, constants eth.ERC20Consts) {
 599	nextBlock := c.nextBlock()
 600	e := nextBlock.Eth
 601	e.Tokens[tokenAddr] = constants
 602}
 603
 604// EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
 605func (c *Client) EthERC20Consts(tokenAddr ethCommon.Address) (*eth.ERC20Consts, error) {
 606	currentBlock := c.currentBlock()
 607	e := currentBlock.Eth
 608	if constants, ok := e.Tokens[tokenAddr]; ok {
 609		return &constants, nil
 610	}
 611	return nil, fmt.Errorf("tokenAddr not found")
 612}
 613
 614// func newHeader(number *big.Int) *types.Header {
 615// 	return &types.Header{
 616// 		Number: number,
 617// 		Time:   uint64(number.Int64()),
 618// 	}
 619// }
 620
 621// EthHeaderByNumber returns the *types.Header for the given block number in a
 622// deterministic way.
 623// func (c *Client) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
 624// 	return newHeader(number), nil
 625// }
 626
 627// EthBlockByNumber returns the *common.Block for the given block number in a
 628// deterministic way.
 629func (c *Client) EthBlockByNumber(ctx context.Context, blockNum int64) (*common.Block, error) {
 630	c.rw.RLock()
 631	defer c.rw.RUnlock()
 632
 633	if blockNum > c.blockNum {
 634		return nil, ethereum.NotFound
 635	}
 636	block := c.blocks[blockNum]
 637	return &common.Block{
 638		EthBlockNum: blockNum,
 639		Timestamp:   time.Unix(block.Eth.Time, 0),
 640		Hash:        block.Eth.Hash,
 641		ParentHash:  block.Eth.ParentHash,
 642	}, nil
 643}
 644
 645// EthAddress returns the ethereum address of the account loaded into the Client
 646func (c *Client) EthAddress() (*ethCommon.Address, error) {
 647	if c.addr == nil {
 648		return nil, eth.ErrAccountNil
 649	}
 650	return c.addr, nil
 651}
 652
 653var errTODO = fmt.Errorf("TODO: Not implemented yet")
 654
 655//
 656// Rollup
 657//
 658
 659// CtlAddL1TxUser adds an L1TxUser to the L1UserTxs queue of the Rollup
 660// func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) {
 661// 	c.rw.Lock()
 662// 	defer c.rw.Unlock()
 663//
 664// 	nextBlock := c.nextBlock()
 665// 	r := nextBlock.Rollup
 666// 	queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
 667// 	if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx {
 668// 		r.State.LastToForgeL1TxsNum++
 669// 		r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
 670// 		queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
 671// 	}
 672// 	if int64(l1Tx.FromIdx) > r.State.CurrentIdx {
 673// 		panic("l1Tx.FromIdx > r.State.CurrentIdx")
 674// 	}
 675// 	if int(l1Tx.TokenID)+1 > len(r.State.TokenList) {
 676// 		panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
 677// 	}
 678// 	queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
 679// 	r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
 680// 		L1Tx:            *l1Tx,
 681// 		ToForgeL1TxsNum: r.State.LastToForgeL1TxsNum,
 682// 		Position:        len(queue.L1TxQueue) - 1,
 683// 	})
 684// }
 685
 686// RollupL1UserTxERC20Permit is the interface to call the smart contract function
 687func (c *Client) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
 688	log.Error("TODO")
 689	return nil, errTODO
 690}
 691
 692// RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
 693func (c *Client) RollupL1UserTxERC20ETH(
 694	fromBJJ *babyjub.PublicKey,
 695	fromIdx int64,
 696	loadAmount *big.Int,
 697	amount *big.Int,
 698	tokenID uint32,
 699	toIdx int64,
 700) (tx *types.Transaction, err error) {
 701	c.rw.Lock()
 702	defer c.rw.Unlock()
 703	cpy := c.nextBlock().copy()
 704	defer func() { c.revertIfErr(err, cpy) }()
 705
 706	_, err = common.NewFloat16(amount)
 707	if err != nil {
 708		return nil, err
 709	}
 710	_, err = common.NewFloat16(loadAmount)
 711	if err != nil {
 712		return nil, err
 713	}
 714
 715	nextBlock := c.nextBlock()
 716	r := nextBlock.Rollup
 717	queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
 718	if len(queue.L1TxQueue) >= common.RollupConstMaxL1UserTx {
 719		r.State.LastToForgeL1TxsNum++
 720		r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
 721		queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
 722	}
 723	if fromIdx > r.State.CurrentIdx {
 724		panic("l1Tx.FromIdx > r.State.CurrentIdx")
 725	}
 726	if int(tokenID)+1 > len(r.State.TokenList) {
 727		panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
 728	}
 729	toForgeL1TxsNum := r.State.LastToForgeL1TxsNum
 730	l1Tx, err := common.NewL1Tx(&common.L1Tx{
 731		FromIdx:         common.Idx(fromIdx),
 732		FromEthAddr:     *c.addr,
 733		FromBJJ:         fromBJJ,
 734		Amount:          amount,
 735		LoadAmount:      loadAmount,
 736		TokenID:         common.TokenID(tokenID),
 737		ToIdx:           common.Idx(toIdx),
 738		ToForgeL1TxsNum: &toForgeL1TxsNum,
 739		Position:        len(queue.L1TxQueue),
 740		UserOrigin:      true,
 741	})
 742	if err != nil {
 743		return nil, err
 744	}
 745
 746	queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
 747	r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
 748		L1UserTx: *l1Tx,
 749	})
 750	return r.addTransaction(newTransaction("l1UserTxERC20ETH", l1Tx)), nil
 751}
 752
 753// RollupL1UserTxERC777 is the interface to call the smart contract function
 754// func (c *Client) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
 755// 	log.Error("TODO")
 756// 	return nil, errTODO
 757// }
 758
 759// RollupRegisterTokensCount is the interface to call the smart contract function
 760func (c *Client) RollupRegisterTokensCount() (*big.Int, error) {
 761	log.Error("TODO")
 762	return nil, errTODO
 763}
 764
 765// RollupWithdrawCircuit is the interface to call the smart contract function
 766func (c *Client) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) {
 767	log.Error("TODO")
 768	return nil, errTODO
 769}
 770
 771// RollupWithdrawMerkleProof is the interface to call the smart contract function
 772func (c *Client) RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
 773	c.rw.Lock()
 774	defer c.rw.Unlock()
 775	cpy := c.nextBlock().copy()
 776	defer func() { c.revertIfErr(err, cpy) }()
 777
 778	nextBlock := c.nextBlock()
 779	r := nextBlock.Rollup
 780
 781	if int(numExitRoot) >= len(r.State.ExitRoots) {
 782		return nil, fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)")
 783	}
 784	if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok {
 785		return nil, fmt.Errorf("exit already withdrawn")
 786	}
 787	r.State.ExitNullifierMap[numExitRoot][idx] = true
 788
 789	type data struct {
 790		BabyPubKey      *babyjub.PublicKey
 791		TokenID         uint32
 792		NumExitRoot     int64
 793		Idx             int64
 794		Amount          *big.Int
 795		Siblings        []*big.Int
 796		InstantWithdraw bool
 797	}
 798	tx = r.addTransaction(newTransaction("withdrawMerkleProof", data{
 799		BabyPubKey:      babyPubKey,
 800		TokenID:         tokenID,
 801		NumExitRoot:     numExitRoot,
 802		Idx:             idx,
 803		Amount:          amount,
 804		Siblings:        siblings,
 805		InstantWithdraw: instantWithdraw,
 806	}))
 807	r.Events.Withdraw = append(r.Events.Withdraw, eth.RollupEventWithdraw{
 808		Idx:             uint64(idx),
 809		NumExitRoot:     uint64(numExitRoot),
 810		InstantWithdraw: instantWithdraw,
 811		TxHash:          tx.Hash(),
 812	})
 813
 814	if !instantWithdraw {
 815		w := nextBlock.WDelayer
 816		w.deposit(tx.Hash(), *c.addr, r.State.TokenList[int(tokenID)], amount)
 817	}
 818	return tx, nil
 819}
 820
 821type transactionData struct {
 822	Name  string
 823	Value interface{}
 824}
 825
 826func newTransaction(name string, value interface{}) *types.Transaction {
 827	data, err := json.Marshal(transactionData{name, value})
 828	if err != nil {
 829		panic(err)
 830	}
 831	return types.NewTransaction(0, ethCommon.Address{}, nil, 0, nil,
 832		data)
 833}
 834
 835// RollupForgeBatch is the interface to call the smart contract function
 836func (c *Client) RollupForgeBatch(args *eth.RollupForgeBatchArgs) (tx *types.Transaction, err error) {
 837	c.rw.Lock()
 838	defer c.rw.Unlock()
 839	cpy := c.nextBlock().copy()
 840	defer func() { c.revertIfErr(err, cpy) }()
 841	if c.addr == nil {
 842		return nil, eth.ErrAccountNil
 843	}
 844
 845	a := c.nextBlock().Auction
 846	ok, err := a.canForge(*c.addr, a.Eth.BlockNum)
 847	if err != nil {
 848		return nil, err
 849	}
 850	if !ok {
 851		return nil, fmt.Errorf("incorrect slot")
 852	}
 853
 854	// TODO: Verify proof
 855
 856	// Auction
 857	err = a.forge(*c.addr)
 858	if err != nil {
 859		return nil, err
 860	}
 861
 862	// TODO: If successful, store the tx in a successful array.
 863	// TODO: If failed, store the tx in a failed array.
 864	// TODO: Add method to move the tx to another block, reapply it there, and possibly go from successful to failed.
 865
 866	return c.addBatch(args)
 867}
 868
 869// CtlAddBatch adds forged batch to the Rollup, without checking any ZKProof
 870func (c *Client) CtlAddBatch(args *eth.RollupForgeBatchArgs) {
 871	c.rw.Lock()
 872	defer c.rw.Unlock()
 873
 874	if _, err := c.addBatch(args); err != nil {
 875		panic(err)
 876	}
 877}
 878
 879func (c *Client) addBatch(args *eth.RollupForgeBatchArgs) (*types.Transaction, error) {
 880	nextBlock := c.nextBlock()
 881	r := nextBlock.Rollup
 882	r.State.StateRoot = args.NewStRoot
 883	if args.NewLastIdx < r.State.CurrentIdx {
 884		return nil, fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx")
 885	}
 886	r.State.CurrentIdx = args.NewLastIdx
 887	r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)
 888	r.State.ExitRoots = append(r.State.ExitRoots, args.NewExitRoot)
 889	if args.L1Batch {
 890		r.State.CurrentToForgeL1TxsNum++
 891		if r.State.CurrentToForgeL1TxsNum == r.State.LastToForgeL1TxsNum {
 892			r.State.LastToForgeL1TxsNum++
 893			r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
 894		}
 895	}
 896	ethTx := r.addTransaction(newTransaction("forgebatch", args))
 897	c.forgeBatchArgsPending[ethTx.Hash()] = &batch{*args, *c.addr}
 898	r.Events.ForgeBatch = append(r.Events.ForgeBatch, eth.RollupEventForgeBatch{
 899		BatchNum:  int64(len(r.State.ExitRoots)) - 1,
 900		EthTxHash: ethTx.Hash(),
 901	})
 902
 903	return ethTx, nil
 904}
 905
 906// RollupAddTokenSimple is a wrapper around RollupAddToken that automatically
 907// sets `deadlie`.
 908func (c *Client) RollupAddTokenSimple(tokenAddress ethCommon.Address, feeAddToken *big.Int) (tx *types.Transaction, err error) {
 909	return c.RollupAddToken(tokenAddress, feeAddToken, big.NewInt(9999)) //nolint:gomnd
 910}
 911
 912// RollupAddToken is the interface to call the smart contract function
 913func (c *Client) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int,
 914	deadline *big.Int) (tx *types.Transaction, err error) {
 915	c.rw.Lock()
 916	defer c.rw.Unlock()
 917	cpy := c.nextBlock().copy()
 918	defer func() { c.revertIfErr(err, cpy) }()
 919	if c.addr == nil {
 920		return nil, eth.ErrAccountNil
 921	}
 922
 923	nextBlock := c.nextBlock()
 924	r := nextBlock.Rollup
 925	if _, ok := r.State.TokenMap[tokenAddress]; ok {
 926		return nil, fmt.Errorf("Token %v already registered", tokenAddress)
 927	}
 928	if feeAddToken.Cmp(r.Vars.FeeAddToken) != 0 {
 929		return nil, fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken)
 930	}
 931
 932	r.State.TokenMap[tokenAddress] = true
 933	r.State.TokenList = append(r.State.TokenList, tokenAddress)
 934	r.Events.AddToken = append(r.Events.AddToken, eth.RollupEventAddToken{TokenAddress: tokenAddress,
 935		TokenID: uint32(len(r.State.TokenList) - 1)})
 936	return r.addTransaction(newTransaction("addtoken", tokenAddress)), nil
 937}
 938
 939// RollupGetCurrentTokens is the interface to call the smart contract function
 940func (c *Client) RollupGetCurrentTokens() (*big.Int, error) {
 941	c.rw.RLock()
 942	defer c.rw.RUnlock()
 943
 944	log.Error("TODO")
 945	return nil, errTODO
 946}
 947
 948// RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
 949func (c *Client) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (tx *types.Transaction, err error) {
 950	c.rw.Lock()
 951	defer c.rw.Unlock()
 952	cpy := c.nextBlock().copy()
 953	defer func() { c.revertIfErr(err, cpy) }()
 954	if c.addr == nil {
 955		return nil, eth.ErrAccountNil
 956	}
 957
 958	nextBlock := c.nextBlock()
 959	r := nextBlock.Rollup
 960	r.Vars.ForgeL1L2BatchTimeout = newForgeL1Timeout
 961	r.Events.UpdateForgeL1L2BatchTimeout = append(r.Events.UpdateForgeL1L2BatchTimeout,
 962		eth.RollupEventUpdateForgeL1L2BatchTimeout{NewForgeL1L2BatchTimeout: newForgeL1Timeout})
 963
 964	return r.addTransaction(newTransaction("updateForgeL1L2BatchTimeout", newForgeL1Timeout)), nil
 965}
 966
 967// RollupUpdateFeeAddToken is the interface to call the smart contract function
 968func (c *Client) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
 969	c.rw.Lock()
 970	defer c.rw.Unlock()
 971	cpy := c.nextBlock().copy()
 972	defer func() { c.revertIfErr(err, cpy) }()
 973	if c.addr == nil {
 974		return nil, eth.ErrAccountNil
 975	}
 976
 977	log.Error("TODO")
 978	return nil, errTODO
 979}
 980
 981// RollupUpdateTokensHEZ is the interface to call the smart contract function
 982// func (c *Client) RollupUpdateTokensHEZ(newTokenHEZ ethCommon.Address) (tx *types.Transaction, err error) {
 983// 	c.rw.Lock()
 984// 	defer c.rw.Unlock()
 985// 	cpy := c.nextBlock().copy()
 986// 	defer func() { c.revertIfErr(err, cpy) }()
 987//
 988// 	log.Error("TODO")
 989// 	return nil, errTODO
 990// }
 991
 992// RollupUpdateGovernance is the interface to call the smart contract function
 993// func (c *Client) RollupUpdateGovernance() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
 994// 	return nil, errTODO
 995// }
 996
 997// RollupConstants returns the Constants of the Rollup Smart Contract
 998func (c *Client) RollupConstants() (*common.RollupConstants, error) {
 999	c.rw.RLock()
1000	defer c.rw.RUnlock()
1001
1002	return c.rollupConstants, nil
1003}
1004
1005// RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
1006func (c *Client) RollupEventsByBlock(blockNum int64) (*eth.RollupEvents, *ethCommon.Hash, error) {
1007	c.rw.RLock()
1008	defer c.rw.RUnlock()
1009
1010	block, ok := c.blocks[blockNum]
1011	if !ok {
1012		return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
1013	}
1014	return &block.Rollup.Events, &block.Eth.Hash, nil
1015}
1016
1017// RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
1018func (c *Client) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*eth.RollupForgeBatchArgs, *ethCommon.Address, error) {
1019	c.rw.RLock()
1020	defer c.rw.RUnlock()
1021
1022	batch, ok := c.forgeBatchArgs[ethTxHash]
1023	if !ok {
1024		return nil, nil, fmt.Errorf("transaction not found")
1025	}
1026	return &batch.ForgeBatchArgs, &batch.Sender, nil
1027}
1028
1029//
1030// Auction
1031//
1032
1033// AuctionSetSlotDeadline is the interface to call the smart contract function
1034func (c *Client) AuctionSetSlotDeadline(newDeadline uint8) (tx *types.Transaction, err error) {
1035	c.rw.Lock()
1036	defer c.rw.Unlock()
1037	cpy := c.nextBlock().copy()
1038	defer func() { c.revertIfErr(err, cpy) }()
1039	if c.addr == nil {
1040		return nil, eth.ErrAccountNil
1041	}
1042
1043	log.Error("TODO")
1044	return nil, errTODO
1045}
1046
1047// AuctionGetSlotDeadline is the interface to call the smart contract function
1048func (c *Client) AuctionGetSlotDeadline() (uint8, error) {
1049	c.rw.RLock()
1050	defer c.rw.RUnlock()
1051
1052	log.Error("TODO")
1053	return 0, errTODO
1054}
1055
1056// AuctionSetOpenAuctionSlots is the interface to call the smart contract function
1057func (c *Client) AuctionSetOpenAuctionSlots(newOpenAuctionSlots uint16) (tx *types.Transaction, err error) {
1058	c.rw.Lock()
1059	defer c.rw.Unlock()
1060	cpy := c.nextBlock().copy()
1061	defer func() { c.revertIfErr(err, cpy) }()
1062	if c.addr == nil {
1063		return nil, eth.ErrAccountNil
1064	}
1065
1066	nextBlock := c.nextBlock()
1067	a := nextBlock.Auction
1068	a.Vars.OpenAuctionSlots = newOpenAuctionSlots
1069	a.Events.NewOpenAuctionSlots = append(a.Events.NewOpenAuctionSlots,
1070		eth.AuctionEventNewOpenAuctionSlots{NewOpenAuctionSlots: newOpenAuctionSlots})
1071
1072	return a.addTransaction(newTransaction("setOpenAuctionSlots", newOpenAuctionSlots)), nil
1073}
1074
1075// AuctionGetOpenAuctionSlots is the interface to call the smart contract function
1076func (c *Client) AuctionGetOpenAuctionSlots() (uint16, error) {
1077	c.rw.RLock()
1078	defer c.rw.RUnlock()
1079
1080	log.Error("TODO")
1081	return 0, errTODO
1082}
1083
1084// AuctionSetClosedAuctionSlots is the interface to call the smart contract function
1085func (c *Client) AuctionSetClosedAuctionSlots(newClosedAuctionSlots uint16) (tx *types.Transaction, err error) {
1086	c.rw.Lock()
1087	defer c.rw.Unlock()
1088	cpy := c.nextBlock().copy()
1089	defer func() { c.revertIfErr(err, cpy) }()
1090	if c.addr == nil {
1091		return nil, eth.ErrAccountNil
1092	}
1093
1094	log.Error("TODO")
1095	return nil, errTODO
1096}
1097
1098// AuctionGetClosedAuctionSlots is the interface to call the smart contract function
1099func (c *Client) AuctionGetClosedAuctionSlots() (uint16, error) {
1100	c.rw.RLock()
1101	defer c.rw.RUnlock()
1102
1103	log.Error("TODO")
1104	return 0, errTODO
1105}
1106
1107// AuctionSetOutbidding is the interface to call the smart contract function
1108func (c *Client) AuctionSetOutbidding(newOutbidding uint16) (tx *types.Transaction, err error) {
1109	c.rw.Lock()
1110	defer c.rw.Unlock()
1111	cpy := c.nextBlock().copy()
1112	defer func() { c.revertIfErr(err, cpy) }()
1113	if c.addr == nil {
1114		return nil, eth.ErrAccountNil
1115	}
1116
1117	log.Error("TODO")
1118	return nil, errTODO
1119}
1120
1121// AuctionGetOutbidding is the interface to call the smart contract function
1122func (c *Client) AuctionGetOutbidding() (uint16, error) {
1123	c.rw.RLock()
1124	defer c.rw.RUnlock()
1125
1126	log.Error("TODO")
1127	return 0, errTODO
1128}
1129
1130// AuctionSetAllocationRatio is the interface to call the smart contract function
1131func (c *Client) AuctionSetAllocationRatio(newAllocationRatio [3]uint16) (tx *types.Transaction, err error) {
1132	c.rw.Lock()
1133	defer c.rw.Unlock()
1134	cpy := c.nextBlock().copy()
1135	defer func() { c.revertIfErr(err, cpy) }()
1136	if c.addr == nil {
1137		return nil, eth.ErrAccountNil
1138	}
1139
1140	log.Error("TODO")
1141	return nil, errTODO
1142}
1143
1144// AuctionGetAllocationRatio is the interface to call the smart contract function
1145func (c *Client) AuctionGetAllocationRatio() ([3]uint16, error) {
1146	c.rw.RLock()
1147	defer c.rw.RUnlock()
1148
1149	log.Error("TODO")
1150	return [3]uint16{}, errTODO
1151}
1152
1153// AuctionSetDonationAddress is the interface to call the smart contract function
1154func (c *Client) AuctionSetDonationAddress(newDonationAddress ethCommon.Address) (tx *types.Transaction, err error) {
1155	c.rw.Lock()
1156	defer c.rw.Unlock()
1157	cpy := c.nextBlock().copy()
1158	defer func() { c.revertIfErr(err, cpy) }()
1159	if c.addr == nil {
1160		return nil, eth.ErrAccountNil
1161	}
1162
1163	log.Error("TODO")
1164	return nil, errTODO
1165}
1166
1167// AuctionGetDonationAddress is the interface to call the smart contract function
1168func (c *Client) AuctionGetDonationAddress() (*ethCommon.Address, error) {
1169	c.rw.RLock()
1170	defer c.rw.RUnlock()
1171
1172	log.Error("TODO")
1173	return nil, errTODO
1174}
1175
1176// AuctionSetBootCoordinator is the interface to call the smart contract function
1177func (c *Client) AuctionSetBootCoordinator(newBootCoordinator ethCommon.Address) (tx *types.Transaction, err error) {
1178	c.rw.Lock()
1179	defer c.rw.Unlock()
1180	cpy := c.nextBlock().copy()
1181	defer func() { c.revertIfErr(err, cpy) }()
1182	if c.addr == nil {
1183		return nil, eth.ErrAccountNil
1184	}
1185
1186	log.Error("TODO")
1187	return nil, errTODO
1188}
1189
1190// AuctionGetBootCoordinator is the interface to call the smart contract function
1191func (c *Client) AuctionGetBootCoordinator() (*ethCommon.Address, error) {
1192	c.rw.RLock()
1193	defer c.rw.RUnlock()
1194
1195	currentBlock := c.currentBlock()
1196	a := currentBlock.Auction
1197
1198	return &a.Vars.BootCoordinator, nil
1199}
1200
1201// AuctionChangeDefaultSlotSetBid is the interface to call the smart contract function
1202func (c *Client) AuctionChangeDefaultSlotSetBid(slotSet int64, newInitialMinBid *big.Int) (tx *types.Transaction, err error) {
1203	c.rw.Lock()
1204	defer c.rw.Unlock()
1205	cpy := c.nextBlock().copy()
1206	defer func() { c.revertIfErr(err, cpy) }()
1207	if c.addr == nil {
1208		return nil, eth.ErrAccountNil
1209	}
1210
1211	log.Error("TODO")
1212	return nil, errTODO
1213}
1214
1215// AuctionSetCoordinator is the interface to call the smart contract function
1216func (c *Client) AuctionSetCoordinator(forger ethCommon.Address, URL string) (tx *types.Transaction, err error) {
1217	c.rw.Lock()
1218	defer c.rw.Unlock()
1219	cpy := c.nextBlock().copy()
1220	defer func() { c.revertIfErr(err, cpy) }()
1221	if c.addr == nil {
1222		return nil, eth.ErrAccountNil
1223	}
1224
1225	nextBlock := c.nextBlock()
1226	a := nextBlock.Auction
1227
1228	a.State.Coordinators[*c.addr] = &eth.Coordinator{
1229		Forger: forger,
1230		URL:    URL,
1231	}
1232
1233	a.Events.SetCoordinator = append(a.Events.SetCoordinator,
1234		eth.AuctionEventSetCoordinator{
1235			BidderAddress:  *c.addr,
1236			ForgerAddress:  forger,
1237			CoordinatorURL: URL,
1238		})
1239
1240	type data struct {
1241		BidderAddress ethCommon.Address
1242		ForgerAddress ethCommon.Address
1243		URL           string
1244	}
1245	return a.addTransaction(newTransaction("registercoordinator", data{*c.addr, forger, URL})), nil
1246}
1247
1248// AuctionIsRegisteredCoordinator is the interface to call the smart contract function
1249func (c *Client) AuctionIsRegisteredCoordinator(forgerAddress ethCommon.Address) (bool, error) {
1250	c.rw.RLock()
1251	defer c.rw.RUnlock()
1252
1253	log.Error("TODO")
1254	return false, errTODO
1255}
1256
1257// AuctionUpdateCoordinatorInfo is the interface to call the smart contract function
1258func (c *Client) AuctionUpdateCoordinatorInfo(forgerAddress ethCommon.Address, newWithdrawAddress ethCommon.Address, newURL string) (tx *types.Transaction, err error) {
1259	c.rw.Lock()
1260	defer c.rw.Unlock()
1261	cpy := c.nextBlock().copy()
1262	defer func() { c.revertIfErr(err, cpy) }()
1263	if c.addr == nil {
1264		return nil, eth.ErrAccountNil
1265	}
1266
1267	log.Error("TODO")
1268	return nil, errTODO
1269}
1270
1271// AuctionGetSlotNumber is the interface to call the smart contract function
1272func (c *Client) AuctionGetSlotNumber(blockNum int64) (int64, error) {
1273	c.rw.RLock()
1274	defer c.rw.RUnlock()
1275
1276	currentBlock := c.currentBlock()
1277	a := currentBlock.Auction
1278	return a.getSlotNumber(blockNum), nil
1279}
1280
1281// AuctionGetCurrentSlotNumber is the interface to call the smart contract function
1282func (c *Client) AuctionGetCurrentSlotNumber() (int64, error) {
1283	c.rw.RLock()
1284	defer c.rw.RUnlock()
1285
1286	log.Error("TODO")
1287	return 0, errTODO
1288}
1289
1290// AuctionGetMinBidBySlot is the interface to call the smart contract function
1291func (c *Client) AuctionGetMinBidBySlot(slot int64) (*big.Int, error) {
1292	c.rw.RLock()
1293	defer c.rw.RUnlock()
1294
1295	log.Error("TODO")
1296	return nil, errTODO
1297}
1298
1299// AuctionGetDefaultSlotSetBid is the interface to call the smart contract function
1300func (c *Client) AuctionGetDefaultSlotSetBid(slotSet uint8) (*big.Int, error) {
1301	c.rw.RLock()
1302	defer c.rw.RUnlock()
1303
1304	log.Error("TODO")
1305	return nil, errTODO
1306}
1307
1308// AuctionGetSlotSet is the interface to call the smart contract function
1309func (c *Client) AuctionGetSlotSet(slot int64) (*big.Int, error) {
1310	c.rw.RLock()
1311	defer c.rw.RUnlock()
1312
1313	log.Error("TODO")
1314	return nil, errTODO
1315}
1316
1317// AuctionTokensReceived is the interface to call the smart contract function
1318// func (c *Client) AuctionTokensReceived(operator, from, to ethCommon.Address, amount *big.Int, userData, operatorData []byte) error {
1319// 	return errTODO
1320// }
1321
1322// AuctionBidSimple is a wrapper around AuctionBid that automatically sets `amount` and `deadline`.
1323func (c *Client) AuctionBidSimple(slot int64, bidAmount *big.Int) (tx *types.Transaction, err error) {
1324	return c.AuctionBid(bidAmount, slot, bidAmount, big.NewInt(99999)) //nolint:gomnd
1325}
1326
1327// AuctionBid is the interface to call the smart contract function.  This
1328// implementation behaves as if any address has infinite tokens.
1329func (c *Client) AuctionBid(amount *big.Int, slot int64, bidAmount *big.Int,
1330	deadline *big.Int) (tx *types.Transaction, err error) {
1331	c.rw.Lock()
1332	defer c.rw.Unlock()
1333	cpy := c.nextBlock().copy()
1334	defer func() { func() { c.revertIfErr(err, cpy) }() }()
1335	if c.addr == nil {
1336		return nil, eth.ErrAccountNil
1337	}
1338
1339	nextBlock := c.nextBlock()
1340	a := nextBlock.Auction
1341
1342	if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
1343		return nil, errBidClosed
1344	}
1345
1346	if slot >= a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots)+int64(a.Vars.OpenAuctionSlots) {
1347		return nil, errBidNotOpen
1348	}
1349
1350	minBid, err := a.getMinBidBySlot(slot)
1351	if err != nil {
1352		return nil, err
1353	}
1354	if bidAmount.Cmp(minBid) == -1 {
1355		return nil, errBidBelowMin
1356	}
1357
1358	if _, ok := a.State.Coordinators[*c.addr]; !ok {
1359		return nil, errCoordNotReg
1360	}
1361
1362	slotState, ok := a.State.Slots[slot]
1363	if !ok {
1364		slotState = eth.NewSlotState()
1365		a.State.Slots[slot] = slotState
1366	}
1367	slotState.Bidder = *c.addr
1368	slotState.BidAmount = bidAmount
1369
1370	a.Events.NewBid = append(a.Events.NewBid,
1371		eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, Bidder: *c.addr})
1372
1373	type data struct {
1374		Slot      int64
1375		BidAmount *big.Int
1376		Bidder    ethCommon.Address
1377	}
1378	return a.addTransaction(newTransaction("bid", data{slot, bidAmount, *c.addr})), nil
1379}
1380
1381// AuctionMultiBid is the interface to call the smart contract function.  This
1382// implementation behaves as if any address has infinite tokens.
1383func (c *Client) AuctionMultiBid(amount *big.Int, startingSlot int64, endingSlot int64, slotSet [6]bool,
1384	maxBid, closedMinBid, deadline *big.Int) (tx *types.Transaction, err error) {
1385	c.rw.Lock()
1386	defer c.rw.Unlock()
1387	cpy := c.nextBlock().copy()
1388	defer func() { c.revertIfErr(err, cpy) }()
1389	if c.addr == nil {
1390		return nil, eth.ErrAccountNil
1391	}
1392
1393	log.Error("TODO")
1394	return nil, errTODO
1395}
1396
1397// AuctionCanForge is the interface to call the smart contract function
1398func (c *Client) AuctionCanForge(forger ethCommon.Address, blockNum int64) (bool, error) {
1399	c.rw.RLock()
1400	defer c.rw.RUnlock()
1401
1402	currentBlock := c.currentBlock()
1403	a := currentBlock.Auction
1404	return a.canForge(forger, blockNum)
1405}
1406
1407// AuctionForge is the interface to call the smart contract function
1408func (c *Client) AuctionForge(forger ethCommon.Address) (tx *types.Transaction, err error) {
1409	c.rw.Lock()
1410	defer c.rw.Unlock()
1411	cpy := c.nextBlock().copy()
1412	defer func() { c.revertIfErr(err, cpy) }()
1413	if c.addr == nil {
1414		return nil, eth.ErrAccountNil
1415	}
1416
1417	log.Error("TODO")
1418	return nil, errTODO
1419}
1420
1421// AuctionClaimHEZ is the interface to call the smart contract function
1422func (c *Client) AuctionClaimHEZ() (tx *types.Transaction, err error) {
1423	c.rw.Lock()
1424	defer c.rw.Unlock()
1425	cpy := c.nextBlock().copy()
1426	defer func() { c.revertIfErr(err, cpy) }()
1427	if c.addr == nil {
1428		return nil, eth.ErrAccountNil
1429	}
1430
1431	log.Error("TODO")
1432	return nil, errTODO
1433}
1434
1435// AuctionGetClaimableHEZ is the interface to call the smart contract function
1436func (c *Client) AuctionGetClaimableHEZ(bidder ethCommon.Address) (*big.Int, error) {
1437	c.rw.RLock()
1438	defer c.rw.RUnlock()
1439
1440	log.Error("TODO")
1441	return nil, errTODO
1442}
1443
1444// AuctionConstants returns the Constants of the Auction Smart Contract
1445func (c *Client) AuctionConstants() (*common.AuctionConstants, error) {
1446	c.rw.RLock()
1447	defer c.rw.RUnlock()
1448
1449	return c.auctionConstants, nil
1450}
1451
1452// AuctionEventsByBlock returns the events in a block that happened in the Auction Smart Contract
1453func (c *Client) AuctionEventsByBlock(blockNum int64) (*eth.AuctionEvents, *ethCommon.Hash, error) {
1454	c.rw.RLock()
1455	defer c.rw.RUnlock()
1456
1457	block, ok := c.blocks[blockNum]
1458	if !ok {
1459		return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
1460	}
1461	return &block.Auction.Events, &block.Eth.Hash, nil
1462}
1463
1464//
1465// WDelayer
1466//
1467
1468// WDelayerGetHermezGovernanceDAOAddress is the interface to call the smart contract function
1469func (c *Client) WDelayerGetHermezGovernanceDAOAddress() (*ethCommon.Address, error) {
1470	c.rw.RLock()
1471	defer c.rw.RUnlock()
1472
1473	log.Error("TODO")
1474	return nil, errTODO
1475}
1476
1477// WDelayerSetHermezGovernanceDAOAddress is the interface to call the smart contract function
1478func (c *Client) WDelayerSetHermezGovernanceDAOAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
1479	c.rw.Lock()
1480	defer c.rw.Unlock()
1481	cpy := c.nextBlock().copy()
1482	defer func() { c.revertIfErr(err, cpy) }()
1483	if c.addr == nil {
1484		return nil, eth.ErrAccountNil
1485	}
1486
1487	log.Error("TODO")
1488	return nil, errTODO
1489}
1490
1491// WDelayerGetHermezKeeperAddress is the interface to call the smart contract function
1492func (c *Client) WDelayerGetHermezKeeperAddress() (*ethCommon.Address, error) {
1493	c.rw.RLock()
1494	defer c.rw.RUnlock()
1495
1496	log.Error("TODO")
1497	return nil, errTODO
1498}
1499
1500// WDelayerSetHermezKeeperAddress is the interface to call the smart contract function
1501func (c *Client) WDelayerSetHermezKeeperAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
1502	c.rw.Lock()
1503	defer c.rw.Unlock()
1504	cpy := c.nextBlock().copy()
1505	defer func() { c.revertIfErr(err, cpy) }()
1506	if c.addr == nil {
1507		return nil, eth.ErrAccountNil
1508	}
1509
1510	log.Error("TODO")
1511	return nil, errTODO
1512}
1513
1514// WDelayerGetWhiteHackGroupAddress is the interface to call the smart contract function
1515func (c *Client) WDelayerGetWhiteHackGroupAddress() (*ethCommon.Address, error) {
1516	c.rw.RLock()
1517	defer c.rw.RUnlock()
1518
1519	log.Error("TODO")
1520	return nil, errTODO
1521}
1522
1523// WDelayerSetWhiteHackGroupAddress is the interface to call the smart contract function
1524func (c *Client) WDelayerSetWhiteHackGroupAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
1525	c.rw.Lock()
1526	defer c.rw.Unlock()
1527	cpy := c.nextBlock().copy()
1528	defer func() { c.revertIfErr(err, cpy) }()
1529	if c.addr == nil {
1530		return nil, eth.ErrAccountNil
1531	}
1532
1533	log.Error("TODO")
1534	return nil, errTODO
1535}
1536
1537// WDelayerIsEmergencyMode is the interface to call the smart contract function
1538func (c *Client) WDelayerIsEmergencyMode() (bool, error) {
1539	c.rw.RLock()
1540	defer c.rw.RUnlock()
1541
1542	log.Error("TODO")
1543	return false, errTODO
1544}
1545
1546// WDelayerGetWithdrawalDelay is the interface to call the smart contract function
1547func (c *Client) WDelayerGetWithdrawalDelay() (*big.Int, error) {
1548	c.rw.RLock()
1549	defer c.rw.RUnlock()
1550
1551	log.Error("TODO")
1552	return nil, errTODO
1553}
1554
1555// WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function
1556func (c *Client) WDelayerGetEmergencyModeStartingTime() (*big.Int, error) {
1557	c.rw.RLock()
1558	defer c.rw.RUnlock()
1559
1560	log.Error("TODO")
1561	return nil, errTODO
1562}
1563
1564// WDelayerEnableEmergencyMode is the interface to call the smart contract function
1565func (c *Client) WDelayerEnableEmergencyMode() (tx *types.Transaction, err error) {
1566	c.rw.Lock()
1567	defer c.rw.Unlock()
1568	cpy := c.nextBlock().copy()
1569	defer func() { c.revertIfErr(err, cpy) }()
1570	if c.addr == nil {
1571		return nil, eth.ErrAccountNil
1572	}
1573
1574	log.Error("TODO")
1575	return nil, errTODO
1576}
1577
1578// WDelayerChangeWithdrawalDelay is the interface to call the smart contract function
1579func (c *Client) WDelayerChangeWithdrawalDelay(newWithdrawalDelay uint64) (tx *types.Transaction, err error) {
1580	c.rw.Lock()
1581	defer c.rw.Unlock()
1582	cpy := c.nextBlock().copy()
1583	defer func() { c.revertIfErr(err, cpy) }()
1584	if c.addr == nil {
1585		return nil, eth.ErrAccountNil
1586	}
1587
1588	nextBlock := c.nextBlock()
1589	w := nextBlock.WDelayer
1590	w.Vars.WithdrawalDelay = newWithdrawalDelay
1591	w.Events.NewWithdrawalDelay = append(w.Events.NewWithdrawalDelay,
1592		eth.WDelayerEventNewWithdrawalDelay{WithdrawalDelay: newWithdrawalDelay})
1593
1594	return w.addTransaction(newTransaction("changeWithdrawalDelay", newWithdrawalDelay)), nil
1595}
1596
1597// WDelayerDepositInfo is the interface to call the smart contract function
1598func (c *Client) WDelayerDepositInfo(owner, token ethCommon.Address) (eth.DepositState, error) {
1599	c.rw.RLock()
1600	defer c.rw.RUnlock()
1601
1602	log.Error("TODO")
1603	return eth.DepositState{}, errTODO
1604}
1605
1606// WDelayerDeposit is the interface to call the smart contract function
1607func (c *Client) WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
1608	c.rw.Lock()
1609	defer c.rw.Unlock()
1610	cpy := c.nextBlock().copy()
1611	defer func() { c.revertIfErr(err, cpy) }()
1612	if c.addr == nil {
1613		return nil, eth.ErrAccountNil
1614	}
1615
1616	log.Error("TODO")
1617	return nil, errTODO
1618}
1619
1620// WDelayerWithdrawal is the interface to call the smart contract function
1621func (c *Client) WDelayerWithdrawal(owner, token ethCommon.Address) (tx *types.Transaction, err error) {
1622	c.rw.Lock()
1623	defer c.rw.Unlock()
1624	cpy := c.nextBlock().copy()
1625	defer func() { c.revertIfErr(err, cpy) }()
1626	if c.addr == nil {
1627		return nil, eth.ErrAccountNil
1628	}
1629
1630	log.Error("TODO")
1631	return nil, errTODO
1632}
1633
1634// WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function
1635func (c *Client) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
1636	c.rw.Lock()
1637	defer c.rw.Unlock()
1638	cpy := c.nextBlock().copy()
1639	defer func() { c.revertIfErr(err, cpy) }()
1640	if c.addr == nil {
1641		return nil, eth.ErrAccountNil
1642	}
1643
1644	log.Error("TODO")
1645	return nil, errTODO
1646}
1647
1648// WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract
1649func (c *Client) WDelayerEventsByBlock(blockNum int64) (*eth.WDelayerEvents, *ethCommon.Hash, error) {
1650	c.rw.RLock()
1651	defer c.rw.RUnlock()
1652
1653	block, ok := c.blocks[blockNum]
1654	if !ok {
1655		return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
1656	}
1657	return &block.WDelayer.Events, &block.Eth.Hash, nil
1658}
1659
1660// WDelayerConstants returns the Constants of the WDelayer Contract
1661func (c *Client) WDelayerConstants() (*common.WDelayerConstants, error) {
1662	c.rw.RLock()
1663	defer c.rw.RUnlock()
1664
1665	return c.wDelayerConstants, nil
1666}