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.

774 lines
30 KiB

4 years ago
  1. package eth
  2. import (
  3. "context"
  4. "fmt"
  5. "math/big"
  6. "strings"
  7. "github.com/ethereum/go-ethereum"
  8. "github.com/ethereum/go-ethereum/accounts/abi"
  9. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  10. ethCommon "github.com/ethereum/go-ethereum/common"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethclient"
  14. "github.com/hermeznetwork/hermez-node/common"
  15. Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
  16. HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
  17. "github.com/hermeznetwork/hermez-node/log"
  18. "github.com/iden3/go-iden3-crypto/babyjub"
  19. )
  20. const (
  21. // RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
  22. // coordinator can use to collect fees (determines the number of tokens
  23. // that the coordinator can collect fees from). This value is
  24. // determined by the circuit.
  25. RollupConstMaxFeeIdxCoordinator = 64
  26. // RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
  27. RollupConstReservedIDx = 255
  28. // RollupConstExitIDx IDX 1 is reserved for exits
  29. RollupConstExitIDx = 1
  30. // RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
  31. RollupConstLimitLoadAmount = (1 << 128)
  32. // RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
  33. RollupConstLimitL2TransferAmount = (1 << 192)
  34. // RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
  35. RollupConstLimitTokens = (1 << 32)
  36. // RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
  37. RollupConstL1CoordinatorTotalBytes = 101
  38. // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx +
  39. // [2 bytes] loadAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx
  40. RollupConstL1UserTotalBytes = 72
  41. // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
  42. RollupConstMaxL1UserTx = 128
  43. // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
  44. RollupConstMaxL1Tx = 256
  45. // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot +
  46. // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID =
  47. // 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength
  48. RollupConstInputSHAConstantBytes = 18542
  49. // RollupConstNumBuckets Number of buckets
  50. RollupConstNumBuckets = 5
  51. // RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
  52. RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
  53. // RollupConstExchangeMultiplier exchange multiplier
  54. RollupConstExchangeMultiplier = 1e14
  55. // LenVerifiers number of Rollup Smart Contract Verifiers
  56. LenVerifiers = 1
  57. )
  58. var (
  59. // RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
  60. // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup
  61. // account without needing an ethereum address
  62. RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
  63. // RollupConstRfield Modulus zkSNARK
  64. RollupConstRfield, _ = new(big.Int).SetString(
  65. "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  66. // RollupConstERC1820 ERC1820Registry address
  67. RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
  68. // ERC777 tokens signatures
  69. // RollupConstRecipientInterfaceHash ERC777 recipient interface hash
  70. RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
  71. // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send`
  72. RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
  73. // RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
  74. RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
  75. // RollupConstSendSignature ERC777 Signature
  76. RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
  77. // RollupConstERC777Granularity ERC777 Signature
  78. RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
  79. // RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
  80. RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
  81. // ERC20 signature
  82. // RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  83. RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
  84. // RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  85. RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
  86. // RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  87. RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
  88. // RollupConstERC20Signature ERC20 decimals signature
  89. RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
  90. )
  91. // RollupPublicConstants are the constants of the Rollup Smart Contract
  92. type RollupPublicConstants struct {
  93. AbsoluteMaxL1L2BatchTimeout int64 `json:"absoluteMaxL1L2BatchTimeout"`
  94. TokenHEZ ethCommon.Address `json:"tokenHEZ"`
  95. Verifiers []RollupVerifierStruct `json:"verifiers"`
  96. HermezAuctionContract ethCommon.Address `json:"hermezAuctionContract"`
  97. HermezGovernanceDAOAddress ethCommon.Address `json:"hermezGovernanceDAOAddress"`
  98. SafetyAddress ethCommon.Address `json:"safetyAddress"`
  99. WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
  100. }
  101. // RollupVariables are the variables of the Rollup Smart Contract
  102. type RollupVariables struct {
  103. FeeAddToken *big.Int
  104. ForgeL1L2BatchTimeout int64
  105. WithdrawalDelay uint64
  106. }
  107. // QueueStruct is the queue of L1Txs for a batch
  108. type QueueStruct struct {
  109. L1TxQueue []common.L1Tx
  110. TotalL1TxFee *big.Int
  111. }
  112. // NewQueueStruct creates a new clear QueueStruct.
  113. func NewQueueStruct() *QueueStruct {
  114. return &QueueStruct{
  115. L1TxQueue: make([]common.L1Tx, 0),
  116. TotalL1TxFee: big.NewInt(0),
  117. }
  118. }
  119. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  120. type RollupVerifierStruct struct {
  121. MaxTx int64 `json:"maxTx"`
  122. NLevels int64 `json:"nlevels"`
  123. }
  124. // RollupState represents the state of the Rollup in the Smart Contract
  125. type RollupState struct {
  126. StateRoot *big.Int
  127. ExitRoots []*big.Int
  128. ExitNullifierMap map[[256 / 8]byte]bool
  129. TokenList []ethCommon.Address
  130. TokenMap map[ethCommon.Address]bool
  131. MapL1TxQueue map[int64]*QueueStruct
  132. LastL1L2Batch int64
  133. CurrentToForgeL1TxsNum int64
  134. LastToForgeL1TxsNum int64
  135. CurrentIdx int64
  136. }
  137. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  138. type RollupEventL1UserTx struct {
  139. // ToForgeL1TxsNum int64 // QueueIndex *big.Int
  140. // Position int // TransactionIndex *big.Int
  141. L1UserTx common.L1Tx
  142. }
  143. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  144. type RollupEventL1UserTxAux struct {
  145. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  146. Position uint8 // TransactionIndex *big.Int
  147. L1UserTx []byte
  148. }
  149. // RollupEventAddToken is an event of the Rollup Smart Contract
  150. type RollupEventAddToken struct {
  151. TokenAddress ethCommon.Address
  152. TokenID uint32
  153. }
  154. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  155. type RollupEventForgeBatch struct {
  156. BatchNum int64
  157. // Sender ethCommon.Address
  158. EthTxHash ethCommon.Hash
  159. }
  160. // RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
  161. type RollupEventUpdateForgeL1L2BatchTimeout struct {
  162. NewForgeL1L2BatchTimeout int64
  163. }
  164. // RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
  165. type RollupEventUpdateFeeAddToken struct {
  166. NewFeeAddToken *big.Int
  167. }
  168. // RollupEventWithdrawEvent is an event of the Rollup Smart Contract
  169. type RollupEventWithdrawEvent struct {
  170. Idx uint64
  171. NumExitRoot uint64
  172. InstantWithdraw bool
  173. }
  174. // RollupEvents is the list of events in a block of the Rollup Smart Contract
  175. type RollupEvents struct {
  176. L1UserTx []RollupEventL1UserTx
  177. AddToken []RollupEventAddToken
  178. ForgeBatch []RollupEventForgeBatch
  179. UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
  180. UpdateFeeAddToken []RollupEventUpdateFeeAddToken
  181. WithdrawEvent []RollupEventWithdrawEvent
  182. }
  183. // NewRollupEvents creates an empty RollupEvents with the slices initialized.
  184. func NewRollupEvents() RollupEvents {
  185. return RollupEvents{
  186. L1UserTx: make([]RollupEventL1UserTx, 0),
  187. AddToken: make([]RollupEventAddToken, 0),
  188. ForgeBatch: make([]RollupEventForgeBatch, 0),
  189. UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
  190. UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
  191. WithdrawEvent: make([]RollupEventWithdrawEvent, 0),
  192. }
  193. }
  194. // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
  195. type RollupForgeBatchArgs struct {
  196. NewLastIdx int64
  197. NewStRoot *big.Int
  198. NewExitRoot *big.Int
  199. L1CoordinatorTxs []common.L1Tx
  200. L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
  201. L2TxsData []common.L2Tx
  202. FeeIdxCoordinator []common.Idx
  203. // Circuit selector
  204. VerifierIdx uint8
  205. L1Batch bool
  206. ProofA [2]*big.Int
  207. ProofB [2][2]*big.Int
  208. ProofC [2]*big.Int
  209. }
  210. // RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
  211. type RollupForgeBatchArgsAux struct {
  212. NewLastIdx *big.Int
  213. NewStRoot *big.Int
  214. NewExitRoot *big.Int
  215. EncodedL1CoordinatorTx []byte
  216. L2TxsData []byte
  217. FeeIdxCoordinator []byte
  218. // Circuit selector
  219. VerifierIdx uint8
  220. L1Batch bool
  221. ProofA [2]*big.Int
  222. ProofB [2][2]*big.Int
  223. ProofC [2]*big.Int
  224. }
  225. // RollupInterface is the inteface to to Rollup Smart Contract
  226. type RollupInterface interface {
  227. //
  228. // Smart Contract Methods
  229. //
  230. // Public Functions
  231. RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
  232. RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (*types.Transaction, error)
  233. RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
  234. RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
  235. RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
  236. RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error)
  237. // Governance Public Functions
  238. RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
  239. RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
  240. // Viewers
  241. RollupRegisterTokensCount() (*big.Int, error)
  242. //
  243. // Smart Contract Status
  244. //
  245. RollupConstants() (*RollupPublicConstants, error)
  246. RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
  247. RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error)
  248. }
  249. //
  250. // Implementation
  251. //
  252. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  253. type RollupClient struct {
  254. client *EthereumClient
  255. address ethCommon.Address
  256. tokenHEZCfg TokenConfig
  257. hermez *Hermez.Hermez
  258. tokenHEZ *HEZ.HEZ
  259. contractAbi abi.ABI
  260. }
  261. // NewRollupClient creates a new RollupClient
  262. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZCfg TokenConfig) (*RollupClient, error) {
  263. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  264. if err != nil {
  265. return nil, err
  266. }
  267. hermez, err := Hermez.NewHermez(address, client.Client())
  268. if err != nil {
  269. return nil, err
  270. }
  271. tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client())
  272. if err != nil {
  273. return nil, err
  274. }
  275. return &RollupClient{
  276. client: client,
  277. address: address,
  278. tokenHEZCfg: tokenHEZCfg,
  279. hermez: hermez,
  280. tokenHEZ: tokenHEZ,
  281. contractAbi: contractAbi,
  282. }, nil
  283. }
  284. // RollupForgeBatch is the interface to call the smart contract function
  285. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  286. if tx, err = c.client.CallAuth(
  287. 1000000, //nolint:gomnd
  288. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  289. rollupConst, err := c.RollupConstants()
  290. if err != nil {
  291. return nil, err
  292. }
  293. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  294. lenBytes := nLevels / 8 //nolint:gomnd
  295. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  296. var l1CoordinatorBytes []byte
  297. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  298. l1 := args.L1CoordinatorTxs[i]
  299. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  300. if err != nil {
  301. return nil, err
  302. }
  303. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  304. }
  305. var l2DataBytes []byte
  306. for i := 0; i < len(args.L2TxsData); i++ {
  307. l2 := args.L2TxsData[i]
  308. bytesl2, err := l2.Bytes(int(nLevels))
  309. if err != nil {
  310. return nil, err
  311. }
  312. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  313. }
  314. var feeIdxCoordinator []byte
  315. if len(args.FeeIdxCoordinator) > RollupConstMaxFeeIdxCoordinator {
  316. return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  317. RollupConstMaxFeeIdxCoordinator)
  318. }
  319. for i := 0; i < RollupConstMaxFeeIdxCoordinator; i++ {
  320. feeIdx := common.Idx(0)
  321. if i < len(args.FeeIdxCoordinator) {
  322. feeIdx = args.FeeIdxCoordinator[i]
  323. }
  324. bytesFeeIdx, err := feeIdx.Bytes()
  325. if err != nil {
  326. return nil, err
  327. }
  328. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  329. }
  330. return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  331. },
  332. ); err != nil {
  333. return nil, fmt.Errorf("Failed forge batch: %w", err)
  334. }
  335. return tx, nil
  336. }
  337. // RollupAddToken is the interface to call the smart contract function.
  338. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  339. // token. `feeAddToken` must match the public value of the smart contract.
  340. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (tx *types.Transaction, err error) {
  341. if tx, err = c.client.CallAuth(
  342. 0,
  343. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  344. owner := c.client.account.Address
  345. spender := c.address
  346. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  347. if err != nil {
  348. return nil, err
  349. }
  350. tokenName := c.tokenHEZCfg.Name
  351. tokenAddr := c.tokenHEZCfg.Address
  352. chainid, _ := c.client.Client().ChainID(context.Background())
  353. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, feeAddToken, nonce, deadline, tokenName)
  354. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  355. permit := createPermit(owner, spender, feeAddToken, deadline, digest, signature)
  356. return c.hermez.AddToken(auth, tokenAddress, permit)
  357. },
  358. ); err != nil {
  359. return nil, fmt.Errorf("Failed add Token %w", err)
  360. }
  361. return tx, nil
  362. }
  363. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  364. func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
  365. if tx, err = c.client.CallAuth(
  366. 0,
  367. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  368. pkCompL := fromBJJ.Compress()
  369. pkCompB := common.SwapEndianness(pkCompL[:])
  370. babyPubKey := new(big.Int).SetBytes(pkCompB)
  371. numExitRootB := big.NewInt(numExitRoot)
  372. idxBig := big.NewInt(idx)
  373. return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
  374. },
  375. ); err != nil {
  376. return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
  377. }
  378. return tx, nil
  379. }
  380. // RollupWithdrawCircuit is the interface to call the smart contract function
  381. func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) {
  382. log.Error("TODO")
  383. return nil, errTODO
  384. }
  385. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  386. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
  387. if tx, err = c.client.CallAuth(
  388. 0,
  389. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  390. pkCompL := fromBJJ.Compress()
  391. pkCompB := common.SwapEndianness(pkCompL[:])
  392. babyPubKey := new(big.Int).SetBytes(pkCompB)
  393. fromIdxBig := big.NewInt(fromIdx)
  394. toIdxBig := big.NewInt(toIdx)
  395. loadAmountF, err := common.NewFloat16(loadAmount)
  396. if err != nil {
  397. return nil, err
  398. }
  399. amountF, err := common.NewFloat16(amount)
  400. if err != nil {
  401. return nil, err
  402. }
  403. if tokenID == 0 {
  404. auth.Value = loadAmount
  405. }
  406. var permit []byte
  407. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  408. uint16(amountF), tokenID, toIdxBig, permit)
  409. },
  410. ); err != nil {
  411. return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
  412. }
  413. return tx, nil
  414. }
  415. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  416. func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
  417. if tx, err = c.client.CallAuth(
  418. 0,
  419. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  420. pkCompL := fromBJJ.Compress()
  421. pkCompB := common.SwapEndianness(pkCompL[:])
  422. babyPubKey := new(big.Int).SetBytes(pkCompB)
  423. fromIdxBig := big.NewInt(fromIdx)
  424. toIdxBig := big.NewInt(toIdx)
  425. loadAmountF, err := common.NewFloat16(loadAmount)
  426. if err != nil {
  427. return nil, err
  428. }
  429. amountF, err := common.NewFloat16(amount)
  430. if err != nil {
  431. return nil, err
  432. }
  433. if tokenID == 0 {
  434. auth.Value = loadAmount
  435. }
  436. owner := c.client.account.Address
  437. spender := c.address
  438. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  439. if err != nil {
  440. return nil, err
  441. }
  442. tokenName := c.tokenHEZCfg.Name
  443. tokenAddr := c.tokenHEZCfg.Address
  444. chainid, _ := c.client.Client().ChainID(context.Background())
  445. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, amount, nonce, deadline, tokenName)
  446. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  447. permit := createPermit(owner, spender, amount, deadline, digest, signature)
  448. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  449. uint16(amountF), tokenID, toIdxBig, permit)
  450. },
  451. ); err != nil {
  452. return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)
  453. }
  454. return tx, nil
  455. }
  456. // RollupRegisterTokensCount is the interface to call the smart contract function
  457. func (c *RollupClient) RollupRegisterTokensCount() (*big.Int, error) {
  458. var registerTokensCount *big.Int
  459. if err := c.client.Call(func(ec *ethclient.Client) error {
  460. hermez, err := Hermez.NewHermez(c.address, ec)
  461. if err != nil {
  462. return err
  463. }
  464. registerTokensCount, err = hermez.RegisterTokensCount(nil)
  465. return err
  466. }); err != nil {
  467. return nil, err
  468. }
  469. return registerTokensCount, nil
  470. }
  471. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  472. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
  473. if tx, err = c.client.CallAuth(
  474. 0,
  475. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  476. return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
  477. },
  478. ); err != nil {
  479. return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
  480. }
  481. return tx, nil
  482. }
  483. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  484. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  485. if tx, err = c.client.CallAuth(
  486. 0,
  487. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  488. return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  489. },
  490. ); err != nil {
  491. return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
  492. }
  493. return tx, nil
  494. }
  495. // RollupConstants returns the Constants of the Rollup Smart Contract
  496. func (c *RollupClient) RollupConstants() (rollupConstants *RollupPublicConstants, err error) {
  497. rollupConstants = new(RollupPublicConstants)
  498. if err := c.client.Call(func(ec *ethclient.Client) error {
  499. absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  500. if err != nil {
  501. return err
  502. }
  503. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  504. rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil)
  505. if err != nil {
  506. return err
  507. }
  508. for i := int64(0); i < int64(LenVerifiers); i++ {
  509. var newRollupVerifier RollupVerifierStruct
  510. rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
  511. if err != nil {
  512. return err
  513. }
  514. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  515. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  516. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  517. }
  518. rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil)
  519. if err != nil {
  520. return err
  521. }
  522. rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil)
  523. if err != nil {
  524. return err
  525. }
  526. rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil)
  527. if err != nil {
  528. return err
  529. }
  530. rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil)
  531. return err
  532. }); err != nil {
  533. return nil, err
  534. }
  535. return rollupConstants, nil
  536. }
  537. var (
  538. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  539. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  540. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  541. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  542. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  543. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  544. )
  545. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  546. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  547. var rollupEvents RollupEvents
  548. var blockHash ethCommon.Hash
  549. query := ethereum.FilterQuery{
  550. FromBlock: big.NewInt(blockNum),
  551. ToBlock: big.NewInt(blockNum),
  552. Addresses: []ethCommon.Address{
  553. c.address,
  554. },
  555. BlockHash: nil,
  556. Topics: [][]ethCommon.Hash{},
  557. }
  558. logs, err := c.client.client.FilterLogs(context.Background(), query)
  559. if err != nil {
  560. return nil, nil, err
  561. }
  562. if len(logs) > 0 {
  563. blockHash = logs[0].BlockHash
  564. }
  565. for _, vLog := range logs {
  566. if vLog.BlockHash != blockHash {
  567. return nil, nil, ErrBlockHashMismatchEvent
  568. }
  569. switch vLog.Topics[0] {
  570. case logHermezL1UserTxEvent:
  571. var L1UserTxAux RollupEventL1UserTxAux
  572. var L1UserTx RollupEventL1UserTx
  573. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  574. if err != nil {
  575. return nil, nil, err
  576. }
  577. L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
  578. if err != nil {
  579. return nil, nil, err
  580. }
  581. toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  582. L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
  583. L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  584. L1Tx.UserOrigin = true
  585. L1UserTx.L1UserTx = *L1Tx
  586. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  587. case logHermezAddToken:
  588. var addToken RollupEventAddToken
  589. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  590. if err != nil {
  591. return nil, nil, err
  592. }
  593. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  594. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  595. case logHermezForgeBatch:
  596. var forgeBatch RollupEventForgeBatch
  597. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  598. forgeBatch.EthTxHash = vLog.TxHash
  599. // forgeBatch.Sender = vLog.Address
  600. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  601. case logHermezUpdateForgeL1L2BatchTimeout:
  602. var updateForgeL1L2BatchTimeout struct {
  603. NewForgeL1L2BatchTimeout uint8
  604. }
  605. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  606. if err != nil {
  607. return nil, nil, err
  608. }
  609. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  610. RollupEventUpdateForgeL1L2BatchTimeout{
  611. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  612. })
  613. case logHermezUpdateFeeAddToken:
  614. var updateFeeAddToken RollupEventUpdateFeeAddToken
  615. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  616. if err != nil {
  617. return nil, nil, err
  618. }
  619. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  620. case logHermezWithdrawEvent:
  621. var withdraw RollupEventWithdrawEvent
  622. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  623. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  624. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  625. if instantWithdraw == 1 {
  626. withdraw.InstantWithdraw = true
  627. }
  628. rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
  629. }
  630. }
  631. return &rollupEvents, &blockHash, nil
  632. }
  633. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
  634. // Rollup Smart Contract in the given transaction, and the sender address.
  635. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
  636. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  637. if err != nil {
  638. return nil, nil, err
  639. }
  640. txData := tx.Data()
  641. method, err := c.contractAbi.MethodById(txData[:4])
  642. if err != nil {
  643. return nil, nil, err
  644. }
  645. receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
  646. if err != nil {
  647. return nil, nil, err
  648. }
  649. sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
  650. if err != nil {
  651. return nil, nil, err
  652. }
  653. var aux RollupForgeBatchArgsAux
  654. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  655. return nil, nil, err
  656. }
  657. rollupForgeBatchArgs := RollupForgeBatchArgs{
  658. L1Batch: aux.L1Batch,
  659. NewExitRoot: aux.NewExitRoot,
  660. NewLastIdx: aux.NewLastIdx.Int64(),
  661. NewStRoot: aux.NewStRoot,
  662. ProofA: aux.ProofA,
  663. ProofB: aux.ProofB,
  664. ProofC: aux.ProofC,
  665. VerifierIdx: aux.VerifierIdx,
  666. L1CoordinatorTxs: []common.L1Tx{},
  667. L1CoordinatorTxsAuths: [][]byte{},
  668. L2TxsData: []common.L2Tx{},
  669. FeeIdxCoordinator: []common.Idx{},
  670. }
  671. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  672. for i := 0; i < numTxsL1; i++ {
  673. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  674. var signature []byte
  675. v := bytesL1Coordinator[0]
  676. s := bytesL1Coordinator[1:33]
  677. r := bytesL1Coordinator[33:65]
  678. signature = append(signature, r[:]...)
  679. signature = append(signature, s[:]...)
  680. signature = append(signature, v)
  681. l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator)
  682. if err != nil {
  683. return nil, nil, err
  684. }
  685. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  686. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  687. }
  688. rollupConsts, err := c.RollupConstants()
  689. if err != nil {
  690. return nil, nil, err
  691. }
  692. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  693. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  694. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  695. for i := 0; i < numTxsL2; i++ {
  696. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  697. if err != nil {
  698. return nil, nil, err
  699. }
  700. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  701. }
  702. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  703. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  704. for i := 0; i < numFeeIdxCoordinator; i++ {
  705. var paddedFeeIdx [6]byte
  706. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  707. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  708. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  709. } else {
  710. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  711. }
  712. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  713. if err != nil {
  714. return nil, nil, err
  715. }
  716. if feeIdxCoordinator != common.Idx(0) {
  717. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  718. }
  719. }
  720. return &rollupForgeBatchArgs, &sender, nil
  721. }