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.

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