Skip to content
This repository was archived by the owner on Dec 5, 2021. It is now read-only.

Commit

Permalink
[pull] develop from ethereum-optimism:develop (#91)
Browse files Browse the repository at this point in the history
* chore: reduce hardhat timeout to 20 seconds (ethereum-optimism#968)

* fix: force LF line endings for scripts to avoid docker problems on Windows (ethereum-optimism#974)

* fix: use correct line endings for windows

* chore: add changeset

* refactor[contracts]: Turn ExecutionManagerWrapper into a predeployed contract (ethereum-optimism#808)

* wip: Started working on L2 contract testing revamp

* test: clean tests for ProxyEOA

* style: clean imports for ProxyEOA tests

* test: port tests for ECDSAContractAccount

* fix tests and add wrapper to dump

* fix: add em wrapper to l2 deploy

* ffix: add comments to wrapper contract

* fix: add more comments

* fix: add smock comment for unbind

* Update packages/smock/src/smockit/binding.ts

* maintenance[contracts]: use dashes in chain container names (ethereum-optimism#819)

* maintenance: use dashes in chain container names

* chore: add changeset

* feat[contracts]: temporarily disable EOA upgrades (ethereum-optimism#857)

* feat[contracts]: disable eoa upgrades temporarily

* chore: add changeset

* Update OVM_ProxyEOA.sol

* fix: turn upgrade into a noop

* lint: fix

* feat[contracts]: Update Lib_AddressManager.AddressSet event to speed up data transport layer (ethereum-optimism#820)

* feat: update and improve AddressSet event

* chore: add changeset

* Update Lib_AddressManager.sol

* Reduce gas costs of deposits (ethereum-optimism#667)

* Remove messageNonce from BaseCrossDomainMessenger and use CTC queue lenght instead

Remove Abs_BaseCrossDomainMessenger and restore dedicated nonce generation in OVM_L2CrossDomainMessenger

Fix typo

* Remove sentMessages mapping from L1CrossDomainMessenger storage
and use the nonce to check for existence of replayed transaction

* Refactor out common library function for getting cross domain calldata

* Post rebase fixes

* Use the queueIndex to check the transaction was enqueued

* Fix tests for L1CrossDomainMessenger.replayMessage
Also make that test work with an actual CanonicalTransactionChain implementation rather than a smock

* Lint fixes

* Optimise the resolve calls into the AddressManager lib

* Rename the nonce parameter to be clear

* Update test name

Co-authored-by: ben-chain <[email protected]>

* Rename getXDomainCalldata to encodeXDomainCalldata to match the new Lib_CrossDomainUtils

Co-authored-by: ben-chain <[email protected]>

* optimism: bump gaslimit to 10 million ethereum-optimism#870 (ethereum-optimism#871)

* optimism: bump gaslimit to 10million

* chore: add changeset

* optimism: bump max gaslimit to 10 mil

* chore: add changeset

* chore: remove unnecessary changeset

* chore: remove unnecessary changeset

Co-authored-by: Georgios Konstantopoulos <[email protected]>

* fix: use correct contract name in tests (ethereum-optimism#921)

* fix: disable upgradability from ECDSA Account (ethereum-optimism#885)

* l2geth: remove `SignatureHashType` (ethereum-optimism#752)

* l2geth: remove tx type

* l2geth: no longer parse type in rollup client

* chore: add changeset

* chore: remove extra sighash params

* fix: do not check txtype in integration tests

Co-authored-by: Georgios Konstantopoulos <[email protected]>

* feat[contracts]: introduce OVM_GasPriceOracle (ethereum-optimism#912)

* feat[contracts]: congestion price oracle

* chore: add changeset

* contracts: gas price oracle (ethereum-optimism#917)

* contracts: gas price oracle

* tests: update

* fees: fix tests

* contracts: simplify gas price oracle

* lint: fix

* test: execution price is at the 1st storage slot

* chore: rename predeploy to GasPriceOracle

* chore: rename gas price oracle test name

Co-authored-by: Mark Tyneway <[email protected]>
Co-authored-by: Georgios Konstantopoulos <[email protected]>

* fix: configure max gas limit to 11m (ethereum-optimism#928)

Uniswap V3 contracts require that, otherwise they throw call exceptions at deployment

* Consolidate Predeploy Addresses (ethereum-optimism#931)

* added library for predeploy addresses

* refactor tests and other packages to use exported predeploys

* revert library usage in OVM_ECDSAContractAccount

* lint

* added newline

* fixed address typos

Co-authored-by: rajivpo <[email protected]>
Co-authored-by: smartcontracts <[email protected]>

* chore: remove yarn-error.log and gitignore it (ethereum-optimism#956)

* feat[contracts]: Replace Lib_RingBuffer with a much simpler Lib_Buffer (ethereum-optimism#821)

* feat[contracts]: replace Lib_RingBuffer with a simpler Lib_Buffer

* chore: changeset

* test: add tests for Lib_Buffer

* lint: fix

* test: add extra coverage for Lib_Buffer

* Update packages/contracts/contracts/optimistic-ethereum/libraries/utils/Lib_Buffer.sol

Co-authored-by: ben-chain <[email protected]>

* add some extra comments

Co-authored-by: ben-chain <[email protected]>

* fix(contracts): import predeploys (ethereum-optimism#982)

* fix(contracts): import predeploys

* fix: lint

* feat: add hardhat deploy instructions to readme (ethereum-optimism#965)

* feat: add deployment instructions to readme

* Add changeset

* fix style

* Update README.md

* feat: fees v2 (ethereum-optimism#976)

* l2 geth: new fee logic

* l2 geth: migrate to fees package

* core-utils: new fee scheme

* chore: add changeset

* l2geth: delete dead code

* integration-tests: fix typo

* integration-tests: fixes

* fees: use fee scalar

* lint: fix

* rollup: correct gas payment comparison

* fix(integration-tests): do not hardcode gas price

* core-utils: update with new scheme

* l2geth: refactor rollup oracle

* l2geth: clean up DoEstimateGas

* l2geth: implement latest scheme

* tests: fix up

* lint: fix

* l2geth: better sycn service test

* optimism: rename to TxGasLimit

* fee: fix docstring

* tests: fix

* variables: rename

* l2geth: prevent users from sending txs with too high of a fee

* integration-tests: fix import

* integration-tests: fix type

* integration-tests: fix gas limits

* lint: fix

* l2geth: log error

Co-authored-by: Georgios Konstantopoulos <[email protected]>

* Add static analysis action (ethereum-optimism#848)

* Add static analysis github action
setup python and install slither

* Add nvmrc file for setting node to v14.17

* Update slither command run to link missing contract packages from monorepo root

* Add steps for installing dependencies

* Add yarn build step to github action

* Enable colour in github action for static analysis

* Disable certain detectors

* Ensure slither does not fail build

* Add instructions on running static analysis to monorepo readme

* build(deps): bump ws from 7.4.4 to 7.4.6 in /ops/docker/hardhat (ethereum-optimism#987)

Bumps [ws](https://github.com/websockets/ws) from 7.4.4 to 7.4.6.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](websockets/ws@7.4.4...7.4.6)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix[l2geth]: fix accidental merge conflict (ethereum-optimism#994)

* feat[message-relayer]: relay tx generator (ethereum-optimism#952)

* feat[message-relayer]: relay tx generator

* whoops, I burned our infura key

* fix minor bug

* add comments

* add more comments and clean stuff up

* add empty test descriptions

* add tests

* move smock to dev deps

* chore: add changeset

* minor cleanup to merkle tree proof function

* use bignumber math to avoid nested await

* use a better interface

* minor fixes and simplifications

* backwards compatible dtl syncing (ethereum-optimism#986)

* kovan: fix attempt

* kovan: db fix

* kovan: types are strings from db

* l2geth: parse things as strings

* chore: add changeset

* dtl: also stringify the range query

* geth: dereference

* geth: assign err

* dtl: handle null

* dtl: fix unit tests

* fix[smock]: fix broken call assertions for overloaded functions  (ethereum-optimism#996)

* fix[smock]: fix broken call assertions for overloaded functions

* chore: add changeset

* minor correction and add a test

* add a test for non-overloaded functions

* fix[message-relayer]: fix failing test because of merge with develop (ethereum-optimism#1000)

* fix[message-relayer]: remove spreadsheet mode (ethereum-optimism#998)

* fix[message-relayer]: remove spreadsheet mode

* chore: add changeset

* Lower local rollup timestamp refresh (ethereum-optimism#985)

* update rollup timestamp refresh

* increase refresh time to 5s

* feat: fees v3 (ethereum-optimism#999)

* core-utils: fee impl v3

* l2geth: fees v3 impl

* integration-tests: update for fees v3

* chore: add changeset

* fix: typo

* integration-tests: fix and generalize

* fees: update fee scalar

* l2geth: check gas in the mempool behind usingovm

* tests: fix up

* l2geth: remove dead var

* truffle: fix config

* fix: remove dead coders (ethereum-optimism#1001)

* chore: delete dead coders

* chore: add changeset

* dtl: remove dead imports

* core-utils: delete dead tests

* batch-submitter: remove txtype

* chore: add changeset

* docs[message-relayer]: add a README and improve the interface for generating proofs (ethereum-optimism#1002)

* docs[message-relayer]: add basic docs and clean up an interface

* chore: add changeset

* dtl: log error stack for failed http request (ethereum-optimism#995)

* dtl: log error stack for failed http request

* chore: add changeset

* Add rpc-proxy service for whitelisting JSON RPC methods to the sequencer. (ethereum-optimism#945)

* Add healthcheck endpoint for rpc-proxy
Added ethereum-nginx-proxy source
updated README and docker image build

* Check ETH_CALLS_ALLOWED is set, clean up comments, remove old Dockerfile

* Pass additional information across domains via token gateways (ethereum-optimism#824)

* feat(contracts): add from and data args to L1ERC20Gateway

fix(integration): add gasLimit to fundUser

refactor(contracts): add data to gateway events
add changeset

fix(integration): provide data in outboundTransfer

refactor(contracts): reset Abs_L2TokenGateway to Abs_L2DepositedToken

refactor(contracts): fix mismatched names

* feat[contracts]: add custom gas arg to gateway

fix(contracts): take max of user vs. default gas

* fix(integrations): update ovm-eth function call

* fix(integration): remove unecessary explicit gasLimit

* test(contracts): 32kb transfer, 9MM gas

* fix(contracts): fixup comment, bytes arg last

* fix(integration): args order in integrations

* fix(contracts): remove unused L2 gas arg

* fix(contracts): limit data that can be passed to L2

* fix(integration): better tests for data length

* test: check for error on too large data

* Experimental: specify gaslimit in before hook

* fix(integration): add l2 gas argument

* fix: increase gas on fundUser

* fix(contracts): remove duplicate max size limit

* fix(integration): fine tune gas amounts

* lint

* fix: large data test

* fix(integration): set gas closer to real cost

* fix(contracts): remove unused bridge variables
These variables were the default gas amounts for cross domain messages

* fix(contracts): Reorder args

Place dynamic length args last

* fix(integration): update estimateGas values

* fix(integration): reset eth withdraw estimate to 21000

* fix(integration): update expected gas amount

* fix(integration): reduce gas amount for ETH withdraw

* More consistent style for Constant values (ethereum-optimism#991)

* chore(contracts): make container addresses be constants
chore(contracts): consistent style for constant vars

* chore(contracts): add internal on predeploy constants

* feat: deployment config for fee oracle contract (ethereum-optimism#936)

* feat[contracts]: add GasPriceOracle w/o predeploy

Based on ethereum-optimism#912

* feat[contracts]: congestion price oracle

* chore: add changeset

* contracts: gas price oracle (ethereum-optimism#917)

* contracts: gas price oracle

* tests: update

* fees: fix tests

* contracts: simplify gas price oracle

* lint: fix

* test: execution price is at the 1st storage slot

* chore: rename predeploy to GasPriceOracle

* chore: rename gas price oracle test name

Co-authored-by: Mark Tyneway <[email protected]>
Co-authored-by: Georgios Konstantopoulos <[email protected]>

* Add an L2 deploy script for gas oracle contract

* Add a kovan deployment artifact

* Add deployment to readme

* Add extra validation & initial execution price

* Update README.md

* Fix execution price logic

* Perform new deployment with final contract

* contracts: better require in ovm gas price oracle

* Deploy L2GasPriceOracle

* Update contract to use new fee logic & rename to gas

* Deploy updated contract

* Fix lint

* gas price oracle: do not restrict gas price

* gas price oracle: new deployment

* tests: delete dead test

Co-authored-by: smartcontracts <[email protected]>
Co-authored-by: Mark Tyneway <[email protected]>
Co-authored-by: Georgios Konstantopoulos <[email protected]>

* ops: expose debug namespace (ethereum-optimism#1007)

* develop merge fixes

* refactor[l2geth]: queue origin type (ethereum-optimism#975)

* refactor: queueOrigin type

* Convert queueOrigin to uint8 in encode

* Add changeset

* Regenerate json marshall

* style: combine lines

* Add Stringer for QueueOrigin

* Turn QueueOrigin into uint8

* l2geth: gen tx meta fix

* l2geth: gen tx meta fix

* lint

Co-authored-by: Mark Tyneway <[email protected]>

* fix(sync-service): prevent underflows (ethereum-optimism#1015)

* fix(sync-service): prevent underflows

* chore: add changeset

* chore: remove dead confirmation depth

* chore: remove eth1conf depth from rollup config

* test: remove duplicate value in array (ethereum-optimism#1014)

* ci: tag docker image for canary with abbreviated GITHUB_SHA (ethereum-optimism#1006)

* ci: tag docker image for canary with abbreviated GITHUB_SHA

* ci: update from 6 bytes to 8 bytes of abbreviation

* refactor: improve logging for transactions being submitted to chain with gasPrice (ethereum-optimism#1016)

* refactor: improve logging for transactions being submitted to chain with gasPrice

* lint: apply lint autofixes

* dtl: remove stringify from db logic + more overflow protection (ethereum-optimism#1010)

* dtl: remove stringify from db logic

* l2geth: overflow protection

* dtl: overflow protection

* chore: add changeset

* ci: upload logs for failed integration tests (ethereum-optimism#1020)

* fix(dtl): improve slow blocking JSON parsing that occurs during l2 sync (ethereum-optimism#1019)

The use of eth_getBlockRange returns a large response which is very
slow to parse in ethersjs, and can block the event loop for upwards
of multiple seconds.

When this happens, incoming http requests will likely timeout and fail.

Instead, we will parse the incoming http stream directly with the bfj
package, which yields the event loop periodically so that we don't
fail to serve requests.

* fix: lint errors in dtl (ethereum-optimism#1025)

* fix[dtl]: fix dtl bug breaking verifiers (ethereum-optimism#1011)

* fix[dtl]: fix dtl bug breaking verifiers

* tweaks so tests pass

* chore: add changeset

* fix: deterministic blockhashes (ethereum-optimism#1032)

* config: set etherbase

* l2geth: add deterministic clique key

* l2geth: default value

* chore: add changeset

* test: add sync test for deterministic blockhash

Co-authored-by: Kevin Ho <[email protected]>

* Version Packages (ethereum-optimism#978)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* ci: add sync test's own workflow (ethereum-optimism#1031)

* fix(dtl): incorrect parsing of eth_getBlockRange result (ethereum-optimism#1037)

* Version Packages (ethereum-optimism#1045)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: no gas refund (ethereum-optimism#1043)

* l2geth: remove the gas refund

* chore: add changeset

* refactor[contracts]: remove one-off GasPriceOracle deployment file (ethereum-optimism#1046)

* refactor[contracts]: remove one-off gpo deployment

* chore: add changeset

* feat[contracts]: introduce new L1ChugSplashProxy contract (ethereum-optimism#1009)

* feat[contracts]: add L1ChugSplashProxy

* improve comments slightly

* start adding tests

* add more tests

* make the system pausable

* added another test

* add some extra comments

* Update packages/contracts/test/contracts/chugsplash/L1ChugSplashProxy.spec.ts

Co-authored-by: Maurelian <[email protected]>

* Update packages/contracts/test/contracts/chugsplash/L1ChugSplashProxy.spec.ts

Co-authored-by: Maurelian <[email protected]>

* chore: add changeset

* address review feedback

Co-authored-by: Maurelian <[email protected]>

* feat[contracts]: add sequencer fee wallet (ethereum-optimism#1029)

* wip: first draft of the fee wallet

* add fee wallet to dump

* rename to sequencer vault

* add L1 fee wallet to geth config

* add unit tests

* fix geth linting error

* add a basic integration test

* fix broken integration test

* add test for correct storage slot

* add integration test for fee withdrawal

* fix typo in integration tests

* fix a bug bin integration tests

* Update OVM_SequencerFeeVault.sol

* fix bug in contract tests

* chore: add changeset

* fix bug in contract tests

* build(deps): bump glob-parent from 5.1.1 to 5.1.2 (ethereum-optimism#1036)

Bumps [glob-parent](https://github.com/gulpjs/glob-parent) from 5.1.1 to 5.1.2.
- [Release notes](https://github.com/gulpjs/glob-parent/releases)
- [Changelog](https://github.com/gulpjs/glob-parent/blob/main/CHANGELOG.md)
- [Commits](gulpjs/glob-parent@v5.1.1...v5.1.2)

---
updated-dependencies:
- dependency-name: glob-parent
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: smartcontracts <[email protected]>
Co-authored-by: Liam Horne <[email protected]>

* fix: predeploy gasprice oracle (ethereum-optimism#1039)

* l2geth: delete extra config options

* l2geth: stop using extra config options

* l2geth: more stop using extra config options

* chore: add changeset

* l2geth: add new config for gpo owner

* chore: add changeset

* l2geth: fix tests

* tests: fix build

* l2geth: optimize loops (ethereum-optimism#1027)

* l2geth: optimize loops

* l2geth: stop ticker when done

* l2geth: don't wait for first tick

* chore: add changeset

* Enable custom tagging of release docker image (ethereum-optimism#1048)

* ci: enable custom tagging of release docker image

* ci: refactor to add prerelease prefix for secuirty

* doc: typo

* ci: fix indentation issue of canary workflow

* ci: fix typo with GITHUB_SHA

* fix: typo in USE_HARDHAT config (ethereum-optimism#1023)

* fix: abi encoded tx (ethereum-optimism#1049)

* contracts: don't double rlp decode

* chore: add changeset

* lint: fix

* deps: update

* linting: cleanup

* feat: contracts: use selector

* fix: contracts: use typescript

* contracts: use interface

* l2geth: bump to go 1.15 (ethereum-optimism#1058)

* l2geth: bump to go 1.15

* chore: add changeset

* Change monotonicity band-aid code to log warnings not errors (ethereum-optimism#1060)

* refactor: change monotonicity band-aid code to log warnings not errors

* build: add changeset

* feat(contracts, l2geth): native ETH value support for ovmCALL (ethereum-optimism#1038)

* feat(contracts): add ovmCALL-types with native value

* add ovmCALLVALUE context

* add ovmBALANCE

* test success and revert cases

* test empty contract case

* chore: lint

* test(integration-tests): ovmCALL-types with value (compiler and wrapper)

* fix ovmDELEGATECALL type, update tests

* add ovmSELFBALANCE

* fix ovmDELEGATECALL jumping to CALL

* chore: lint

* fix(contracts): account for intrinsic gas of OVM_ETH sends

* fix(contracts): merge conflict bug

* fix(contracts): update gas benchmark

* feat(contracts, integration-tests): use new value-compatible compiler

* feat(contracts,l2geth): support value calls in OVM_ECDSAContractAccount

* fix(contracts): ovmDELEGATECALL does not change message context

* feat(contracts): sending value between EOAs

* test(integration-tests): ovmDELEGATECALL preserves ovmCALLVALUE

* test(integration-tests): assert ovmSELFBALANCEs correct

* test(integration-tests): intrinsic gas for eth value calls

* test(integration-tests): update gas values

* chore(contracts): lint

* feat(contracts, l2geth): eth_calls with nonzero value

* chore: minor fixups and comments based on PR feedback

* test(integration-tests): add requested tests from PR reviews

* test(integration-tests): ovmSELFBALANCE is preserved in ovmDELEGATECALLs

* fix(contracts): fix bug where ovmDELEGATECALL could fail if balance was lower than the ovmCALLVALUE

* chore: add changeset

* fix(contracts): update intrinsic gas for worst-case value sends

* chore: address final PR nits/improvements

Co-authored-by: Kelvin Fichter <[email protected]>

* Add erc1271 support to contract account (ethereum-optimism#1052)

* add ERC1271 support, failing unit tests

* add integration test for isValidSignature

* remove .only

* lint

* add changeset

* clean up 1271 tests and lint

* switch back to using waffle wallet

* lint

* fix import

* feat[contracts]: slightly better account funding for hardhat accounts (rebased) (ethereum-optimism#1065)

* feat[contracts]: better account funding for hardhat accounts

* add a sleep to avoid any potential problems

* chore: add changeset

* fix: bug with gas estimation in funding step

* fix: limit to 20 accounts max

Co-authored-by: Kelvin Fichter <[email protected]>

* Ensure Sentry is correctly set up for DTL and MR (ethereum-optimism#1054)

* refactor: add logger and metrics to options for BaseService

* refactor: thread sentryOptions through from message-relayer into BaseService

* refactor: ensure DTL Logger is using Sentry for errors

* style: lint base-service.ts

* refactor: init Sentry on batch-submitter too

* refactor: init Sentry on message-relayer too

* refactor: pass in basic logger to MessageRelayerService

* build: provide changeset

* fix: correct usage of use-sentry boolean config

* refactor: appropriately type loggingOptions

* build: add @sentry/node

* build: add @sentry/node to message-relayer and fix linting issue

* Add more logging information to monotonicity violation logs (ethereum-optimism#1066)

* refactor: log idx of monotonicity violation from batch

* build: add changeset

* temporarily disable hardhat example tests (ethereum-optimism#1071)

* fix: monotonicity auto healer (ethereum-optimism#1070)

* fix: monotonicity auto healer

* add: changeset

* Version Packages (ethereum-optimism#1053)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Standard token bridge (ethereum-optimism#988)

* Remove abstract token gateway and deposited token implementations

* Further simplification of bridge contracts

* Standart token bridge and L2 token implementation

* Fix spacing

* Implement case when a bad deposit happens to a nonexistent L1<>L2 token pair

* Use SafeMath in common token bridge accounting

* test(contracts): fix finalizeWithdrawal test

* fix(contracts): use SafeERC20 on token deposits

* Rename OVM_L1ERC20Gateway to OVM_L1ERC20Bridge contract

* Rename iOVM_L1ERC20Gateway to iOVM_L1ERC20Bridge contract

* Cleanup gateway to bridge rename

* Better name for the mapping holding l1->l2 deposit amounts

* Use OZ SafeMath

* Rename local variables in OVM_L2DepositedERC20 from gateway to bridge

* Merge ETH and ERC20 bridge contracts

* Rename OVM_L1ERC20Bridge to OVM_L1StandardBridge and fix tests from merging the ETH and ERC20 bridges

* Better name for iAbs_BaseCrossDomainMessenger -> iOVM_CrossDomainMessenger

* Correct the bounce back of deposit sender and recipient properties

* Remove obsoleted event from OVM_L2DepositedERC20

* chore(contracts): change references from ETHGateway to Bridge

* Fix a linting error

* fix(contracts): add bridge to deployer

* Split off ERC20Bridge interface for the purposes
of being reused in custom ERC20 bridges

* Split off interface natspec definitions

* Draft version of OVM_L2DepositedERC20 splitted into a standard L2 erc20: L2StandardERC20 and
a common L2 bridge: OVM_L2StandardBridge

* style(contracts): define L1_ETH_ADDRESS as constant

* test(integration): update interface to use depositETH

* test(contracts): fix OVM_L1StandardBridge tests

* test(contracts): fix L2 Standard Bridge tests

* test(contracts): lint and remove an obsolete test case

* Fix modifier check to comply with the L2 bridge distinction from L2 token

* Simplify address <> interface casting in bridges

* Ensure natspec comments are correct
also add l1 and l2 token params to WithdrawalInitiated event for consistency

* Fix issues in L1 and L2 bridges to ensure
cross domain messages are sent only between the two bridges
also adjusted withdrawals to send to either finalizeETHWithdrawal or finalizeERC20Withdrawal
depending on which asset is being withdrawn

* Remove AddressManager from the L1 standard bridge

* REVERT ME: instruments cross domain enabled

* fix(contracts): remove Address Manager from L1 Bridge

* feat(contracts): make L2 Standard Bridge a predeploy

* WIP: update deployments for standard bridges

* WIP: update deployments for standard bridges

* l2geth: TEMP log contract calls

* chore(l2geth): replace eth gateway with standard bridge

* fix(contracts): make contract-deployment/config work

* WIP fix(integration): update integration tests for bridge

* Remove ovmEth from L1 Standard bridge as obsoleted

* Separate ERC20 standard implementation from L2 bridge

* Formatting fixes

* chore(l2geth): replace eth gateway with standard bridge

* Revert "REVERT ME: instruments cross domain enabled"

This reverts commit d5bb8f8.

* fix: lint ts

* Implement EIP-165 in the Standard L2 ERC20 token
Also switch that to be based off the OpenZeppelin default implementation plus mint and burn
Additionally remove the obsoleted iOVM_ERC20

* fix(contracts): add deployment check on bridge proxy
fix(contracts): whitespace
fix(contracts): init bridge implementation with non-zero address

* Remove dependency on Ownable contract for the StandardERC20 token on L2

* fix(contracts): update deployment scripts

* fix: lint

* remove debugging code

* fix: correct rpc get balance slot

* restore l2 cross domain messenger

* fix: lint

* Add a test for a non compliant token deposit

* Only allow EOAs to deposit ETH and ERC20

* Add comments and tests for ERC165 implementation

* Decide against using explicit ETH MOCK address as we're not using it for checks

* Fix linting issues

* Add onlyEOAContract restriction to standard bridge withdrawals

* Update codehashes in L2 Standard bridge

* fix(ops): remove unintentionally added file

* feat(contracts): add expectApproxGasCost function

* fix(integration): proper arrayify input on fundUser

* fix(integration): proper gas value checks

* Revert "Add onlyEOAContract restriction to standard bridge withdrawals"

This reverts commit 2713c06ceb2609e4f13718e1034a4d76210d9758.

* fix(contracts): removed unused expectApproxGasCost for now

* fix(contracts): update OVM_SequencerFeeVault for bridge changes

* lint

* Update deployment for L1 Bridge w/ ChugSplash

* Revert "l2geth: TEMP log contract calls"

This reverts commit 21d42259278449f221bf34605162229b3d9d4fa9.

* Apply suggestions from code review

* Apply suggestions from code review

* fix(contracts): deploy with chugsplash proxy

* fix(contracts): add working bridge and chugsplash proxy deployment

* fix(contracts,integration): 500k gas for depositETH

* comment(contracts): describe failed deposit handling on l2

* Apply suggestions from code review

Co-authored-by: ben-chain <[email protected]>

* docs: add changeset

* fix(integration): set working l2 gas amount on funduser

* test(integration): add receive() test

* fix(contracts): reset receive to 1.2MM l2 gas

* test(examples): skip l1-l2 example test for now

* fix(contracts): drop hardcoded gas to 500k in receive()

* fix(contracts): use abi.encodeWithSignature

* fix(contracts): resolve merge conflicts

* feat(integration): add expectApprox for flexible gas testing

* fix(integration): fix failing gas tests

* fix: incorrect l2 gas for deposit

* Update utils.ts

* fix(workflow): disable l1-l2 example until npm imports are fixed

* chore: final round of PR review nits and tests

Co-authored-by: Maurelian <[email protected]>
Co-authored-by: Mark Tyneway <[email protected]>
Co-authored-by: ben-chain <[email protected]>
Co-authored-by: Kelvin Fichter <[email protected]>

* fix: comment out codeowners (ethereum-optimism#1073)

* fix: use predeploy constant lib for em wrapper (ethereum-optimism#1075)

* fix: use predeploy constant lib for em wrapper

* chore: add changeset

* fix[l2geth]: off-by-one sometimes breaking replica sync (ethereum-optimism#1082)

* fix[l2geth]: off-by-one sometimes breaking replica sync

* chore: add changeset

* fix(l2geth): Log 'end of OVM execution' correctly (ethereum-optimism#1080)

* refactor[contracts]: move account contracts to predeploy folder (ethereum-optimism#1085)

* refactor[contracts]: move account contracts to predeploy folder

* chore: add changeset

* maintenance[contracts]: rename precompiles test folder to predeploys (ethereum-optimism#1086)

* fix[bs]: disambiguate generic submission errors (ethereum-optimism#1051)

* fix[bs]: disambiguate generic submission errors

* add cases for errors

* separate out errors from transaction reverts with reasons

* remove extraneous errors

* WETH deposit and withdraw on OVM_ETH (ethereum-optimism#1083)

* feat(contracts): add no-op WETH9 functionality to OVM_ETH

* working WETH deposit and withdraw + tests

* add changeset

* address PR feedback

* update WETH9 contract implementation

* add fallback to WETH9

* add fallback and revert withdraw test

* update nit comment

Co-authored-by: ben <[email protected]>

* Also move the accounts interface to iOVM/predeploys (ethereum-optimism#1087)

* refactor[contracts]: move account interface to predeploy folder

* chore: add changeset

* Version Packages (ethereum-optimism#1089)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: use -z flag for var unset in canary

* Use Eslint instead of Tslint (ethereum-optimism#1005)

* removed tslint

* forgot to commit files

* made .eslintrc.js consistent for all subdirs and other cleanup

* [removed] includes and files keys from tsconfig.json

* removed file level linting exceptions and added details to line level

* added changeset

* fixed newly introduced linting errors from rebase

* enable json import for batch submitter

* removed ecdsa-coder

* maybe a tsconfig issue?

* Update deploy.ts

Co-authored-by: smartcontracts <[email protected]>
Co-authored-by: platocrat <[email protected]>

* metrics[batch-submitter]: add new batch submitter metrics (ethereum-optimism#1074)

* metrics[batch-submitter]: add new batch submitter metrics

* chore: changeset

* account for failed submissions

* Fix canary publishing (ethereum-optimism#1093)

* ci: fix custom docker tag

* ci: use new env file

* ci: use outputs from previous job

* ci: fix headers of jobs

* ci: inherit canary tag from builder

* feat[ci]: upload logs for sync tests if failure (ethereum-optimism#1098)

* deploy: goerli 0.4.0 (ethereum-optimism#1099)

* deployments: goerli 0.4.0 rc

* readme: update

* chore: add changeset

* fix[dtl]: defend against RPC provider missing events (ethereum-optimism#1084)

* fix[dtl]: defend against RPC provider missing events

* chore: add changeset

* respond to review comments

* better error handling for missing handlers

* deploy: kovan v.4.0 rc (ethereum-optimism#1101)

* deploy: kovan v0.4.0 rc

* chore: add changeset

* readme: update

* maintenance[monorepo]: first pass update to README (ethereum-optimism#1106)

* maintenance[monorepo]: first pass update to README

Doing some relatively minor updates to the README just to clean things up a bit.

* replying to review comments

* Move the metric prefix string to a label (ethereum-optimism#1047)

Added changeset and fixes
Changeset to patch

* fix[smock]: add support for hardhat 2.4.0 (ethereum-optimism#1112)

* fix[smock]: add support for hardhat 2.4.0

* chore: add changeset

* lint: fix

* build(deps): bump hosted-git-info from 2.8.8 to 2.8.9 (ethereum-optimism#1064)

Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](npm/hosted-git-info@v2.8.8...v2.8.9)

---
updated-dependencies:
- dependency-name: hosted-git-info
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: smartcontracts <[email protected]>

* Misc. small improvements to README (ethereum-optimism#1115)

* Update README.md

* Update README.md

* fix[dtl]: use the same L2 chain ID everywhere (ethereum-optimism#1122)

* fix[dtl]: use the same L2 chain ID everywhere

* chore: add changeset

* fix: make sync tests only on workflow dispatch (ethereum-optimism#1123)

* fix[dtl]: remove old stringification function (ethereum-optimism#1134)

* fix[dtl]: remove old stringification function

* chore: add changeset

* fix[dtl]: log server errors as ERROR instead of INFO (ethereum-optimism#1133)

* fix[dtl]: log server errors as ERROR instead of INFO

* chore: add changeset

* Contracts: connectL1Contracts & connectL2Contracts  (ethereum-optimism#713)

* Contracts: connect-contracts

* Trying to resolve build problems

* connect-contracts build working

* Adds artifacts-ovm back to gitignore

* Removes incorrect changes

* Adds copy-artifacts script

* Adds test file (not working yet)

* fix: incorrect contract instantiation

* Improves tests and removes old deployment versions

* Single source of truth for predeploy addresses

* Reverts deployments/README.md

* Makes connect-contracts more DRY

* Adds missing @ethersproject/abstract-signer dependency

* Adds argument evaluation

* Adds L1Contracts and L2Contracts types

* Attempts removing artifacts-ovm again

* Adds webpack config (not working yet)

* build: add artifacts to dist (ethereum-optimism#776)

* Updates lint rule

* Adds l2 imports

* Fixes dependency tree bug

* Removes webpack stuff

* Fixing package.json issues and adds .DS_Store to gitignore

* Removes test-contracts script

* Reverting script change

* Adds comments

* Adds comment

* Renames deployments folders

* Fixes linting errors

* Generates markdown

* build: add deployments directory to Dockerfiles

* Removes unneeded contracts, improves error handling and tests

* Adds changeset

* yarn.lock

* Removes console.log

* Changes from minor to patch version

* Fixes lint errors

Co-authored-by: Kelvin Fichter <[email protected]>
Co-authored-by: Liam Horne <[email protected]>
Co-authored-by: Georgios Konstantopoulos <[email protected]>

* fix: prevent overflow in abi encoding (ethereum-optimism#1135)

* l2geth: prevent overflow in abi encoding to ovm codec tx

* chore: add changeset

* tests: replica syncing (ethereum-optimism#981)

* [wip] add l2_dtl and replica images

* passing basic dummy tx test

* add erc20 test

* add sync test to ci

Co-authored-by: Mark Tyneway <[email protected]>

* fix[relayer]: update exported files list in package.json (ethereum-optimism#1138)

* fix[relayer]: update exported files

* chore: add changeset

* fix: import path (ethereum-optimism#1141)

* fix: correct import path for altered contract path

* chore: add changeset

* refactor: improve logging for batch submission timeout scenarios (ethereum-optimism#1120)

* Add highest L1 and L2 block number Gauge metrics to DTL (ethereum-optimism#1125)

* build: add prom-client to data-transport-layer

* refactor: thread metrics more carefully through data-transport-layer; add two new metrics

* style: fix some style issues

* refactor: make metrics mandatory

* refactor: move metrics register code to top of file

* style: apply linting

* refactor: move promethesus initialization after express

* refactor: move promBundle call up, provide registry

* build: add changeset

* Improve Watcher ability to find transactions (ethereum-optimism#1107)

* remove listeners and use loop to find tx receipt

* add yarn ready

* moved filters inside loop

* [added] changeset

* Add minimal vscode settings and extensions (ethereum-optimism#1109)

* chore: add minimal vscode settings and extensions

* chore: Add "files.trimTrailingWhitespace" to vscode native config

* chore: replace vscode prettier plugin with eslint plugin

* fix[contracts]: remove part of MultiMessageRelayer deployment (ethereum-optimism#1144)

* fix[contracts]: remove part of MultiMessageRelayer deployment

* chore: add changeset

* Define L1 Starting block via OwnershipTransferred rather than AddressSet (ethereum-optimism#1129)

* Update service.ts

* Create thirty-years-look.md

Co-authored-by: smartcontracts <[email protected]>

* Easy fix for broken watchers (ethereum-optimism#1121)

* Easy fix for broken watchers

* Ran yarn changeset

Co-authored-by: Liam Horne <[email protected]>

* feat: go packages (ethereum-optimism#1111)

* go: add utils module

* readme: update

* Version Packages (ethereum-optimism#1094)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* build: add husky pre-commit hook to lint (ethereum-optimism#1146)

* feat[contracts]: add mainnet deploy script (ethereum-optimism#1147)

* Add mainnet deploy script

* Update mainnet.sh

* Address PR review feedback

* feat: mainnet contract deployment 0.4.0 (ethereum-optimism#1148)

* feat: mainnet contract deployment 0.4.0

* feat: deployments readme

* chore: add changeset

* contracts: remove dead contract

* contracts: remove dead config

* tests: fix to not test for old contracts

* feat: `rollup gasPrices` RPC endpoint (ethereum-optimism#1136)

* feature: l2geth  endpoint

* chore: add changeset

Co-authored-by: Liam Horne <[email protected]>

* Adds l2 standard bridge to contracts markdown file (ethereum-optimism#1151)

* Version Packages (ethereum-optimism#1150)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Add more info about our branching strategy to the README (ethereum-optimism#1114)

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Remove references to OVM_L1ETHGateway in deployments and readme (ethereum-optimism#1119)

Co-authored-by: Maurelian <[email protected]>
Co-authored-by: smartcontracts <[email protected]>
Co-authored-by: Elena Gesheva <[email protected]>
Co-authored-by: ben-chain <[email protected]>
Co-authored-by: Mark Tyneway <[email protected]>
Co-authored-by: Georgios Konstantopoulos <[email protected]>
Co-authored-by: Karl Floersch <[email protected]>
Co-authored-by: Rajiv Patel-O'Connor <[email protected]>
Co-authored-by: rajivpo <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kevin Ho <[email protected]>
Co-authored-by: Ben Wilson <[email protected]>
Co-authored-by: Liam Horne <[email protected]>
Co-authored-by: Tim Myers <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Annie Ke <[email protected]>
Co-authored-by: platocrat <[email protected]>
Co-authored-by: Matt Masurka <[email protected]>
Co-authored-by: CAPtheorem <[email protected]>
Co-authored-by: Alejandro Santander <[email protected]>
  • Loading branch information
1 parent 71f64d0 commit 8f83671
Show file tree
Hide file tree
Showing 224 changed files with 9,902 additions and 6,363 deletions.
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

yarn lint:check
12 changes: 12 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp

// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"dbaeumer.vscode-eslint",
"editorconfig.editorconfig",
"juanblanco.solidity",
"golang.go",
],
}
11 changes: 11 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"editor.formatOnSave": true,
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
},
"eslint.nodePath": "./node_modules/eslint/bin/",
"eslint.format.enable": true,
"editorconfig.generateAuto": false,
"files.trimTrailingWhitespace": true,
}
18 changes: 9 additions & 9 deletions examples/l1-l2-deposit-withdrawal/test/example.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const factory = (name, ovm = false) => {
}
const factory__L1_ERC20 = factory('ERC20')
const factory__L2_ERC20 = factory('L2DepositedERC20', true)
const factory__L1_ERC20Gateway = getContractFactory('OVM_L1ERC20Gateway')
const factory__L1StandardBridge = getContractFactory('OVM_L1StandardBridge')


describe(`L1 <> L2 Deposit and Withdrawal`, () => {
Expand Down Expand Up @@ -50,7 +50,7 @@ describe(`L1 <> L2 Deposit and Withdrawal`, () => {

let L1_ERC20,
L2_ERC20,
L1_ERC20Gateway
L1StandardBridge

before(`deploy contracts`, async () => {
// Deploy an ERC20 token on L1.
Expand All @@ -75,8 +75,8 @@ describe(`L1 <> L2 Deposit and Withdrawal`, () => {

await L2_ERC20.deployTransaction.wait()

// Create a gateway that connects the two contracts.
L1_ERC20Gateway = await factory__L1_ERC20Gateway.connect(l1Wallet).deploy(
// Create a bridge that connects the two contracts.
L1StandardBridge = await factory__L1StandardBridge.connect(l1Wallet).deploy(
L1_ERC20.address,
L2_ERC20.address,
l1MessengerAddress,
Expand All @@ -85,12 +85,12 @@ describe(`L1 <> L2 Deposit and Withdrawal`, () => {
}
)

await L1_ERC20Gateway.deployTransaction.wait()
await L1StandardBridge.deployTransaction.wait()
})

describe('Initialization and initial balances', async () => {
it(`should initialize L2 ERC20`, async () => {
const tx = await L2_ERC20.init(L1_ERC20Gateway.address, { gasPrice: 0 })
const tx = await L2_ERC20.init(L1StandardBridge.address, { gasPrice: 0 })
await tx.wait()
const txHashPrefix = tx.hash.slice(0, 2)
expect(txHashPrefix).to.eq('0x')
Expand All @@ -107,15 +107,15 @@ describe(`L1 <> L2 Deposit and Withdrawal`, () => {
describe('L1 to L2 deposit', async () => {
let l1Tx1

it(`should approve 1234 tokens for ERC20 gateway`, async () => {
const tx = await L1_ERC20.approve(L1_ERC20Gateway.address, 1234)
it(`should approve 1234 tokens for ERC20 bridge`, async () => {
const tx = await L1_ERC20.approve(L1StandardBridge.address, 1234)
await tx.wait()
const txHashPrefix = tx.hash.slice(0, 2)
expect(txHashPrefix).to.eq('0x')
})

it(`should deposit 1234 tokens into L2 ERC20`, async () => {
l1Tx1 = await L1_ERC20Gateway.deposit(1234, { gasPrice: 0 })
l1Tx1 = await L1StandardBridge.deposit(1234, { gasPrice: 0 })
await l1Tx1.wait()
const txHashPrefix = l1Tx1.hash.slice(0, 2)
expect(txHashPrefix).to.eq('0x')
Expand Down
29 changes: 29 additions & 0 deletions go/utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# utils

This package is meant to hold utilities used by
[Optimistic Ethereum](https://github.com/ethereum-optimism/optimism) written in
Golang.

## Packages

### Fees

Package fees includes helpers for dealing with fees on Optimistic Ethereum

#### `EncodeTxGasLimit(data []byte, l1GasPrice, l2GasLimit, l2GasPrice *big.Int) *big.Int`

Encodes `tx.gasLimit` based on the variables that are used to determine it.

`data` - Calldata of the transaction being sent. This data should *not* include the full signed RLP transaction.

`l1GasPrice` - gas price on L1 in wei

`l2GasLimit` - amount of gas provided for execution in L2. Notably, accounts are charged for execution based on this gasLimit, even if the gasUsed ends up being less.

`l2GasPrice` - gas price on L2 in wei

#### `DecodeL2GasLimit(gasLimit *big.Int) *big.Int`

Accepts the return value of `eth_estimateGas` and decodes the L2 gas limit that
is encoded in the return value. This is the gas limit that is passed to the user
contract within the OVM.
113 changes: 113 additions & 0 deletions go/utils/fees/rollup_fee.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package fees

import (
"math/big"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params"
)

// overhead represents the fixed cost of batch submission of a single
// transaction in gas.
const overhead uint64 = 4200 + 200*params.TxDataNonZeroGasEIP2028

// feeScalar is used to scale the calculations in EncodeL2GasLimit
// to prevent them from being too large
const feeScalar uint64 = 10_000_000

// TxGasPrice is a constant that determines the result of `eth_gasPrice`
// It is scaled upwards by 50%
// tx.gasPrice is hard coded to 1500 * wei and all transactions must set that
// gas price.
const TxGasPrice uint64 = feeScalar + (feeScalar / 2)

// BigTxGasPrice is the L2GasPrice as type big.Int
var BigTxGasPrice = new(big.Int).SetUint64(TxGasPrice)
var bigFeeScalar = new(big.Int).SetUint64(feeScalar)

const tenThousand = 10000

var BigTenThousand = new(big.Int).SetUint64(tenThousand)

// EncodeTxGasLimit computes the `tx.gasLimit` based on the L1/L2 gas prices and
// the L2 gas limit. The L2 gas limit is encoded inside of the lower order bits
// of the number like so: [ | l2GasLimit ]
// [ tx.gaslimit ]
// The lower order bits must be large enough to fit the L2 gas limit, so 10**8
// is chosen. If higher order bits collide with any bits from the L2 gas limit,
// the L2 gas limit will not be able to be decoded.
// An explicit design goal of this scheme was to make the L2 gas limit be human
// readable. The entire number is interpreted as the gas limit when computing
// the fee, so increasing the L2 Gas limit will increase the fee paid.
// The calculation is:
// l1GasLimit = zero_count(data) * 4 + non_zero_count(data) * 16 + overhead
// roundedL2GasLimit = ceilmod(l2GasLimit, 10_000)
// l1Fee = l1GasPrice * l1GasLimit
// l2Fee = l2GasPrice * roundedL2GasLimit
// sum = l1Fee + l2Fee
// scaled = sum / scalar
// rounded = ceilmod(scaled, tenThousand)
// roundedScaledL2GasLimit = roundedL2GasLimit / tenThousand
// result = rounded + roundedScaledL2GasLimit
// Note that for simplicity purposes, only the calldata is passed into this
// function when in reality the RLP encoded transaction should be. The
// additional cost is added to the overhead constant to prevent the need to RLP
// encode transactions during calls to `eth_estimateGas`
func EncodeTxGasLimit(data []byte, l1GasPrice, l2GasLimit, l2GasPrice *big.Int) *big.Int {
l1GasLimit := calculateL1GasLimit(data, overhead)
roundedL2GasLimit := Ceilmod(l2GasLimit, BigTenThousand)
l1Fee := new(big.Int).Mul(l1GasPrice, l1GasLimit)
l2Fee := new(big.Int).Mul(l2GasPrice, roundedL2GasLimit)
sum := new(big.Int).Add(l1Fee, l2Fee)
scaled := new(big.Int).Div(sum, bigFeeScalar)
rounded := Ceilmod(scaled, BigTenThousand)
roundedScaledL2GasLimit := new(big.Int).Div(roundedL2GasLimit, BigTenThousand)
result := new(big.Int).Add(rounded, roundedScaledL2GasLimit)
return result
}

func Ceilmod(a, b *big.Int) *big.Int {
remainder := new(big.Int).Mod(a, b)
if remainder.Cmp(common.Big0) == 0 {
return a
}
sum := new(big.Int).Add(a, b)
rounded := new(big.Int).Sub(sum, remainder)
return rounded
}

// DecodeL2GasLimit decodes the L2 gas limit from an encoded L2 gas limit
func DecodeL2GasLimit(gasLimit *big.Int) *big.Int {
scaled := new(big.Int).Mod(gasLimit, BigTenThousand)
return new(big.Int).Mul(scaled, BigTenThousand)
}

func DecodeL2GasLimitU64(gasLimit uint64) uint64 {
scaled := gasLimit % tenThousand
return scaled * tenThousand
}

// calculateL1GasLimit computes the L1 gasLimit based on the calldata and
// constant sized overhead. The overhead can be decreased as the cost of the
// batch submission goes down via contract optimizations. This will not overflow
// under standard network conditions.
func calculateL1GasLimit(data []byte, overhead uint64) *big.Int {
zeroes, ones := zeroesAndOnes(data)
zeroesCost := zeroes * params.TxDataZeroGas
onesCost := ones * params.TxDataNonZeroGasEIP2028
gasLimit := zeroesCost + onesCost + overhead
return new(big.Int).SetUint64(gasLimit)
}

func zeroesAndOnes(data []byte) (uint64, uint64) {
var zeroes uint64
var ones uint64
for _, byt := range data {
if byt == 0 {
zeroes++
} else {
ones++
}
}
return zeroes, ones
}
104 changes: 104 additions & 0 deletions go/utils/fees/rollup_fee_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package fees

import (
"math/big"
"testing"

"github.com/ethereum/go-ethereum/params"
)

var l1GasLimitTests = map[string]struct {
data []byte
overhead uint64
expect *big.Int
}{
"simple": {[]byte{}, 0, big.NewInt(0)},
"simple-overhead": {[]byte{}, 10, big.NewInt(10)},
"zeros": {[]byte{0x00, 0x00, 0x00, 0x00}, 10, big.NewInt(26)},
"ones": {[]byte{0x01, 0x02, 0x03, 0x04}, 200, big.NewInt(16*4 + 200)},
}

func TestL1GasLimit(t *testing.T) {
for name, tt := range l1GasLimitTests {
t.Run(name, func(t *testing.T) {
got := calculateL1GasLimit(tt.data, tt.overhead)
if got.Cmp(tt.expect) != 0 {
t.Fatal("Calculated gas limit does not match")
}
})
}
}

var feeTests = map[string]struct {
dataLen int
l1GasPrice uint64
l2GasLimit uint64
l2GasPrice uint64
}{
"simple": {
dataLen: 10,
l1GasPrice: params.GWei,
l2GasLimit: 437118,
l2GasPrice: params.GWei,
},
"zero-l2-gasprice": {
dataLen: 10,
l1GasPrice: params.GWei,
l2GasLimit: 196205,
l2GasPrice: 0,
},
"one-l2-gasprice": {
dataLen: 10,
l1GasPrice: params.GWei,
l2GasLimit: 196205,
l2GasPrice: 1,
},
"zero-l1-gasprice": {
dataLen: 10,
l1GasPrice: 0,
l2GasLimit: 196205,
l2GasPrice: params.GWei,
},
"one-l1-gasprice": {
dataLen: 10,
l1GasPrice: 1,
l2GasLimit: 23255,
l2GasPrice: params.GWei,
},
"zero-gasprices": {
dataLen: 10,
l1GasPrice: 0,
l2GasLimit: 23255,
l2GasPrice: 0,
},
"max-gaslimit": {
dataLen: 10,
l1GasPrice: params.GWei,
l2GasLimit: 99_970_000,
l2GasPrice: params.GWei,
},
"larger-divisor": {
dataLen: 10,
l1GasPrice: 0,
l2GasLimit: 10,
l2GasPrice: 0,
},
}

func TestCalculateRollupFee(t *testing.T) {
for name, tt := range feeTests {
t.Run(name, func(t *testing.T) {
data := make([]byte, tt.dataLen)
l1GasPrice := new(big.Int).SetUint64(tt.l1GasPrice)
l2GasLimit := new(big.Int).SetUint64(tt.l2GasLimit)
l2GasPrice := new(big.Int).SetUint64(tt.l2GasPrice)

fee := EncodeTxGasLimit(data, l1GasPrice, l2GasLimit, l2GasPrice)
decodedGasLimit := DecodeL2GasLimit(fee)
roundedL2GasLimit := Ceilmod(l2GasLimit, BigTenThousand)
if roundedL2GasLimit.Cmp(decodedGasLimit) != 0 {
t.Errorf("rollup fee check failed: expected %d, got %d", l2GasLimit.Uint64(), decodedGasLimit)
}
})
}
}
5 changes: 5 additions & 0 deletions go/utils/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/ethereum-optimism/optimism/go/utils

go 1.15

require github.com/ethereum/go-ethereum v1.9.10
Loading

0 comments on commit 8f83671

Please sign in to comment.