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.

1677 lines
50 KiB

Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
  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. // fmt.Printf("DBG canForge slot: %v\n", slotToForge)
  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. // CtlLastBlock returns the last blockNum without checks
  497. func (c *Client) CtlLastBlock() int64 {
  498. c.rw.RLock()
  499. defer c.rw.RUnlock()
  500. return c.blockNum
  501. }
  502. // EthLastBlock returns the last blockNum
  503. func (c *Client) EthLastBlock() (int64, error) {
  504. c.rw.RLock()
  505. defer c.rw.RUnlock()
  506. if c.blockNum < c.maxBlockNum {
  507. panic("blockNum has decreased. " +
  508. "After a rollback you must mine to reach the same or higher blockNum")
  509. }
  510. return c.blockNum, nil
  511. }
  512. // EthTransactionReceipt returns the transaction receipt of the given txHash
  513. func (c *Client) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  514. c.rw.RLock()
  515. defer c.rw.RUnlock()
  516. for i := int64(0); i < c.blockNum; i++ {
  517. b := c.blocks[i]
  518. _, ok := b.Rollup.Txs[txHash]
  519. if !ok {
  520. _, ok = b.Auction.Txs[txHash]
  521. }
  522. if ok {
  523. return &types.Receipt{
  524. TxHash: txHash,
  525. Status: types.ReceiptStatusSuccessful,
  526. BlockHash: b.Eth.Hash,
  527. BlockNumber: big.NewInt(b.Eth.BlockNum),
  528. }, nil
  529. }
  530. }
  531. return nil, nil
  532. }
  533. // CtlAddERC20 adds an ERC20 token to the blockchain.
  534. func (c *Client) CtlAddERC20(tokenAddr ethCommon.Address, constants eth.ERC20Consts) {
  535. nextBlock := c.nextBlock()
  536. e := nextBlock.Eth
  537. e.Tokens[tokenAddr] = constants
  538. }
  539. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  540. func (c *Client) EthERC20Consts(tokenAddr ethCommon.Address) (*eth.ERC20Consts, error) {
  541. currentBlock := c.currentBlock()
  542. e := currentBlock.Eth
  543. if constants, ok := e.Tokens[tokenAddr]; ok {
  544. return &constants, nil
  545. }
  546. return nil, fmt.Errorf("tokenAddr not found")
  547. }
  548. // func newHeader(number *big.Int) *types.Header {
  549. // return &types.Header{
  550. // Number: number,
  551. // Time: uint64(number.Int64()),
  552. // }
  553. // }
  554. // EthHeaderByNumber returns the *types.Header for the given block number in a
  555. // deterministic way.
  556. // func (c *Client) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  557. // return newHeader(number), nil
  558. // }
  559. // EthBlockByNumber returns the *common.Block for the given block number in a
  560. // deterministic way.
  561. func (c *Client) EthBlockByNumber(ctx context.Context, blockNum int64) (*common.Block, error) {
  562. c.rw.RLock()
  563. defer c.rw.RUnlock()
  564. if blockNum > c.blockNum {
  565. return nil, ethereum.NotFound
  566. }
  567. block := c.blocks[blockNum]
  568. return &common.Block{
  569. EthBlockNum: blockNum,
  570. Timestamp: time.Unix(block.Eth.Time, 0),
  571. Hash: block.Eth.Hash,
  572. ParentHash: block.Eth.ParentHash,
  573. }, nil
  574. }
  575. // EthAddress returns the ethereum address of the account loaded into the Client
  576. func (c *Client) EthAddress() (*ethCommon.Address, error) {
  577. if c.addr == nil {
  578. return nil, eth.ErrAccountNil
  579. }
  580. return c.addr, nil
  581. }
  582. var errTODO = fmt.Errorf("TODO: Not implemented yet")
  583. //
  584. // Rollup
  585. //
  586. // CtlAddL1TxUser adds an L1TxUser to the L1UserTxs queue of the Rollup
  587. // func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) {
  588. // c.rw.Lock()
  589. // defer c.rw.Unlock()
  590. //
  591. // nextBlock := c.nextBlock()
  592. // r := nextBlock.Rollup
  593. // queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  594. // if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx {
  595. // r.State.LastToForgeL1TxsNum++
  596. // r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  597. // queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  598. // }
  599. // if int64(l1Tx.FromIdx) > r.State.CurrentIdx {
  600. // panic("l1Tx.FromIdx > r.State.CurrentIdx")
  601. // }
  602. // if int(l1Tx.TokenID)+1 > len(r.State.TokenList) {
  603. // panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  604. // }
  605. // queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  606. // r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  607. // L1Tx: *l1Tx,
  608. // ToForgeL1TxsNum: r.State.LastToForgeL1TxsNum,
  609. // Position: len(queue.L1TxQueue) - 1,
  610. // })
  611. // }
  612. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  613. 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) {
  614. log.Error("TODO")
  615. return nil, errTODO
  616. }
  617. // RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
  618. func (c *Client) RollupL1UserTxERC20ETH(
  619. fromBJJ *babyjub.PublicKey,
  620. fromIdx int64,
  621. loadAmount *big.Int,
  622. amount *big.Int,
  623. tokenID uint32,
  624. toIdx int64,
  625. ) (tx *types.Transaction, err error) {
  626. c.rw.Lock()
  627. defer c.rw.Unlock()
  628. cpy := c.nextBlock().copy()
  629. defer func() { c.revertIfErr(err, cpy) }()
  630. _, err = common.NewFloat16(amount)
  631. if err != nil {
  632. return nil, err
  633. }
  634. _, err = common.NewFloat16(loadAmount)
  635. if err != nil {
  636. return nil, err
  637. }
  638. nextBlock := c.nextBlock()
  639. r := nextBlock.Rollup
  640. queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  641. if len(queue.L1TxQueue) >= common.RollupConstMaxL1UserTx {
  642. r.State.LastToForgeL1TxsNum++
  643. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  644. queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  645. }
  646. if fromIdx > r.State.CurrentIdx {
  647. panic("l1Tx.FromIdx > r.State.CurrentIdx")
  648. }
  649. if int(tokenID)+1 > len(r.State.TokenList) {
  650. panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  651. }
  652. toForgeL1TxsNum := r.State.LastToForgeL1TxsNum
  653. l1Tx, err := common.NewL1Tx(&common.L1Tx{
  654. FromIdx: common.Idx(fromIdx),
  655. FromEthAddr: *c.addr,
  656. FromBJJ: fromBJJ,
  657. Amount: amount,
  658. LoadAmount: loadAmount,
  659. TokenID: common.TokenID(tokenID),
  660. ToIdx: common.Idx(toIdx),
  661. ToForgeL1TxsNum: &toForgeL1TxsNum,
  662. Position: len(queue.L1TxQueue),
  663. UserOrigin: true,
  664. })
  665. if err != nil {
  666. return nil, err
  667. }
  668. queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  669. r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  670. L1UserTx: *l1Tx,
  671. })
  672. return r.addTransaction(newTransaction("l1UserTxERC20ETH", l1Tx)), nil
  673. }
  674. // RollupL1UserTxERC777 is the interface to call the smart contract function
  675. // func (c *Client) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  676. // log.Error("TODO")
  677. // return nil, errTODO
  678. // }
  679. // RollupRegisterTokensCount is the interface to call the smart contract function
  680. func (c *Client) RollupRegisterTokensCount() (*big.Int, error) {
  681. log.Error("TODO")
  682. return nil, errTODO
  683. }
  684. // RollupLastForgedBatch is the interface to call the smart contract function
  685. func (c *Client) RollupLastForgedBatch() (int64, error) {
  686. c.rw.RLock()
  687. defer c.rw.RUnlock()
  688. currentBlock := c.currentBlock()
  689. e := currentBlock.Rollup
  690. return int64(len(e.State.ExitRoots)) - 1, nil
  691. }
  692. // RollupWithdrawCircuit is the interface to call the smart contract function
  693. 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) {
  694. log.Error("TODO")
  695. return nil, errTODO
  696. }
  697. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  698. 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) {
  699. c.rw.Lock()
  700. defer c.rw.Unlock()
  701. cpy := c.nextBlock().copy()
  702. defer func() { c.revertIfErr(err, cpy) }()
  703. nextBlock := c.nextBlock()
  704. r := nextBlock.Rollup
  705. if int(numExitRoot) >= len(r.State.ExitRoots) {
  706. return nil, fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)")
  707. }
  708. if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok {
  709. return nil, fmt.Errorf("exit already withdrawn")
  710. }
  711. r.State.ExitNullifierMap[numExitRoot][idx] = true
  712. type data struct {
  713. BabyPubKey *babyjub.PublicKey
  714. TokenID uint32
  715. NumExitRoot int64
  716. Idx int64
  717. Amount *big.Int
  718. Siblings []*big.Int
  719. InstantWithdraw bool
  720. }
  721. tx = r.addTransaction(newTransaction("withdrawMerkleProof", data{
  722. BabyPubKey: babyPubKey,
  723. TokenID: tokenID,
  724. NumExitRoot: numExitRoot,
  725. Idx: idx,
  726. Amount: amount,
  727. Siblings: siblings,
  728. InstantWithdraw: instantWithdraw,
  729. }))
  730. r.Events.Withdraw = append(r.Events.Withdraw, eth.RollupEventWithdraw{
  731. Idx: uint64(idx),
  732. NumExitRoot: uint64(numExitRoot),
  733. InstantWithdraw: instantWithdraw,
  734. TxHash: tx.Hash(),
  735. })
  736. if !instantWithdraw {
  737. w := nextBlock.WDelayer
  738. w.deposit(tx.Hash(), *c.addr, r.State.TokenList[int(tokenID)], amount)
  739. }
  740. return tx, nil
  741. }
  742. type transactionData struct {
  743. Name string
  744. Value interface{}
  745. }
  746. func newTransaction(name string, value interface{}) *types.Transaction {
  747. data, err := json.Marshal(transactionData{name, value})
  748. if err != nil {
  749. panic(err)
  750. }
  751. return types.NewTransaction(0, ethCommon.Address{}, nil, 0, nil,
  752. data)
  753. }
  754. // RollupForgeBatch is the interface to call the smart contract function
  755. func (c *Client) RollupForgeBatch(args *eth.RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  756. c.rw.Lock()
  757. defer c.rw.Unlock()
  758. cpy := c.nextBlock().copy()
  759. defer func() { c.revertIfErr(err, cpy) }()
  760. if c.addr == nil {
  761. return nil, eth.ErrAccountNil
  762. }
  763. a := c.nextBlock().Auction
  764. ok, err := a.canForge(*c.addr, a.Eth.BlockNum)
  765. if err != nil {
  766. return nil, err
  767. }
  768. if !ok {
  769. return nil, fmt.Errorf("incorrect slot")
  770. }
  771. // TODO: Verify proof
  772. // Auction
  773. err = a.forge(*c.addr)
  774. if err != nil {
  775. return nil, err
  776. }
  777. // TODO: If successful, store the tx in a successful array.
  778. // TODO: If failed, store the tx in a failed array.
  779. // TODO: Add method to move the tx to another block, reapply it there, and possibly go from successful to failed.
  780. return c.addBatch(args)
  781. }
  782. // CtlAddBatch adds forged batch to the Rollup, without checking any ZKProof
  783. func (c *Client) CtlAddBatch(args *eth.RollupForgeBatchArgs) {
  784. c.rw.Lock()
  785. defer c.rw.Unlock()
  786. if _, err := c.addBatch(args); err != nil {
  787. panic(err)
  788. }
  789. }
  790. func (c *Client) addBatch(args *eth.RollupForgeBatchArgs) (*types.Transaction, error) {
  791. nextBlock := c.nextBlock()
  792. r := nextBlock.Rollup
  793. r.State.StateRoot = args.NewStRoot
  794. if args.NewLastIdx < r.State.CurrentIdx {
  795. return nil, fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx")
  796. }
  797. r.State.CurrentIdx = args.NewLastIdx
  798. r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)
  799. r.State.ExitRoots = append(r.State.ExitRoots, args.NewExitRoot)
  800. if args.L1Batch {
  801. r.State.CurrentToForgeL1TxsNum++
  802. if r.State.CurrentToForgeL1TxsNum == r.State.LastToForgeL1TxsNum {
  803. r.State.LastToForgeL1TxsNum++
  804. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  805. }
  806. }
  807. ethTx := r.addTransaction(newTransaction("forgebatch", args))
  808. c.forgeBatchArgsPending[ethTx.Hash()] = &batch{*args, *c.addr}
  809. r.Events.ForgeBatch = append(r.Events.ForgeBatch, eth.RollupEventForgeBatch{
  810. BatchNum: int64(len(r.State.ExitRoots)) - 1,
  811. EthTxHash: ethTx.Hash(),
  812. })
  813. return ethTx, nil
  814. }
  815. // RollupAddTokenSimple is a wrapper around RollupAddToken that automatically
  816. // sets `deadlie`.
  817. func (c *Client) RollupAddTokenSimple(tokenAddress ethCommon.Address, feeAddToken *big.Int) (tx *types.Transaction, err error) {
  818. return c.RollupAddToken(tokenAddress, feeAddToken, big.NewInt(9999)) //nolint:gomnd
  819. }
  820. // RollupAddToken is the interface to call the smart contract function
  821. func (c *Client) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int,
  822. deadline *big.Int) (tx *types.Transaction, err error) {
  823. c.rw.Lock()
  824. defer c.rw.Unlock()
  825. cpy := c.nextBlock().copy()
  826. defer func() { c.revertIfErr(err, cpy) }()
  827. if c.addr == nil {
  828. return nil, eth.ErrAccountNil
  829. }
  830. nextBlock := c.nextBlock()
  831. r := nextBlock.Rollup
  832. if _, ok := r.State.TokenMap[tokenAddress]; ok {
  833. return nil, fmt.Errorf("Token %v already registered", tokenAddress)
  834. }
  835. if feeAddToken.Cmp(r.Vars.FeeAddToken) != 0 {
  836. return nil, fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken)
  837. }
  838. r.State.TokenMap[tokenAddress] = true
  839. r.State.TokenList = append(r.State.TokenList, tokenAddress)
  840. r.Events.AddToken = append(r.Events.AddToken, eth.RollupEventAddToken{TokenAddress: tokenAddress,
  841. TokenID: uint32(len(r.State.TokenList) - 1)})
  842. return r.addTransaction(newTransaction("addtoken", tokenAddress)), nil
  843. }
  844. // RollupGetCurrentTokens is the interface to call the smart contract function
  845. func (c *Client) RollupGetCurrentTokens() (*big.Int, error) {
  846. c.rw.RLock()
  847. defer c.rw.RUnlock()
  848. log.Error("TODO")
  849. return nil, errTODO
  850. }
  851. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  852. func (c *Client) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (tx *types.Transaction, err error) {
  853. c.rw.Lock()
  854. defer c.rw.Unlock()
  855. cpy := c.nextBlock().copy()
  856. defer func() { c.revertIfErr(err, cpy) }()
  857. if c.addr == nil {
  858. return nil, eth.ErrAccountNil
  859. }
  860. nextBlock := c.nextBlock()
  861. r := nextBlock.Rollup
  862. r.Vars.ForgeL1L2BatchTimeout = newForgeL1Timeout
  863. r.Events.UpdateForgeL1L2BatchTimeout = append(r.Events.UpdateForgeL1L2BatchTimeout,
  864. eth.RollupEventUpdateForgeL1L2BatchTimeout{NewForgeL1L2BatchTimeout: newForgeL1Timeout})
  865. return r.addTransaction(newTransaction("updateForgeL1L2BatchTimeout", newForgeL1Timeout)), nil
  866. }
  867. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  868. func (c *Client) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  869. c.rw.Lock()
  870. defer c.rw.Unlock()
  871. cpy := c.nextBlock().copy()
  872. defer func() { c.revertIfErr(err, cpy) }()
  873. if c.addr == nil {
  874. return nil, eth.ErrAccountNil
  875. }
  876. log.Error("TODO")
  877. return nil, errTODO
  878. }
  879. // RollupUpdateTokensHEZ is the interface to call the smart contract function
  880. // func (c *Client) RollupUpdateTokensHEZ(newTokenHEZ ethCommon.Address) (tx *types.Transaction, err error) {
  881. // c.rw.Lock()
  882. // defer c.rw.Unlock()
  883. // cpy := c.nextBlock().copy()
  884. // defer func() { c.revertIfErr(err, cpy) }()
  885. //
  886. // log.Error("TODO")
  887. // return nil, errTODO
  888. // }
  889. // RollupUpdateGovernance is the interface to call the smart contract function
  890. // func (c *Client) RollupUpdateGovernance() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
  891. // return nil, errTODO
  892. // }
  893. // RollupConstants returns the Constants of the Rollup Smart Contract
  894. func (c *Client) RollupConstants() (*common.RollupConstants, error) {
  895. c.rw.RLock()
  896. defer c.rw.RUnlock()
  897. return c.rollupConstants, nil
  898. }
  899. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  900. func (c *Client) RollupEventsByBlock(blockNum int64) (*eth.RollupEvents, *ethCommon.Hash, error) {
  901. c.rw.RLock()
  902. defer c.rw.RUnlock()
  903. block, ok := c.blocks[blockNum]
  904. if !ok {
  905. return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
  906. }
  907. return &block.Rollup.Events, &block.Eth.Hash, nil
  908. }
  909. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
  910. func (c *Client) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*eth.RollupForgeBatchArgs, *ethCommon.Address, error) {
  911. c.rw.RLock()
  912. defer c.rw.RUnlock()
  913. batch, ok := c.forgeBatchArgs[ethTxHash]
  914. if !ok {
  915. return nil, nil, fmt.Errorf("transaction not found")
  916. }
  917. return &batch.ForgeBatchArgs, &batch.Sender, nil
  918. }
  919. //
  920. // Auction
  921. //
  922. // AuctionSetSlotDeadline is the interface to call the smart contract function
  923. func (c *Client) AuctionSetSlotDeadline(newDeadline uint8) (tx *types.Transaction, err error) {
  924. c.rw.Lock()
  925. defer c.rw.Unlock()
  926. cpy := c.nextBlock().copy()
  927. defer func() { c.revertIfErr(err, cpy) }()
  928. if c.addr == nil {
  929. return nil, eth.ErrAccountNil
  930. }
  931. log.Error("TODO")
  932. return nil, errTODO
  933. }
  934. // AuctionGetSlotDeadline is the interface to call the smart contract function
  935. func (c *Client) AuctionGetSlotDeadline() (uint8, error) {
  936. c.rw.RLock()
  937. defer c.rw.RUnlock()
  938. log.Error("TODO")
  939. return 0, errTODO
  940. }
  941. // AuctionSetOpenAuctionSlots is the interface to call the smart contract function
  942. func (c *Client) AuctionSetOpenAuctionSlots(newOpenAuctionSlots uint16) (tx *types.Transaction, err error) {
  943. c.rw.Lock()
  944. defer c.rw.Unlock()
  945. cpy := c.nextBlock().copy()
  946. defer func() { c.revertIfErr(err, cpy) }()
  947. if c.addr == nil {
  948. return nil, eth.ErrAccountNil
  949. }
  950. nextBlock := c.nextBlock()
  951. a := nextBlock.Auction
  952. a.Vars.OpenAuctionSlots = newOpenAuctionSlots
  953. a.Events.NewOpenAuctionSlots = append(a.Events.NewOpenAuctionSlots,
  954. eth.AuctionEventNewOpenAuctionSlots{NewOpenAuctionSlots: newOpenAuctionSlots})
  955. return a.addTransaction(newTransaction("setOpenAuctionSlots", newOpenAuctionSlots)), nil
  956. }
  957. // AuctionGetOpenAuctionSlots is the interface to call the smart contract function
  958. func (c *Client) AuctionGetOpenAuctionSlots() (uint16, error) {
  959. c.rw.RLock()
  960. defer c.rw.RUnlock()
  961. log.Error("TODO")
  962. return 0, errTODO
  963. }
  964. // AuctionSetClosedAuctionSlots is the interface to call the smart contract function
  965. func (c *Client) AuctionSetClosedAuctionSlots(newClosedAuctionSlots uint16) (tx *types.Transaction, err error) {
  966. c.rw.Lock()
  967. defer c.rw.Unlock()
  968. cpy := c.nextBlock().copy()
  969. defer func() { c.revertIfErr(err, cpy) }()
  970. if c.addr == nil {
  971. return nil, eth.ErrAccountNil
  972. }
  973. log.Error("TODO")
  974. return nil, errTODO
  975. }
  976. // AuctionGetClosedAuctionSlots is the interface to call the smart contract function
  977. func (c *Client) AuctionGetClosedAuctionSlots() (uint16, error) {
  978. c.rw.RLock()
  979. defer c.rw.RUnlock()
  980. log.Error("TODO")
  981. return 0, errTODO
  982. }
  983. // AuctionSetOutbidding is the interface to call the smart contract function
  984. func (c *Client) AuctionSetOutbidding(newOutbidding uint16) (tx *types.Transaction, err error) {
  985. c.rw.Lock()
  986. defer c.rw.Unlock()
  987. cpy := c.nextBlock().copy()
  988. defer func() { c.revertIfErr(err, cpy) }()
  989. if c.addr == nil {
  990. return nil, eth.ErrAccountNil
  991. }
  992. log.Error("TODO")
  993. return nil, errTODO
  994. }
  995. // AuctionGetOutbidding is the interface to call the smart contract function
  996. func (c *Client) AuctionGetOutbidding() (uint16, error) {
  997. c.rw.RLock()
  998. defer c.rw.RUnlock()
  999. log.Error("TODO")
  1000. return 0, errTODO
  1001. }
  1002. // AuctionSetAllocationRatio is the interface to call the smart contract function
  1003. func (c *Client) AuctionSetAllocationRatio(newAllocationRatio [3]uint16) (tx *types.Transaction, err error) {
  1004. c.rw.Lock()
  1005. defer c.rw.Unlock()
  1006. cpy := c.nextBlock().copy()
  1007. defer func() { c.revertIfErr(err, cpy) }()
  1008. if c.addr == nil {
  1009. return nil, eth.ErrAccountNil
  1010. }
  1011. log.Error("TODO")
  1012. return nil, errTODO
  1013. }
  1014. // AuctionGetAllocationRatio is the interface to call the smart contract function
  1015. func (c *Client) AuctionGetAllocationRatio() ([3]uint16, error) {
  1016. c.rw.RLock()
  1017. defer c.rw.RUnlock()
  1018. log.Error("TODO")
  1019. return [3]uint16{}, errTODO
  1020. }
  1021. // AuctionSetDonationAddress is the interface to call the smart contract function
  1022. func (c *Client) AuctionSetDonationAddress(newDonationAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1023. c.rw.Lock()
  1024. defer c.rw.Unlock()
  1025. cpy := c.nextBlock().copy()
  1026. defer func() { c.revertIfErr(err, cpy) }()
  1027. if c.addr == nil {
  1028. return nil, eth.ErrAccountNil
  1029. }
  1030. log.Error("TODO")
  1031. return nil, errTODO
  1032. }
  1033. // AuctionGetDonationAddress is the interface to call the smart contract function
  1034. func (c *Client) AuctionGetDonationAddress() (*ethCommon.Address, error) {
  1035. c.rw.RLock()
  1036. defer c.rw.RUnlock()
  1037. log.Error("TODO")
  1038. return nil, errTODO
  1039. }
  1040. // AuctionSetBootCoordinator is the interface to call the smart contract function
  1041. func (c *Client) AuctionSetBootCoordinator(newBootCoordinator ethCommon.Address) (tx *types.Transaction, err error) {
  1042. c.rw.Lock()
  1043. defer c.rw.Unlock()
  1044. cpy := c.nextBlock().copy()
  1045. defer func() { c.revertIfErr(err, cpy) }()
  1046. if c.addr == nil {
  1047. return nil, eth.ErrAccountNil
  1048. }
  1049. log.Error("TODO")
  1050. return nil, errTODO
  1051. }
  1052. // AuctionGetBootCoordinator is the interface to call the smart contract function
  1053. func (c *Client) AuctionGetBootCoordinator() (*ethCommon.Address, error) {
  1054. c.rw.RLock()
  1055. defer c.rw.RUnlock()
  1056. currentBlock := c.currentBlock()
  1057. a := currentBlock.Auction
  1058. return &a.Vars.BootCoordinator, nil
  1059. }
  1060. // AuctionChangeDefaultSlotSetBid is the interface to call the smart contract function
  1061. func (c *Client) AuctionChangeDefaultSlotSetBid(slotSet int64, newInitialMinBid *big.Int) (tx *types.Transaction, err error) {
  1062. c.rw.Lock()
  1063. defer c.rw.Unlock()
  1064. cpy := c.nextBlock().copy()
  1065. defer func() { c.revertIfErr(err, cpy) }()
  1066. if c.addr == nil {
  1067. return nil, eth.ErrAccountNil
  1068. }
  1069. log.Error("TODO")
  1070. return nil, errTODO
  1071. }
  1072. // AuctionSetCoordinator is the interface to call the smart contract function
  1073. func (c *Client) AuctionSetCoordinator(forger ethCommon.Address, URL string) (tx *types.Transaction, err error) {
  1074. c.rw.Lock()
  1075. defer c.rw.Unlock()
  1076. cpy := c.nextBlock().copy()
  1077. defer func() { c.revertIfErr(err, cpy) }()
  1078. if c.addr == nil {
  1079. return nil, eth.ErrAccountNil
  1080. }
  1081. nextBlock := c.nextBlock()
  1082. a := nextBlock.Auction
  1083. a.State.Coordinators[*c.addr] = &eth.Coordinator{
  1084. Forger: forger,
  1085. URL: URL,
  1086. }
  1087. a.Events.SetCoordinator = append(a.Events.SetCoordinator,
  1088. eth.AuctionEventSetCoordinator{
  1089. BidderAddress: *c.addr,
  1090. ForgerAddress: forger,
  1091. CoordinatorURL: URL,
  1092. })
  1093. type data struct {
  1094. BidderAddress ethCommon.Address
  1095. ForgerAddress ethCommon.Address
  1096. URL string
  1097. }
  1098. return a.addTransaction(newTransaction("registercoordinator", data{*c.addr, forger, URL})), nil
  1099. }
  1100. // AuctionIsRegisteredCoordinator is the interface to call the smart contract function
  1101. func (c *Client) AuctionIsRegisteredCoordinator(forgerAddress ethCommon.Address) (bool, error) {
  1102. c.rw.RLock()
  1103. defer c.rw.RUnlock()
  1104. log.Error("TODO")
  1105. return false, errTODO
  1106. }
  1107. // AuctionUpdateCoordinatorInfo is the interface to call the smart contract function
  1108. func (c *Client) AuctionUpdateCoordinatorInfo(forgerAddress ethCommon.Address, newWithdrawAddress ethCommon.Address, newURL string) (tx *types.Transaction, err error) {
  1109. c.rw.Lock()
  1110. defer c.rw.Unlock()
  1111. cpy := c.nextBlock().copy()
  1112. defer func() { c.revertIfErr(err, cpy) }()
  1113. if c.addr == nil {
  1114. return nil, eth.ErrAccountNil
  1115. }
  1116. log.Error("TODO")
  1117. return nil, errTODO
  1118. }
  1119. // AuctionGetSlotNumber is the interface to call the smart contract function
  1120. func (c *Client) AuctionGetSlotNumber(blockNum int64) (int64, error) {
  1121. c.rw.RLock()
  1122. defer c.rw.RUnlock()
  1123. currentBlock := c.currentBlock()
  1124. a := currentBlock.Auction
  1125. return a.getSlotNumber(blockNum), nil
  1126. }
  1127. // AuctionGetCurrentSlotNumber is the interface to call the smart contract function
  1128. func (c *Client) AuctionGetCurrentSlotNumber() (int64, error) {
  1129. c.rw.RLock()
  1130. defer c.rw.RUnlock()
  1131. log.Error("TODO")
  1132. return 0, errTODO
  1133. }
  1134. // AuctionGetMinBidBySlot is the interface to call the smart contract function
  1135. func (c *Client) AuctionGetMinBidBySlot(slot int64) (*big.Int, error) {
  1136. c.rw.RLock()
  1137. defer c.rw.RUnlock()
  1138. log.Error("TODO")
  1139. return nil, errTODO
  1140. }
  1141. // AuctionGetDefaultSlotSetBid is the interface to call the smart contract function
  1142. func (c *Client) AuctionGetDefaultSlotSetBid(slotSet uint8) (*big.Int, error) {
  1143. c.rw.RLock()
  1144. defer c.rw.RUnlock()
  1145. log.Error("TODO")
  1146. return nil, errTODO
  1147. }
  1148. // AuctionGetSlotSet is the interface to call the smart contract function
  1149. func (c *Client) AuctionGetSlotSet(slot int64) (*big.Int, error) {
  1150. c.rw.RLock()
  1151. defer c.rw.RUnlock()
  1152. log.Error("TODO")
  1153. return nil, errTODO
  1154. }
  1155. // AuctionTokensReceived is the interface to call the smart contract function
  1156. // func (c *Client) AuctionTokensReceived(operator, from, to ethCommon.Address, amount *big.Int, userData, operatorData []byte) error {
  1157. // return errTODO
  1158. // }
  1159. // AuctionBidSimple is a wrapper around AuctionBid that automatically sets `amount` and `deadline`.
  1160. func (c *Client) AuctionBidSimple(slot int64, bidAmount *big.Int) (tx *types.Transaction, err error) {
  1161. return c.AuctionBid(bidAmount, slot, bidAmount, big.NewInt(99999)) //nolint:gomnd
  1162. }
  1163. // AuctionBid is the interface to call the smart contract function. This
  1164. // implementation behaves as if any address has infinite tokens.
  1165. func (c *Client) AuctionBid(amount *big.Int, slot int64, bidAmount *big.Int,
  1166. deadline *big.Int) (tx *types.Transaction, err error) {
  1167. c.rw.Lock()
  1168. defer c.rw.Unlock()
  1169. cpy := c.nextBlock().copy()
  1170. defer func() { func() { c.revertIfErr(err, cpy) }() }()
  1171. if c.addr == nil {
  1172. return nil, eth.ErrAccountNil
  1173. }
  1174. nextBlock := c.nextBlock()
  1175. a := nextBlock.Auction
  1176. if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
  1177. return nil, errBidClosed
  1178. }
  1179. if slot >= a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots)+int64(a.Vars.OpenAuctionSlots) {
  1180. return nil, errBidNotOpen
  1181. }
  1182. minBid, err := a.getMinBidBySlot(slot)
  1183. if err != nil {
  1184. return nil, err
  1185. }
  1186. if bidAmount.Cmp(minBid) == -1 {
  1187. return nil, errBidBelowMin
  1188. }
  1189. if _, ok := a.State.Coordinators[*c.addr]; !ok {
  1190. return nil, errCoordNotReg
  1191. }
  1192. slotState, ok := a.State.Slots[slot]
  1193. if !ok {
  1194. slotState = eth.NewSlotState()
  1195. a.State.Slots[slot] = slotState
  1196. }
  1197. slotState.Bidder = *c.addr
  1198. slotState.BidAmount = bidAmount
  1199. a.Events.NewBid = append(a.Events.NewBid,
  1200. eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, Bidder: *c.addr})
  1201. type data struct {
  1202. Slot int64
  1203. BidAmount *big.Int
  1204. Bidder ethCommon.Address
  1205. }
  1206. return a.addTransaction(newTransaction("bid", data{slot, bidAmount, *c.addr})), nil
  1207. }
  1208. // AuctionMultiBid is the interface to call the smart contract function. This
  1209. // implementation behaves as if any address has infinite tokens.
  1210. func (c *Client) AuctionMultiBid(amount *big.Int, startingSlot int64, endingSlot int64, slotSet [6]bool,
  1211. maxBid, closedMinBid, deadline *big.Int) (tx *types.Transaction, err error) {
  1212. c.rw.Lock()
  1213. defer c.rw.Unlock()
  1214. cpy := c.nextBlock().copy()
  1215. defer func() { c.revertIfErr(err, cpy) }()
  1216. if c.addr == nil {
  1217. return nil, eth.ErrAccountNil
  1218. }
  1219. log.Error("TODO")
  1220. return nil, errTODO
  1221. }
  1222. // AuctionCanForge is the interface to call the smart contract function
  1223. func (c *Client) AuctionCanForge(forger ethCommon.Address, blockNum int64) (bool, error) {
  1224. c.rw.RLock()
  1225. defer c.rw.RUnlock()
  1226. currentBlock := c.currentBlock()
  1227. a := currentBlock.Auction
  1228. return a.canForge(forger, blockNum)
  1229. }
  1230. // AuctionForge is the interface to call the smart contract function
  1231. func (c *Client) AuctionForge(forger ethCommon.Address) (tx *types.Transaction, err error) {
  1232. c.rw.Lock()
  1233. defer c.rw.Unlock()
  1234. cpy := c.nextBlock().copy()
  1235. defer func() { c.revertIfErr(err, cpy) }()
  1236. if c.addr == nil {
  1237. return nil, eth.ErrAccountNil
  1238. }
  1239. log.Error("TODO")
  1240. return nil, errTODO
  1241. }
  1242. // AuctionClaimHEZ is the interface to call the smart contract function
  1243. func (c *Client) AuctionClaimHEZ() (tx *types.Transaction, err error) {
  1244. c.rw.Lock()
  1245. defer c.rw.Unlock()
  1246. cpy := c.nextBlock().copy()
  1247. defer func() { c.revertIfErr(err, cpy) }()
  1248. if c.addr == nil {
  1249. return nil, eth.ErrAccountNil
  1250. }
  1251. log.Error("TODO")
  1252. return nil, errTODO
  1253. }
  1254. // AuctionGetClaimableHEZ is the interface to call the smart contract function
  1255. func (c *Client) AuctionGetClaimableHEZ(bidder ethCommon.Address) (*big.Int, error) {
  1256. c.rw.RLock()
  1257. defer c.rw.RUnlock()
  1258. log.Error("TODO")
  1259. return nil, errTODO
  1260. }
  1261. // AuctionConstants returns the Constants of the Auction Smart Contract
  1262. func (c *Client) AuctionConstants() (*common.AuctionConstants, error) {
  1263. c.rw.RLock()
  1264. defer c.rw.RUnlock()
  1265. return c.auctionConstants, nil
  1266. }
  1267. // AuctionEventsByBlock returns the events in a block that happened in the Auction Smart Contract
  1268. func (c *Client) AuctionEventsByBlock(blockNum int64) (*eth.AuctionEvents, *ethCommon.Hash, error) {
  1269. c.rw.RLock()
  1270. defer c.rw.RUnlock()
  1271. block, ok := c.blocks[blockNum]
  1272. if !ok {
  1273. return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
  1274. }
  1275. return &block.Auction.Events, &block.Eth.Hash, nil
  1276. }
  1277. //
  1278. // WDelayer
  1279. //
  1280. // WDelayerGetHermezGovernanceDAOAddress is the interface to call the smart contract function
  1281. func (c *Client) WDelayerGetHermezGovernanceDAOAddress() (*ethCommon.Address, error) {
  1282. c.rw.RLock()
  1283. defer c.rw.RUnlock()
  1284. log.Error("TODO")
  1285. return nil, errTODO
  1286. }
  1287. // WDelayerSetHermezGovernanceDAOAddress is the interface to call the smart contract function
  1288. func (c *Client) WDelayerSetHermezGovernanceDAOAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1289. c.rw.Lock()
  1290. defer c.rw.Unlock()
  1291. cpy := c.nextBlock().copy()
  1292. defer func() { c.revertIfErr(err, cpy) }()
  1293. if c.addr == nil {
  1294. return nil, eth.ErrAccountNil
  1295. }
  1296. log.Error("TODO")
  1297. return nil, errTODO
  1298. }
  1299. // WDelayerGetHermezKeeperAddress is the interface to call the smart contract function
  1300. func (c *Client) WDelayerGetHermezKeeperAddress() (*ethCommon.Address, error) {
  1301. c.rw.RLock()
  1302. defer c.rw.RUnlock()
  1303. log.Error("TODO")
  1304. return nil, errTODO
  1305. }
  1306. // WDelayerSetHermezKeeperAddress is the interface to call the smart contract function
  1307. func (c *Client) WDelayerSetHermezKeeperAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1308. c.rw.Lock()
  1309. defer c.rw.Unlock()
  1310. cpy := c.nextBlock().copy()
  1311. defer func() { c.revertIfErr(err, cpy) }()
  1312. if c.addr == nil {
  1313. return nil, eth.ErrAccountNil
  1314. }
  1315. log.Error("TODO")
  1316. return nil, errTODO
  1317. }
  1318. // WDelayerGetWhiteHackGroupAddress is the interface to call the smart contract function
  1319. func (c *Client) WDelayerGetWhiteHackGroupAddress() (*ethCommon.Address, error) {
  1320. c.rw.RLock()
  1321. defer c.rw.RUnlock()
  1322. log.Error("TODO")
  1323. return nil, errTODO
  1324. }
  1325. // WDelayerSetWhiteHackGroupAddress is the interface to call the smart contract function
  1326. func (c *Client) WDelayerSetWhiteHackGroupAddress(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1327. c.rw.Lock()
  1328. defer c.rw.Unlock()
  1329. cpy := c.nextBlock().copy()
  1330. defer func() { c.revertIfErr(err, cpy) }()
  1331. if c.addr == nil {
  1332. return nil, eth.ErrAccountNil
  1333. }
  1334. log.Error("TODO")
  1335. return nil, errTODO
  1336. }
  1337. // WDelayerIsEmergencyMode is the interface to call the smart contract function
  1338. func (c *Client) WDelayerIsEmergencyMode() (bool, error) {
  1339. c.rw.RLock()
  1340. defer c.rw.RUnlock()
  1341. log.Error("TODO")
  1342. return false, errTODO
  1343. }
  1344. // WDelayerGetWithdrawalDelay is the interface to call the smart contract function
  1345. func (c *Client) WDelayerGetWithdrawalDelay() (*big.Int, error) {
  1346. c.rw.RLock()
  1347. defer c.rw.RUnlock()
  1348. log.Error("TODO")
  1349. return nil, errTODO
  1350. }
  1351. // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function
  1352. func (c *Client) WDelayerGetEmergencyModeStartingTime() (*big.Int, error) {
  1353. c.rw.RLock()
  1354. defer c.rw.RUnlock()
  1355. log.Error("TODO")
  1356. return nil, errTODO
  1357. }
  1358. // WDelayerEnableEmergencyMode is the interface to call the smart contract function
  1359. func (c *Client) WDelayerEnableEmergencyMode() (tx *types.Transaction, err error) {
  1360. c.rw.Lock()
  1361. defer c.rw.Unlock()
  1362. cpy := c.nextBlock().copy()
  1363. defer func() { c.revertIfErr(err, cpy) }()
  1364. if c.addr == nil {
  1365. return nil, eth.ErrAccountNil
  1366. }
  1367. log.Error("TODO")
  1368. return nil, errTODO
  1369. }
  1370. // WDelayerChangeWithdrawalDelay is the interface to call the smart contract function
  1371. func (c *Client) WDelayerChangeWithdrawalDelay(newWithdrawalDelay uint64) (tx *types.Transaction, err error) {
  1372. c.rw.Lock()
  1373. defer c.rw.Unlock()
  1374. cpy := c.nextBlock().copy()
  1375. defer func() { c.revertIfErr(err, cpy) }()
  1376. if c.addr == nil {
  1377. return nil, eth.ErrAccountNil
  1378. }
  1379. nextBlock := c.nextBlock()
  1380. w := nextBlock.WDelayer
  1381. w.Vars.WithdrawalDelay = newWithdrawalDelay
  1382. w.Events.NewWithdrawalDelay = append(w.Events.NewWithdrawalDelay,
  1383. eth.WDelayerEventNewWithdrawalDelay{WithdrawalDelay: newWithdrawalDelay})
  1384. return w.addTransaction(newTransaction("changeWithdrawalDelay", newWithdrawalDelay)), nil
  1385. }
  1386. // WDelayerDepositInfo is the interface to call the smart contract function
  1387. func (c *Client) WDelayerDepositInfo(owner, token ethCommon.Address) (eth.DepositState, error) {
  1388. c.rw.RLock()
  1389. defer c.rw.RUnlock()
  1390. log.Error("TODO")
  1391. return eth.DepositState{}, errTODO
  1392. }
  1393. // WDelayerDeposit is the interface to call the smart contract function
  1394. func (c *Client) WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1395. c.rw.Lock()
  1396. defer c.rw.Unlock()
  1397. cpy := c.nextBlock().copy()
  1398. defer func() { c.revertIfErr(err, cpy) }()
  1399. if c.addr == nil {
  1400. return nil, eth.ErrAccountNil
  1401. }
  1402. log.Error("TODO")
  1403. return nil, errTODO
  1404. }
  1405. // WDelayerWithdrawal is the interface to call the smart contract function
  1406. func (c *Client) WDelayerWithdrawal(owner, token ethCommon.Address) (tx *types.Transaction, err error) {
  1407. c.rw.Lock()
  1408. defer c.rw.Unlock()
  1409. cpy := c.nextBlock().copy()
  1410. defer func() { c.revertIfErr(err, cpy) }()
  1411. if c.addr == nil {
  1412. return nil, eth.ErrAccountNil
  1413. }
  1414. log.Error("TODO")
  1415. return nil, errTODO
  1416. }
  1417. // WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function
  1418. func (c *Client) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1419. c.rw.Lock()
  1420. defer c.rw.Unlock()
  1421. cpy := c.nextBlock().copy()
  1422. defer func() { c.revertIfErr(err, cpy) }()
  1423. if c.addr == nil {
  1424. return nil, eth.ErrAccountNil
  1425. }
  1426. log.Error("TODO")
  1427. return nil, errTODO
  1428. }
  1429. // WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract
  1430. func (c *Client) WDelayerEventsByBlock(blockNum int64) (*eth.WDelayerEvents, *ethCommon.Hash, error) {
  1431. c.rw.RLock()
  1432. defer c.rw.RUnlock()
  1433. block, ok := c.blocks[blockNum]
  1434. if !ok {
  1435. return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum)
  1436. }
  1437. return &block.WDelayer.Events, &block.Eth.Hash, nil
  1438. }
  1439. // WDelayerConstants returns the Constants of the WDelayer Contract
  1440. func (c *Client) WDelayerConstants() (*common.WDelayerConstants, error) {
  1441. c.rw.RLock()
  1442. defer c.rw.RUnlock()
  1443. return c.wDelayerConstants, nil
  1444. }