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.

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