You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1661 lines
49 KiB

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