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.

1717 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. HermezGovernanceAddress: governanceAddress,
  262. HermezAuctionContract: ethCommon.HexToAddress("0x8E442975805fb1908f43050c9C1A522cB0e28D7b"),
  263. WithdrawDelayerContract: ethCommon.HexToAddress("0x5CB7979cBdbf65719BEE92e4D15b7b7Ed3D79114"),
  264. }
  265. rollupVariables := &common.RollupVariables{
  266. FeeAddToken: big.NewInt(11),
  267. ForgeL1L2BatchTimeout: 9,
  268. WithdrawalDelay: 80,
  269. }
  270. auctionConstants := &common.AuctionConstants{
  271. BlocksPerSlot: 40,
  272. InitialMinimalBidding: initialMinimalBidding,
  273. GenesisBlockNum: 1,
  274. GovernanceAddress: governanceAddress,
  275. TokenHEZ: tokenHEZ,
  276. HermezRollup: ethCommon.HexToAddress("0x474B6e29852257491cf283EfB1A9C61eBFe48369"),
  277. }
  278. auctionVariables := &common.AuctionVariables{
  279. DonationAddress: ethCommon.HexToAddress("0x61Ed87CF0A1496b49A420DA6D84B58196b98f2e7"),
  280. BootCoordinator: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  281. BootCoordinatorURL: "https://boot.coordinator.com",
  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. HermezGovernanceAddress: ethCommon.HexToAddress("0xcfD0d163AE6432a72682323E2C3A5a69e6B37D12"),
  298. EmergencyCouncilAddress: ethCommon.HexToAddress("0x2730700932a4FDB97B9268A3Ca29f97Ea5fd7EA0"),
  299. WithdrawalDelay: 60,
  300. EmergencyModeStartingTime: 0,
  301. EmergencyMode: false,
  302. }
  303. return &ClientSetup{
  304. RollupConstants: rollupConstants,
  305. RollupVariables: rollupVariables,
  306. AuctionConstants: auctionConstants,
  307. AuctionVariables: auctionVariables,
  308. WDelayerConstants: wDelayerConstants,
  309. WDelayerVariables: wDelayerVariables,
  310. }
  311. }
  312. // Timer is an interface to simulate a source of time, useful to advance time
  313. // virtually.
  314. type Timer interface {
  315. Time() int64
  316. }
  317. // type forgeBatchArgs struct {
  318. // ethTx *types.Transaction
  319. // blockNum int64
  320. // blockHash ethCommon.Hash
  321. // }
  322. type batch struct {
  323. ForgeBatchArgs eth.RollupForgeBatchArgs
  324. Sender ethCommon.Address
  325. }
  326. // Client implements the eth.ClientInterface interface, allowing to manipulate the
  327. // values for testing, working with deterministic results.
  328. type Client struct {
  329. rw *sync.RWMutex
  330. log bool
  331. addr *ethCommon.Address
  332. rollupConstants *common.RollupConstants
  333. auctionConstants *common.AuctionConstants
  334. wDelayerConstants *common.WDelayerConstants
  335. blocks map[int64]*Block
  336. // state state
  337. blockNum int64 // last mined block num
  338. maxBlockNum int64 // highest block num calculated
  339. timer Timer
  340. hasher hasher
  341. forgeBatchArgsPending map[ethCommon.Hash]*batch
  342. forgeBatchArgs map[ethCommon.Hash]*batch
  343. }
  344. // NewClient returns a new test Client that implements the eth.IClient
  345. // interface, at the given initialBlockNumber.
  346. func NewClient(l bool, timer Timer, addr *ethCommon.Address, setup *ClientSetup) *Client {
  347. blocks := make(map[int64]*Block)
  348. blockNum := int64(0)
  349. hasher := hasher{}
  350. // Add ethereum genesis block
  351. mapL1TxQueue := make(map[int64]*eth.QueueStruct)
  352. mapL1TxQueue[0] = eth.NewQueueStruct()
  353. mapL1TxQueue[1] = eth.NewQueueStruct()
  354. blockCurrent := &Block{
  355. Rollup: &RollupBlock{
  356. State: eth.RollupState{
  357. StateRoot: big.NewInt(0),
  358. ExitRoots: make([]*big.Int, 1),
  359. ExitNullifierMap: make(map[int64]map[int64]bool),
  360. // TokenID = 0 is ETH. Set first entry in TokenList with 0x0 address for ETH.
  361. TokenList: []ethCommon.Address{{}},
  362. TokenMap: make(map[ethCommon.Address]bool),
  363. MapL1TxQueue: mapL1TxQueue,
  364. LastL1L2Batch: 0,
  365. CurrentToForgeL1TxsNum: 0,
  366. LastToForgeL1TxsNum: 1,
  367. CurrentIdx: 0,
  368. },
  369. Vars: *setup.RollupVariables,
  370. Txs: make(map[ethCommon.Hash]*types.Transaction),
  371. Events: eth.NewRollupEvents(),
  372. Constants: setup.RollupConstants,
  373. },
  374. Auction: &AuctionBlock{
  375. State: eth.AuctionState{
  376. Slots: make(map[int64]*eth.SlotState),
  377. PendingBalances: make(map[ethCommon.Address]*big.Int),
  378. Coordinators: make(map[ethCommon.Address]*eth.Coordinator),
  379. },
  380. Vars: *setup.AuctionVariables,
  381. Txs: make(map[ethCommon.Hash]*types.Transaction),
  382. Events: eth.NewAuctionEvents(),
  383. Constants: setup.AuctionConstants,
  384. },
  385. WDelayer: &WDelayerBlock{
  386. // State: TODO
  387. Vars: *setup.WDelayerVariables,
  388. Txs: make(map[ethCommon.Hash]*types.Transaction),
  389. Events: eth.NewWDelayerEvents(),
  390. Constants: setup.WDelayerConstants,
  391. },
  392. Eth: &EthereumBlock{
  393. BlockNum: blockNum,
  394. Time: timer.Time(),
  395. Hash: hasher.Next(),
  396. ParentHash: ethCommon.Hash{},
  397. Tokens: make(map[ethCommon.Address]eth.ERC20Consts),
  398. },
  399. }
  400. blockCurrent.Rollup.Eth = blockCurrent.Eth
  401. blockCurrent.Auction.Eth = blockCurrent.Eth
  402. blocks[blockNum] = blockCurrent
  403. blockNext := blockCurrent.Next()
  404. blocks[blockNum+1] = blockNext
  405. c := Client{
  406. rw: &sync.RWMutex{},
  407. log: l,
  408. addr: addr,
  409. rollupConstants: setup.RollupConstants,
  410. auctionConstants: setup.AuctionConstants,
  411. wDelayerConstants: setup.WDelayerConstants,
  412. blocks: blocks,
  413. timer: timer,
  414. hasher: hasher,
  415. forgeBatchArgsPending: make(map[ethCommon.Hash]*batch),
  416. forgeBatchArgs: make(map[ethCommon.Hash]*batch),
  417. blockNum: blockNum,
  418. maxBlockNum: blockNum,
  419. }
  420. for i := int64(1); i < setup.AuctionConstants.GenesisBlockNum+1; i++ {
  421. c.CtlMineBlock()
  422. }
  423. return &c
  424. }
  425. //
  426. // Mock Control
  427. //
  428. func (c *Client) setNextBlock(block *Block) {
  429. c.blocks[c.blockNum+1] = block
  430. }
  431. func (c *Client) revertIfErr(err error, block *Block) {
  432. if err != nil {
  433. log.Infow("TestClient revert", "block", block.Eth.BlockNum, "err", err)
  434. c.setNextBlock(block)
  435. }
  436. }
  437. // Debugf calls log.Debugf if c.log is true
  438. func (c *Client) Debugf(template string, args ...interface{}) {
  439. if c.log {
  440. log.Debugf(template, args...)
  441. }
  442. }
  443. // Debugw calls log.Debugw if c.log is true
  444. func (c *Client) Debugw(template string, kv ...interface{}) {
  445. if c.log {
  446. log.Debugw(template, kv...)
  447. }
  448. }
  449. type hasher struct {
  450. counter uint64
  451. }
  452. // Next returns the next hash
  453. func (h *hasher) Next() ethCommon.Hash {
  454. var hash ethCommon.Hash
  455. binary.LittleEndian.PutUint64(hash[:], h.counter)
  456. h.counter++
  457. return hash
  458. }
  459. func (c *Client) nextBlock() *Block {
  460. return c.blocks[c.blockNum+1]
  461. }
  462. func (c *Client) currentBlock() *Block {
  463. return c.blocks[c.blockNum]
  464. }
  465. // CtlSetAddr sets the address of the client
  466. func (c *Client) CtlSetAddr(addr ethCommon.Address) {
  467. c.addr = &addr
  468. }
  469. // CtlMineBlock moves one block forward
  470. func (c *Client) CtlMineBlock() {
  471. c.rw.Lock()
  472. defer c.rw.Unlock()
  473. blockCurrent := c.nextBlock()
  474. c.blockNum++
  475. c.maxBlockNum = c.blockNum
  476. blockCurrent.Eth.Time = c.timer.Time()
  477. blockCurrent.Eth.Hash = c.hasher.Next()
  478. for ethTxHash, forgeBatchArgs := range c.forgeBatchArgsPending {
  479. c.forgeBatchArgs[ethTxHash] = forgeBatchArgs
  480. }
  481. c.forgeBatchArgsPending = make(map[ethCommon.Hash]*batch)
  482. blockNext := blockCurrent.Next()
  483. c.blocks[c.blockNum+1] = blockNext
  484. c.Debugw("TestClient mined block", "blockNum", c.blockNum)
  485. }
  486. // CtlRollback discards the last mined block. Use this to replace a mined
  487. // block to simulate reorgs.
  488. func (c *Client) CtlRollback() {
  489. c.rw.Lock()
  490. defer c.rw.Unlock()
  491. if c.blockNum == 0 {
  492. panic("Can't rollback at blockNum = 0")
  493. }
  494. delete(c.blocks, c.blockNum+1) // delete next block
  495. delete(c.blocks, c.blockNum) // delete current block
  496. c.blockNum--
  497. blockCurrent := c.blocks[c.blockNum]
  498. blockNext := blockCurrent.Next()
  499. c.blocks[c.blockNum+1] = blockNext
  500. }
  501. //
  502. // Ethereum
  503. //
  504. // CtlLastBlock returns the last blockNum without checks
  505. func (c *Client) CtlLastBlock() *common.Block {
  506. c.rw.RLock()
  507. defer c.rw.RUnlock()
  508. block := c.blocks[c.blockNum]
  509. return &common.Block{
  510. Num: c.blockNum,
  511. Timestamp: time.Unix(block.Eth.Time, 0),
  512. Hash: block.Eth.Hash,
  513. ParentHash: block.Eth.ParentHash,
  514. }
  515. }
  516. // CtlLastForgedBatch returns the last batchNum without checks
  517. func (c *Client) CtlLastForgedBatch() int64 {
  518. c.rw.RLock()
  519. defer c.rw.RUnlock()
  520. currentBlock := c.currentBlock()
  521. e := currentBlock.Rollup
  522. return int64(len(e.State.ExitRoots)) - 1
  523. }
  524. // EthLastBlock returns the last blockNum
  525. func (c *Client) EthLastBlock() (int64, error) {
  526. c.rw.RLock()
  527. defer c.rw.RUnlock()
  528. if c.blockNum < c.maxBlockNum {
  529. panic("blockNum has decreased. " +
  530. "After a rollback you must mine to reach the same or higher blockNum")
  531. }
  532. return c.blockNum, nil
  533. }
  534. // EthTransactionReceipt returns the transaction receipt of the given txHash
  535. func (c *Client) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  536. c.rw.RLock()
  537. defer c.rw.RUnlock()
  538. for i := int64(0); i < c.blockNum; i++ {
  539. b := c.blocks[i]
  540. _, ok := b.Rollup.Txs[txHash]
  541. if !ok {
  542. _, ok = b.Auction.Txs[txHash]
  543. }
  544. if ok {
  545. return &types.Receipt{
  546. TxHash: txHash,
  547. Status: types.ReceiptStatusSuccessful,
  548. BlockHash: b.Eth.Hash,
  549. BlockNumber: big.NewInt(b.Eth.BlockNum),
  550. }, nil
  551. }
  552. }
  553. return nil, nil
  554. }
  555. // CtlAddERC20 adds an ERC20 token to the blockchain.
  556. func (c *Client) CtlAddERC20(tokenAddr ethCommon.Address, constants eth.ERC20Consts) {
  557. nextBlock := c.nextBlock()
  558. e := nextBlock.Eth
  559. e.Tokens[tokenAddr] = constants
  560. }
  561. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  562. func (c *Client) EthERC20Consts(tokenAddr ethCommon.Address) (*eth.ERC20Consts, error) {
  563. currentBlock := c.currentBlock()
  564. e := currentBlock.Eth
  565. if constants, ok := e.Tokens[tokenAddr]; ok {
  566. return &constants, nil
  567. }
  568. return nil, tracerr.Wrap(fmt.Errorf("tokenAddr not found"))
  569. }
  570. // func newHeader(number *big.Int) *types.Header {
  571. // return &types.Header{
  572. // Number: number,
  573. // Time: uint64(number.Int64()),
  574. // }
  575. // }
  576. // EthHeaderByNumber returns the *types.Header for the given block number in a
  577. // deterministic way.
  578. // func (c *Client) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  579. // return newHeader(number), nil
  580. // }
  581. // EthBlockByNumber returns the *common.Block for the given block number in a
  582. // deterministic way. If number == -1, the latests known block is returned.
  583. func (c *Client) EthBlockByNumber(ctx context.Context, blockNum int64) (*common.Block, error) {
  584. c.rw.RLock()
  585. defer c.rw.RUnlock()
  586. if blockNum > c.blockNum {
  587. return nil, ethereum.NotFound
  588. }
  589. if blockNum == -1 {
  590. blockNum = c.blockNum
  591. }
  592. block := c.blocks[blockNum]
  593. return &common.Block{
  594. Num: blockNum,
  595. Timestamp: time.Unix(block.Eth.Time, 0),
  596. Hash: block.Eth.Hash,
  597. ParentHash: block.Eth.ParentHash,
  598. }, nil
  599. }
  600. // EthAddress returns the ethereum address of the account loaded into the Client
  601. func (c *Client) EthAddress() (*ethCommon.Address, error) {
  602. if c.addr == nil {
  603. return nil, tracerr.Wrap(eth.ErrAccountNil)
  604. }
  605. return c.addr, nil
  606. }
  607. var errTODO = fmt.Errorf("TODO: Not implemented yet")
  608. //
  609. // Rollup
  610. //
  611. // CtlAddL1TxUser adds an L1TxUser to the L1UserTxs queue of the Rollup
  612. // func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) {
  613. // c.rw.Lock()
  614. // defer c.rw.Unlock()
  615. //
  616. // nextBlock := c.nextBlock()
  617. // r := nextBlock.Rollup
  618. // queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  619. // if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx {
  620. // r.State.LastToForgeL1TxsNum++
  621. // r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  622. // queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  623. // }
  624. // if int64(l1Tx.FromIdx) > r.State.CurrentIdx {
  625. // panic("l1Tx.FromIdx > r.State.CurrentIdx")
  626. // }
  627. // if int(l1Tx.TokenID)+1 > len(r.State.TokenList) {
  628. // panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  629. // }
  630. // queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  631. // r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  632. // L1Tx: *l1Tx,
  633. // ToForgeL1TxsNum: r.State.LastToForgeL1TxsNum,
  634. // Position: len(queue.L1TxQueue) - 1,
  635. // })
  636. // }
  637. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  638. func (c *Client) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
  639. log.Error("TODO")
  640. return nil, tracerr.Wrap(errTODO)
  641. }
  642. // RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
  643. func (c *Client) RollupL1UserTxERC20ETH(
  644. fromBJJ *babyjub.PublicKey,
  645. fromIdx int64,
  646. depositAmount *big.Int,
  647. amount *big.Int,
  648. tokenID uint32,
  649. toIdx int64,
  650. ) (tx *types.Transaction, err error) {
  651. c.rw.Lock()
  652. defer c.rw.Unlock()
  653. cpy := c.nextBlock().copy()
  654. defer func() { c.revertIfErr(err, cpy) }()
  655. _, err = common.NewFloat16(amount)
  656. if err != nil {
  657. return nil, tracerr.Wrap(err)
  658. }
  659. _, err = common.NewFloat16(depositAmount)
  660. if err != nil {
  661. return nil, tracerr.Wrap(err)
  662. }
  663. nextBlock := c.nextBlock()
  664. r := nextBlock.Rollup
  665. queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  666. if len(queue.L1TxQueue) >= common.RollupConstMaxL1UserTx {
  667. r.State.LastToForgeL1TxsNum++
  668. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  669. queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  670. }
  671. if fromIdx > r.State.CurrentIdx {
  672. panic("l1Tx.FromIdx > r.State.CurrentIdx")
  673. }
  674. if int(tokenID)+1 > len(r.State.TokenList) {
  675. panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  676. }
  677. toForgeL1TxsNum := r.State.LastToForgeL1TxsNum
  678. l1Tx, err := common.NewL1Tx(&common.L1Tx{
  679. FromIdx: common.Idx(fromIdx),
  680. FromEthAddr: *c.addr,
  681. FromBJJ: fromBJJ,
  682. Amount: amount,
  683. DepositAmount: depositAmount,
  684. TokenID: common.TokenID(tokenID),
  685. ToIdx: common.Idx(toIdx),
  686. ToForgeL1TxsNum: &toForgeL1TxsNum,
  687. Position: len(queue.L1TxQueue),
  688. UserOrigin: true,
  689. })
  690. if err != nil {
  691. return nil, tracerr.Wrap(err)
  692. }
  693. queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  694. r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  695. L1UserTx: *l1Tx,
  696. })
  697. return r.addTransaction(c.newTransaction("l1UserTxERC20ETH", l1Tx)), nil
  698. }
  699. // RollupL1UserTxERC777 is the interface to call the smart contract function
  700. // func (c *Client) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  701. // log.Error("TODO")
  702. // return nil, errTODO
  703. // }
  704. // RollupRegisterTokensCount is the interface to call the smart contract function
  705. func (c *Client) RollupRegisterTokensCount() (*big.Int, error) {
  706. log.Error("TODO")
  707. return nil, tracerr.Wrap(errTODO)
  708. }
  709. // RollupLastForgedBatch is the interface to call the smart contract function
  710. func (c *Client) RollupLastForgedBatch() (int64, error) {
  711. c.rw.RLock()
  712. defer c.rw.RUnlock()
  713. currentBlock := c.currentBlock()
  714. e := currentBlock.Rollup
  715. return int64(len(e.State.ExitRoots)) - 1, nil
  716. }
  717. // RollupWithdrawCircuit is the interface to call the smart contract function
  718. 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) {
  719. log.Error("TODO")
  720. return nil, tracerr.Wrap(errTODO)
  721. }
  722. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  723. 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) {
  724. c.rw.Lock()
  725. defer c.rw.Unlock()
  726. cpy := c.nextBlock().copy()
  727. defer func() { c.revertIfErr(err, cpy) }()
  728. nextBlock := c.nextBlock()
  729. r := nextBlock.Rollup
  730. if int(numExitRoot) >= len(r.State.ExitRoots) {
  731. return nil, tracerr.Wrap(fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)"))
  732. }
  733. if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok {
  734. return nil, tracerr.Wrap(fmt.Errorf("exit already withdrawn"))
  735. }
  736. r.State.ExitNullifierMap[numExitRoot][idx] = true
  737. type data struct {
  738. BabyPubKey *babyjub.PublicKey
  739. TokenID uint32
  740. NumExitRoot int64
  741. Idx int64
  742. Amount *big.Int
  743. Siblings []*big.Int
  744. InstantWithdraw bool
  745. }
  746. tx = r.addTransaction(c.newTransaction("withdrawMerkleProof", data{
  747. BabyPubKey: babyPubKey,
  748. TokenID: tokenID,
  749. NumExitRoot: numExitRoot,
  750. Idx: idx,
  751. Amount: amount,
  752. Siblings: siblings,
  753. InstantWithdraw: instantWithdraw,
  754. }))
  755. r.Events.Withdraw = append(r.Events.Withdraw, eth.RollupEventWithdraw{
  756. Idx: uint64(idx),
  757. NumExitRoot: uint64(numExitRoot),
  758. InstantWithdraw: instantWithdraw,
  759. TxHash: tx.Hash(),
  760. })
  761. if !instantWithdraw {
  762. w := nextBlock.WDelayer
  763. w.deposit(tx.Hash(), *c.addr, r.State.TokenList[int(tokenID)], amount)
  764. }
  765. return tx, nil
  766. }
  767. type transactionData struct {
  768. Name string
  769. Value interface{}
  770. }
  771. func (c *Client) newTransaction(name string, value interface{}) *types.Transaction {
  772. eth := c.nextBlock().Eth
  773. nonce := eth.Nonce
  774. eth.Nonce++
  775. data, err := json.Marshal(transactionData{name, value})
  776. if err != nil {
  777. panic(err)
  778. }
  779. return types.NewTransaction(nonce, ethCommon.Address{}, nil, 0, nil,
  780. data)
  781. }
  782. // RollupForgeBatch is the interface to call the smart contract function
  783. func (c *Client) RollupForgeBatch(args *eth.RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  784. c.rw.Lock()
  785. defer c.rw.Unlock()
  786. cpy := c.nextBlock().copy()
  787. defer func() { c.revertIfErr(err, cpy) }()
  788. if c.addr == nil {
  789. return nil, tracerr.Wrap(eth.ErrAccountNil)
  790. }
  791. a := c.nextBlock().Auction
  792. ok, err := a.canForge(*c.addr, a.Eth.BlockNum)
  793. if err != nil {
  794. return nil, tracerr.Wrap(err)
  795. }
  796. if !ok {
  797. return nil, tracerr.Wrap(fmt.Errorf(common.AuctionErrMsgCannotForge))
  798. }
  799. // TODO: Verify proof
  800. // Auction
  801. err = a.forge(*c.addr)
  802. if err != nil {
  803. return nil, tracerr.Wrap(err)
  804. }
  805. // TODO: If successful, store the tx in a successful array.
  806. // TODO: If failed, store the tx in a failed array.
  807. // TODO: Add method to move the tx to another block, reapply it there, and possibly go from successful to failed.
  808. return c.addBatch(args)
  809. }
  810. // CtlAddBatch adds forged batch to the Rollup, without checking any ZKProof
  811. func (c *Client) CtlAddBatch(args *eth.RollupForgeBatchArgs) {
  812. c.rw.Lock()
  813. defer c.rw.Unlock()
  814. if _, err := c.addBatch(args); err != nil {
  815. panic(err)
  816. }
  817. }
  818. func (c *Client) addBatch(args *eth.RollupForgeBatchArgs) (*types.Transaction, error) {
  819. nextBlock := c.nextBlock()
  820. r := nextBlock.Rollup
  821. r.State.StateRoot = args.NewStRoot
  822. if args.NewLastIdx < r.State.CurrentIdx {
  823. return nil, tracerr.Wrap(fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx"))
  824. }
  825. r.State.CurrentIdx = args.NewLastIdx
  826. r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)
  827. r.State.ExitRoots = append(r.State.ExitRoots, args.NewExitRoot)
  828. if args.L1Batch {
  829. r.State.CurrentToForgeL1TxsNum++
  830. if r.State.CurrentToForgeL1TxsNum == r.State.LastToForgeL1TxsNum {
  831. r.State.LastToForgeL1TxsNum++
  832. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  833. }
  834. }
  835. ethTx := r.addTransaction(c.newTransaction("forgebatch", args))
  836. c.forgeBatchArgsPending[ethTx.Hash()] = &batch{*args, *c.addr}
  837. r.Events.ForgeBatch = append(r.Events.ForgeBatch, eth.RollupEventForgeBatch{
  838. BatchNum: int64(len(r.State.ExitRoots)) - 1,
  839. EthTxHash: ethTx.Hash(),
  840. L1UserTxsLen: uint16(len(args.L1UserTxs)),
  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, l1UserTxsLen uint16) (*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, newBootCoordinatorURL string) (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. // WDelayerGetHermezGovernanceAddress is the interface to call the smart contract function
  1310. func (c *Client) WDelayerGetHermezGovernanceAddress() (*ethCommon.Address, error) {
  1311. c.rw.RLock()
  1312. defer c.rw.RUnlock()
  1313. log.Error("TODO")
  1314. return nil, tracerr.Wrap(errTODO)
  1315. }
  1316. // WDelayerTransferGovernance is the interface to call the smart contract function
  1317. func (c *Client) WDelayerTransferGovernance(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. // WDelayerClaimGovernance is the interface to call the smart contract function
  1329. func (c *Client) WDelayerClaimGovernance() (tx *types.Transaction, err error) {
  1330. c.rw.Lock()
  1331. defer c.rw.Unlock()
  1332. cpy := c.nextBlock().copy()
  1333. defer func() { c.revertIfErr(err, cpy) }()
  1334. if c.addr == nil {
  1335. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1336. }
  1337. log.Error("TODO")
  1338. return nil, tracerr.Wrap(errTODO)
  1339. }
  1340. // WDelayerGetEmergencyCouncil is the interface to call the smart contract function
  1341. func (c *Client) WDelayerGetEmergencyCouncil() (*ethCommon.Address, error) {
  1342. c.rw.RLock()
  1343. defer c.rw.RUnlock()
  1344. log.Error("TODO")
  1345. return nil, tracerr.Wrap(errTODO)
  1346. }
  1347. // WDelayerTransferEmergencyCouncil is the interface to call the smart contract function
  1348. func (c *Client) WDelayerTransferEmergencyCouncil(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1349. c.rw.Lock()
  1350. defer c.rw.Unlock()
  1351. cpy := c.nextBlock().copy()
  1352. defer func() { c.revertIfErr(err, cpy) }()
  1353. if c.addr == nil {
  1354. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1355. }
  1356. log.Error("TODO")
  1357. return nil, tracerr.Wrap(errTODO)
  1358. }
  1359. // WDelayerClaimEmergencyCouncil is the interface to call the smart contract function
  1360. func (c *Client) WDelayerClaimEmergencyCouncil() (tx *types.Transaction, err error) {
  1361. c.rw.Lock()
  1362. defer c.rw.Unlock()
  1363. cpy := c.nextBlock().copy()
  1364. defer func() { c.revertIfErr(err, cpy) }()
  1365. if c.addr == nil {
  1366. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1367. }
  1368. log.Error("TODO")
  1369. return nil, tracerr.Wrap(errTODO)
  1370. }
  1371. // WDelayerIsEmergencyMode is the interface to call the smart contract function
  1372. func (c *Client) WDelayerIsEmergencyMode() (bool, error) {
  1373. c.rw.RLock()
  1374. defer c.rw.RUnlock()
  1375. log.Error("TODO")
  1376. return false, tracerr.Wrap(errTODO)
  1377. }
  1378. // WDelayerGetWithdrawalDelay is the interface to call the smart contract function
  1379. func (c *Client) WDelayerGetWithdrawalDelay() (*big.Int, error) {
  1380. c.rw.RLock()
  1381. defer c.rw.RUnlock()
  1382. log.Error("TODO")
  1383. return nil, tracerr.Wrap(errTODO)
  1384. }
  1385. // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function
  1386. func (c *Client) WDelayerGetEmergencyModeStartingTime() (*big.Int, error) {
  1387. c.rw.RLock()
  1388. defer c.rw.RUnlock()
  1389. log.Error("TODO")
  1390. return nil, tracerr.Wrap(errTODO)
  1391. }
  1392. // WDelayerEnableEmergencyMode is the interface to call the smart contract function
  1393. func (c *Client) WDelayerEnableEmergencyMode() (tx *types.Transaction, err error) {
  1394. c.rw.Lock()
  1395. defer c.rw.Unlock()
  1396. cpy := c.nextBlock().copy()
  1397. defer func() { c.revertIfErr(err, cpy) }()
  1398. if c.addr == nil {
  1399. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1400. }
  1401. log.Error("TODO")
  1402. return nil, tracerr.Wrap(errTODO)
  1403. }
  1404. // WDelayerChangeWithdrawalDelay is the interface to call the smart contract function
  1405. func (c *Client) WDelayerChangeWithdrawalDelay(newWithdrawalDelay uint64) (tx *types.Transaction, err error) {
  1406. c.rw.Lock()
  1407. defer c.rw.Unlock()
  1408. cpy := c.nextBlock().copy()
  1409. defer func() { c.revertIfErr(err, cpy) }()
  1410. if c.addr == nil {
  1411. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1412. }
  1413. nextBlock := c.nextBlock()
  1414. w := nextBlock.WDelayer
  1415. w.Vars.WithdrawalDelay = newWithdrawalDelay
  1416. w.Events.NewWithdrawalDelay = append(w.Events.NewWithdrawalDelay,
  1417. eth.WDelayerEventNewWithdrawalDelay{WithdrawalDelay: newWithdrawalDelay})
  1418. return w.addTransaction(c.newTransaction("changeWithdrawalDelay", newWithdrawalDelay)), nil
  1419. }
  1420. // WDelayerDepositInfo is the interface to call the smart contract function
  1421. func (c *Client) WDelayerDepositInfo(owner, token ethCommon.Address) (eth.DepositState, error) {
  1422. c.rw.RLock()
  1423. defer c.rw.RUnlock()
  1424. log.Error("TODO")
  1425. return eth.DepositState{}, tracerr.Wrap(errTODO)
  1426. }
  1427. // WDelayerDeposit is the interface to call the smart contract function
  1428. func (c *Client) WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1429. c.rw.Lock()
  1430. defer c.rw.Unlock()
  1431. cpy := c.nextBlock().copy()
  1432. defer func() { c.revertIfErr(err, cpy) }()
  1433. if c.addr == nil {
  1434. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1435. }
  1436. log.Error("TODO")
  1437. return nil, tracerr.Wrap(errTODO)
  1438. }
  1439. // WDelayerWithdrawal is the interface to call the smart contract function
  1440. func (c *Client) WDelayerWithdrawal(owner, token ethCommon.Address) (tx *types.Transaction, err error) {
  1441. c.rw.Lock()
  1442. defer c.rw.Unlock()
  1443. cpy := c.nextBlock().copy()
  1444. defer func() { c.revertIfErr(err, cpy) }()
  1445. if c.addr == nil {
  1446. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1447. }
  1448. log.Error("TODO")
  1449. return nil, tracerr.Wrap(errTODO)
  1450. }
  1451. // WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function
  1452. func (c *Client) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1453. c.rw.Lock()
  1454. defer c.rw.Unlock()
  1455. cpy := c.nextBlock().copy()
  1456. defer func() { c.revertIfErr(err, cpy) }()
  1457. if c.addr == nil {
  1458. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1459. }
  1460. log.Error("TODO")
  1461. return nil, tracerr.Wrap(errTODO)
  1462. }
  1463. // WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract
  1464. func (c *Client) WDelayerEventsByBlock(blockNum int64) (*eth.WDelayerEvents, *ethCommon.Hash, error) {
  1465. c.rw.RLock()
  1466. defer c.rw.RUnlock()
  1467. block, ok := c.blocks[blockNum]
  1468. if !ok {
  1469. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  1470. }
  1471. return &block.WDelayer.Events, &block.Eth.Hash, nil
  1472. }
  1473. // WDelayerConstants returns the Constants of the WDelayer Contract
  1474. func (c *Client) WDelayerConstants() (*common.WDelayerConstants, error) {
  1475. c.rw.RLock()
  1476. defer c.rw.RUnlock()
  1477. return c.wDelayerConstants, nil
  1478. }