diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 1a9b8b1e9a71c9..135008ace3ab1d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,3 +1,7 @@ +**ATTENTION: ERC-RELATED PULL REQUESTS NOW OCCUR IN [ETHEREUM/ERCS](https://github.com/ethereum/ercs)** + +-- + When opening a pull request to submit a new EIP, please use the suggested template: https://github.com/ethereum/EIPs/blob/master/eip-template.md We have a GitHub bot that automatically merges some PRs. It will merge yours immediately if certain criteria are met: diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 00000000000000..73445ef763d831 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:base", + ":disableDependencyDashboard" + ], + "prConcurrentLimit": 100, + "ignorePaths": [ + "**/assets/**" + ], + "ignoreDeps": [ + "Pandapip1/jekyll-label-action", + "ethereum/eipw-action", + "ethereum/eip-review-bot", + "ethereum/EIP-Bot" + ], + "enabled": false +} diff --git a/.github/workflows/auto-review-bot.yml b/.github/workflows/auto-review-bot.yml index 58b011066e9460..600268097b1e76 100644 --- a/.github/workflows/auto-review-bot.yml +++ b/.github/workflows/auto-review-bot.yml @@ -12,7 +12,7 @@ jobs: name: Run steps: - name: Fetch PR Number - uses: dawidd6/action-download-artifact@6765a42d86407a3d532749069ac03705ad82ebc6 + uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615 with: name: pr-number workflow: auto-review-trigger.yml @@ -24,20 +24,9 @@ jobs: - name: Auto Review Bot id: auto-review-bot - uses: Pandapip1/eip-review-bot@dist + uses: ethereum/eip-review-bot@dist + continue-on-error: true with: token: ${{ secrets.TOKEN }} config: config/eip-editors.yml pr_number: ${{ steps.save-pr-number.outputs.pr }} - - - name: Enable Auto-Merge - uses: reitermarkus/automerge@a25ea0de41019ad13380d22e01db8f5638f1bcdc - with: - token: ${{ secrets.TOKEN }} - pull-request: ${{ steps.save-pr-number.outputs.pr }} - - - name: Submit Approval - uses: hmarr/auto-approve-action@24ec4c8cc344fe1cdde70ff37e55ace9e848a1d8 - with: - github-token: ${{ secrets.TOKEN }} - pull-request-number: ${{ steps.save-pr-number.outputs.pr }} diff --git a/.github/workflows/auto-review-trigger.yml b/.github/workflows/auto-review-trigger.yml index ede3417bfb311f..45b815e390daeb 100644 --- a/.github/workflows/auto-review-trigger.yml +++ b/.github/workflows/auto-review-trigger.yml @@ -23,13 +23,13 @@ jobs: steps: - name: Write PR Number - PR Target run: echo $PR_NUMBER > pr-number.txt - if: github.event_name == 'pull_request_target' + if: github.event_name == 'pull_request_target' && ((!endsWith(github.event.sender.login, '-bot') && !endsWith(github.event.sender.login, '[bot]')) || github.event.sender.login == 'renovate[bot]') env: PR_NUMBER: ${{ github.event.number }} - name: Write PR Number - PR Review run: echo $PR_NUMBER > pr-number.txt - if: github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && !endsWith(github.event.sender.login, '-bot') && !endsWith(github.event.sender.login, '[bot]') + if: github.event_name == 'pull_request_review' && !endsWith(github.event.sender.login, '-bot') && !endsWith(github.event.sender.login, '[bot]') env: PR_NUMBER: ${{ github.event.pull_request.number }} @@ -46,13 +46,13 @@ jobs: PR_NUMBER: ${{ github.event.issue.number }} - name: Check File Existence - uses: andstor/file-existence-action@f02338908d150e00a4b8bebc2dad18bd9e5229b0 + uses: andstor/file-existence-action@20b4d2e596410855db8f9ca21e96fbe18e12930b id: check_pr_number_exists with: files: pr-number.txt - name: Save PR Number - uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 + uses: actions/upload-artifact@65d862660abb392b8c4a3d1195a2108db131dd05 if: steps.check_pr_number_exists.outputs.files_exists == 'true' with: name: pr-number diff --git a/.github/workflows/auto-stagnate-bot.yml b/.github/workflows/auto-stagnate-bot.yml index abc25f1acefb0a..25aca3bf9c9c97 100644 --- a/.github/workflows/auto-stagnate-bot.yml +++ b/.github/workflows/auto-stagnate-bot.yml @@ -2,6 +2,7 @@ on: schedule: # A job that runs every sunday at 00:00 - cron: '0 0 * * 0' + workflow_dispatch: name: Auto Stagnant Bot jobs: @@ -11,9 +12,9 @@ jobs: name: Auto Stagnant Bot steps: - name: Checkout - uses: actions/checkout@e2f20e631ae6d7dd3b768f56a5d2af784dd54791 + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f - name: Setup Node.js Environment - uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 + uses: actions/setup-node@d98fa1113850e562f83c7fc3a89c0ecd7a87fbed with: node-version: '14' - name: auto-stagnant-bot diff --git a/.github/workflows/ci-rerun-trigger.yml b/.github/workflows/ci-rerun-trigger.yml deleted file mode 100644 index 7321bf4e7db1ae..00000000000000 --- a/.github/workflows/ci-rerun-trigger.yml +++ /dev/null @@ -1,33 +0,0 @@ -on: - issue_comment: - types: - - created - -name: Continuous Integration Re-Trigger -jobs: - trigger: - runs-on: ubuntu-latest - name: Trigger - steps: - - name: Trigger - uses: actions/github-script@d556feaca394842dc55e4734bf3bb9f685482fa0 - if: github.event.issue.pull_request && contains(github.event.comment.body, '@eth-bot rerun') - with: - script: | - let pr = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: context.payload.issue.number - }); - await github.rest.pulls.update({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: context.payload.issue.number, - body: '[RETRIGGER]\n' + pr.data.body - }); - await github.rest.pulls.update({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: context.payload.issue.number, - body: pr.data.body - }); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea61f048895005..c1aa963f51d8cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: echo $MERGE_SHA > ./pr/merge_sha - name: Upload PR Number - uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 + uses: actions/upload-artifact@65d862660abb392b8c4a3d1195a2108db131dd05 with: name: pr_number path: pr/ @@ -41,23 +41,47 @@ jobs: runs-on: ubuntu-20.04 steps: - - name: Checkout EIP Repository - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - - name: Install Ruby - uses: ruby/setup-ruby@08245253a76fa4d1e459b7809579c62bd9eb718a + - name: Checkout EIPs + uses: actions/checkout@v4 with: - ruby-version: 2.6.0 - bundler-cache: true - + repository: ethereum/EIPs + path: '' + - name: Checkout ERCs + uses: actions/checkout@v4 + with: + repository: ethereum/ERCs + path: ERCs + - name: Merge Repos + run: | + mkdir -p $GITHUB_WORKSPACE/ERCs/ERCS + mkdir -p $GITHUB_WORKSPACE/ERCs/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/ERCS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/EIPS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/assets/. $GITHUB_WORKSPACE/assets + cd $GITHUB_WORKSPACE/EIPS + find . -name "erc-*.md" -type f -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE/assets + find . -name "erc-*" -type d -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE + rm -rf ERCs + - name: Setup Ruby + uses: ruby/setup-ruby@55283cc23133118229fd3f97f9336ee23a179fcf # v1.146.0 + with: + ruby-version: '3.1' # Not needed with a .ruby-version file + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + cache-version: 0 # Increment this number if you need to re-download cached gems + - name: Build with Jekyll + run: bundle exec jekyll build + env: + JEKYLL_ENV: production + - name: Build Website run: | bundle exec jekyll doctor bundle exec jekyll build - name: HTML Proofer - run: bundle exec htmlproofer ./_site --check-html --check-opengraph --report-missing-names --log-level=:debug --assume-extension --empty-alt-ignore --timeframe=6w --disable-external - + run: bundle exec htmlproofer --allow-missing-href --disable-external --assume-extension '.html' --log-level=:info --cache='{"timeframe":{"external":"6w"}}' --checks 'Links,Images,Scripts,OpenGraph' --no-check-sri --ignore-empty-alt --no-enforce_https ./_site - name: DNS Validator run: bundle exec github-pages health-check @@ -67,10 +91,10 @@ jobs: steps: - name: Checkout EIP Repository - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f - name: Link Checker - uses: gaurav-nelson/github-action-markdown-link-check@0a51127e9955b855a9bbfa1ff5577f1d1338c9a5 + uses: gaurav-nelson/github-action-markdown-link-check@d53a906aa6b22b8979d33bc86170567e619495ec with: config-file: config/mlc_config.json use-quiet-mode: no @@ -83,7 +107,7 @@ jobs: steps: - name: Checkout EIP Repository - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f - name: Get Changed Files id: changed @@ -96,7 +120,7 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run CodeSpell - uses: codespell-project/actions-codespell@2391250ab05295bddd51e36a8c6295edb6343b0e + uses: codespell-project/actions-codespell@57beb9f38f49d773d641ac555d1565c3b6a59938 if: steps.changed.outcome == 'success' with: check_filenames: true @@ -110,20 +134,21 @@ jobs: steps: - name: Checkout EIP Repository - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f - - uses: ethereum/eipw-action@7774047fa54c1cb3b3ada9c9db23721eaee56669 + - uses: ethereum/eipw-action@b8de7ea9ad5cb842301e63898afb996c451c18cf id: eipw with: token: ${{ secrets.GITHUB_TOKEN }} unchecked: 1, 5069, 5757 + options-file: config/eipw.toml markdownlint: name: Markdown Linter runs-on: ubuntu-latest steps: - name: Checkout EIP Repository - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + uses: actions/checkout@47fbe2df0ad0e27efb67a70beac3555f192b062f - name: Get Changed Files id: changed @@ -136,7 +161,7 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Lint - uses: DavidAnson/markdownlint-cli2-action@16d9da45919c958a8d1ddccb4bd7028e8848e4f1 + uses: DavidAnson/markdownlint-cli2-action@f5cf187ef11bd3a68a127321b794aa252ff23019 if: steps.changed.outcome == 'success' with: command: config diff --git a/.github/workflows/jekyll-label-bot.yml b/.github/workflows/jekyll-label-bot.yml index d942ef947dea3f..549c28c9b4d2a2 100644 --- a/.github/workflows/jekyll-label-bot.yml +++ b/.github/workflows/jekyll-label-bot.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: Pandapip1/jekyll-label-action@28a89dbbef321fceaf3cff17f4d29c7a033c3d56 + - uses: Pandapip1/jekyll-label-action@d0fd82c3cd118140a50843906845fca8e59a8b9e with: token: ${{ secrets.GITHUB_TOKEN }} config-path: config/.jekyll-labels.yml diff --git a/.github/workflows/jekyll.yml b/.github/workflows/jekyll.yml new file mode 100644 index 00000000000000..3c79e42a196f7a --- /dev/null +++ b/.github/workflows/jekyll.yml @@ -0,0 +1,87 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +# Sample workflow for building and deploying a Jekyll site to GitHub Pages +name: Deploy Jekyll site to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["master"] + schedule: + - cron: "*/15 * * * *" # Every 15 minutes + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Build job + build: + runs-on: ubuntu-latest + steps: + - name: Checkout EIPs + uses: actions/checkout@v4 + with: + repository: ethereum/EIPs + path: '' + - name: Checkout ERCs + uses: actions/checkout@v4 + with: + repository: ethereum/ERCs + path: ERCs + - name: Merge Repos + run: | + mkdir -p $GITHUB_WORKSPACE/ERCs/ERCS + mkdir -p $GITHUB_WORKSPACE/ERCs/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/ERCS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/EIPS/. $GITHUB_WORKSPACE/EIPS + cp -rp $GITHUB_WORKSPACE/ERCs/assets/. $GITHUB_WORKSPACE/assets + cd $GITHUB_WORKSPACE/EIPS + find . -name "erc-*.md" -type f -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE/assets + find . -name "erc-*" -type d -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/erc/eip/)"' _ {} \; | sh + cd $GITHUB_WORKSPACE + rm -rf ERCs + - name: Setup Ruby + uses: ruby/setup-ruby@55283cc23133118229fd3f97f9336ee23a179fcf # v1.146.0 + with: + ruby-version: '3.1' # Not needed with a .ruby-version file + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + cache-version: 0 # Increment this number if you need to re-download cached gems + - name: Setup Pages + id: pages + uses: actions/configure-pages@v3 + - name: Build with Jekyll + # Outputs to the './_site' directory by default + run: bundle exec jekyll build --baseurl "${{ steps.pages.outputs.base_path }}" + env: + JEKYLL_ENV: production + - name: Upload artifact + # Automatically uploads an artifact from the './_site' directory by default + uses: actions/upload-pages-artifact@v2 + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v2 diff --git a/.github/workflows/post-ci.yml b/.github/workflows/post-ci.yml index e14e3435ba13d8..7057a97f3017cd 100644 --- a/.github/workflows/post-ci.yml +++ b/.github/workflows/post-ci.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Fetch PR Data - uses: dawidd6/action-download-artifact@6765a42d86407a3d532749069ac03705ad82ebc6 + uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615 with: name: pr_number workflow: ci.yml @@ -38,7 +38,7 @@ jobs: Please inspect the [Run Summary](https://github.com/ethereum/EIPs/pull/${{ steps.save-pr-data.outputs.pr_number }}/files) for details. - name: Add Waiting Label - uses: actions-ecosystem/action-add-labels@bd52874380e3909a1ac983768df6976535ece7f8 + uses: actions-ecosystem/action-add-labels@288072f1a3b596f4350fe135bcfe381a23abadef if: ${{ github.event.workflow_run.conclusion == 'failure' }} with: labels: w-ci @@ -47,7 +47,7 @@ jobs: github_token: ${{ github.token }} - name: Remove Waiting Label - uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 + uses: actions-ecosystem/action-remove-labels@d05162525702062b6bdef750ed8594fc024b3ed7 if: ${{ github.event.workflow_run.conclusion != 'failure' }} with: labels: w-ci diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 731f68b5313662..03eaf1bb8c6d35 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest name: Mark Stale Issues steps: - - uses: actions/stale@99b6c709598e2b0d0841cd037aaf1ba07a4410bd + - uses: actions/stale@03af7c36d33f4905e618fac0a1bb7e6d05f0d41b with: # General repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/EIPS/eip-1.md b/EIPS/eip-1.md index 29c9e286c9a832..1160a8831bd6a3 100644 --- a/EIPS/eip-1.md +++ b/EIPS/eip-1.md @@ -24,8 +24,8 @@ There are three types of EIP: - A **Standards Track EIP** describes any change that affects most or all Ethereum implementations, such as—a change to the network protocol, a change in block or transaction validity rules, proposed application standards/conventions, or any change or addition that affects the interoperability of applications using Ethereum. Standards Track EIPs consist of three parts—a design document, an implementation, and (if warranted) an update to the [formal specification](https://github.com/ethereum/yellowpaper). Furthermore, Standards Track EIPs can be broken down into the following categories: - **Core**: improvements requiring a consensus fork (e.g. [EIP-5](./eip-5.md), [EIP-101](./eip-101.md)), as well as changes that are not necessarily consensus critical but may be relevant to [“core dev” discussions](https://github.com/ethereum/pm) (for example, [EIP-90], and the miner/node strategy changes 2, 3, and 4 of [EIP-86](./eip-86.md)). - **Networking**: includes improvements around [devp2p](https://github.com/ethereum/devp2p/blob/readme-spec-links/rlpx.md) ([EIP-8](./eip-8.md)) and [Light Ethereum Subprotocol](https://ethereum.org/en/developers/docs/nodes-and-clients/#light-node), as well as proposed improvements to network protocol specifications of [whisper](https://github.com/ethereum/go-ethereum/issues/16013#issuecomment-364639309) and [swarm](https://github.com/ethereum/go-ethereum/pull/2959). - - **Interface**: includes improvements around client [API/RPC](https://github.com/ethereum/execution-apis#README) specifications and standards, and also certain language-level standards like method names ([EIP-6](./eip-6.md)) and [contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html). The label “interface” aligns with the [interfaces repo] and discussion should primarily occur in that repository before an EIP is submitted to the EIPs repository. - - **ERC**: application-level standards and conventions, including contract standards such as token standards ([EIP-20](./eip-20.md)), name registries ([EIP-137](./eip-137.md)), URI schemes, library/package formats, and wallet formats. + - **Interface**: includes improvements around language-level standards like method names ([EIP-6](./eip-6.md)) and [contract ABIs](https://docs.soliditylang.org/en/develop/abi-spec.html). + - **ERC**: application-level standards and conventions, including contract standards such as token standards ([ERC-20](./eip-20.md)), name registries ([ERC-137](./eip-137.md)), URI schemes, library/package formats, and wallet formats. - A **Meta EIP** describes a process surrounding Ethereum or proposes a change to (or an event in) a process. Process EIPs are like Standards Track EIPs but apply to areas other than the Ethereum protocol itself. They may propose an implementation, but not to Ethereum's codebase; they often require community consensus; unlike Informational EIPs, they are more than recommendations, and users are typically not free to ignore them. Examples include procedures, guidelines, changes to the decision-making process, and changes to the tools or environment used in Ethereum development. Any meta-EIP is also considered a Process EIP. @@ -85,7 +85,9 @@ If this period results in necessary normative changes it will revert the EIP to **Final** - This EIP represents the final standard. A Final EIP exists in a state of finality and should only be updated to correct errata and add non-normative clarifications. -**Stagnant** - Any EIP in `Draft` or `Review` or `Last Call` if inactive for a period of 6 months or greater is moved to `Stagnant`. An EIP may be resurrected from this state by Authors or EIP Editors through moving it back to `Draft` or it's earlier status. If not resurrected, a proposal may stay forever in this status. +A PR moving an EIP from Last Call to Final SHOULD contain no changes other than the status update. Any content or editorial proposed change SHOULD be separate from this status-updating PR and committed prior to it. + +**Stagnant** - Any EIP in `Draft` or `Review` or `Last Call` if inactive for a period of 6 months or greater is moved to `Stagnant`. An EIP may be resurrected from this state by Authors or EIP Editors through moving it back to `Draft` or its earlier status. If not resurrected, a proposal may stay forever in this status. >*EIP Authors are notified of any algorithmic change to the status of their EIP* @@ -116,7 +118,7 @@ EIPs should be written in [markdown](https://github.com/adam-p/markdown-here/wik Each EIP must begin with an [RFC 822](https://www.ietf.org/rfc/rfc822.txt) style header preamble, preceded and followed by three hyphens (`---`). This header is also termed ["front matter" by Jekyll](https://jekyllrb.com/docs/front-matter/). The headers must appear in the following order. -`eip`: *EIP number* (this is determined by the EIP editor) +`eip`: *EIP number* `title`: *The EIP title is a few words, not a complete sentence* @@ -154,13 +156,15 @@ or > Random J. User (@username) -if the email address or GitHub username is included, and +or + +> Random J. User (@username) <address@dom.ain> -> Random J. User +if the email address and/or GitHub username is included, and -if the email address is not given. +> Random J. User -It is not possible to use both an email and a GitHub username at the same time. If important to include both, one could include their name twice, once with the GitHub username, and once with the email. +if neither the email address nor the GitHub username are given. At least one author must use a GitHub username, in order to get notified on change requests and have the capability to approve or reject them. @@ -194,9 +198,27 @@ Other than the specific exceptions listed below, links to external resources **S The process governing permitted external resources is described in [EIP-5757](./eip-5757.md). +### Execution Client Specifications + +Links to the Ethereum Execution Client Specifications may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution Client Specifications](https://github.com/ethereum/execution-specs/blob/9a1f22311f517401fed6c939a159b55600c454af/README.md) +``` + +Which renders to: + +[Ethereum Execution Client Specifications](https://github.com/ethereum/execution-specs/blob/9a1f22311f517401fed6c939a159b55600c454af/README.md) + +Permitted Execution Client Specifications URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ethereum/execution-specs/(blob|commit)/[0-9a-f]{40}/.*|https://github.com/ethereum/execution-specs/tree/[0-9a-f]{40}/.*)$ +``` + ### Consensus Layer Specifications -Links to the Ethereum Consensus Layer Specifications may be included using normal markdown syntax, such as: +Links to specific commits of files within the Ethereum Consensus Layer Specifications may be included using normal markdown syntax, such as: ```markdown [Beacon Chain](https://github.com/ethereum/consensus-specs/blob/26695a9fdb747ecbe4f0bb9812fedbc402e5e18c/specs/sharding/beacon-chain.md) @@ -209,12 +231,12 @@ Which renders to: Permitted Consensus Layer Specifications URLs must anchor to a specific commit, and so must match this regular expression: ```regex -^https://github.com/ethereum/consensus-specs/blob/[0-9a-f]{40}/.*$ +^https://github.com/ethereum/consensus-specs/(blob|commit)/[0-9a-f]{40}/.*$ ``` ### Networking Specifications -Links to the Ethereum Networking Specifications may be included using normal markdown syntax, such as: +Links to specific commits of files within the Ethereum Networking Specifications may be included using normal markdown syntax, such as: ```markdown [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/40ab248bf7e017e83cc9812a4e048446709623e8/caps/eth.md) @@ -227,7 +249,147 @@ Which renders as: Permitted Networking Specifications URLs must anchor to a specific commit, and so must match this regular expression: ```regex -^https://github.com/ethereum/devp2p/blob/[0-9a-f]{40}/.*$ +^https://github.com/ethereum/devp2p/(blob|commit)/[0-9a-f]{40}/.*$ +``` + +### World Wide Web Consortium (W3C) + +Links to a W3C "Recommendation" status specification may be included using normal markdown syntax. For example, the following link would be allowed: + +```markdown +[Secure Contexts](https://www.w3.org/TR/2021/CRD-secure-contexts-20210918/) +``` + +Which renders as: + +[Secure Contexts](https://www.w3.org/TR/2021/CRD-secure-contexts-20210918/) + +Permitted W3C recommendation URLs MUST anchor to a specification in the technical reports namespace with a date, and so MUST match this regular expression: + +```regex +^https://www\.w3\.org/TR/[0-9][0-9][0-9][0-9]/.*$ +``` + +### Web Hypertext Application Technology Working Group (WHATWG) + +Links to WHATWG specifications may be included using normal markdown syntax, such as: + +```markdown +[HTML](https://html.spec.whatwg.org/commit-snapshots/578def68a9735a1e36610a6789245ddfc13d24e0/) +``` + +Which renders as: + +[HTML](https://html.spec.whatwg.org/commit-snapshots/578def68a9735a1e36610a6789245ddfc13d24e0/) + +Permitted WHATWG specification URLs must anchor to a specification defined in the `spec` subdomain (idea specifications are not allowed) and to a commit snapshot, and so must match this regular expression: + +```regex +^https:\/\/[a-z]*\.spec\.whatwg\.org/commit-snapshots/[0-9a-f]{40}/$ +``` + +Although not recommended by WHATWG, EIPs must anchor to a particular commit so that future readers can refer to the exact version of the living standard that existed at the time the EIP was finalized. This gives readers sufficient information to maintain compatibility, if they so choose, with the version referenced by the EIP and the current living standard. + +### Internet Engineering Task Force (IETF) + +Links to an IETF Request For Comment (RFC) specification may be included using normal markdown syntax, such as: + +```markdown +[RFC 8446](https://www.rfc-editor.org/rfc/rfc8446) +``` + +Which renders as: + +[RFC 8446](https://www.rfc-editor.org/rfc/rfc8446) + +Permitted IETF specification URLs MUST anchor to a specification with an assigned RFC number (meaning cannot reference internet drafts), and so MUST match this regular expression: + +```regex +^https:\/\/www.rfc-editor.org\/rfc\/.*$ +``` + +### Bitcoin Improvement Proposal + +Links to Bitcoin Improvement Proposals may be included using normal markdown syntax, such as: + +```markdown +[BIP 38](https://github.com/bitcoin/bips/blob/3db736243cd01389a4dfd98738204df1856dc5b9/bip-0038.mediawiki) +``` + +Which renders to: + +[BIP 38](https://github.com/bitcoin/bips/blob/3db736243cd01389a4dfd98738204df1856dc5b9/bip-0038.mediawiki) + +Permitted Bitcoin Improvement Proposal URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/bitcoin/bips/blob/[0-9a-f]{40}/bip-[0-9]+\.mediawiki)$ +``` + +### National Vulnerability Database (NVD) + +Links to the Common Vulnerabilities and Exposures (CVE) system as published by the National Institute of Standards and Technology (NIST) may be included, provided they are qualified by the date of the most recent change, using the following syntax: + +```markdown +[CVE-2023-29638 (2023-10-17T10:14:15)](https://nvd.nist.gov/vuln/detail/CVE-2023-29638) +``` + +Which renders to: + +[CVE-2023-29638 (2023-10-17T10:14:15)](https://nvd.nist.gov/vuln/detail/CVE-2023-29638) + +### Chain Agnostic Improvement Proposals (CAIPs) + +Links to a Chain Agnostic Improvement Proposals (CAIPs) specification may be included using normal markdown syntax, such as: + +```markdown +[CAIP 10](https://github.com/ChainAgnostic/CAIPs/blob/5dd3a2f541d399a82bb32590b52ca4340b09f08b/CAIPs/caip-10.md) +``` + +Which renders to: + +[CAIP 10](https://github.com/ChainAgnostic/CAIPs/blob/5dd3a2f541d399a82bb32590b52ca4340b09f08b/CAIPs/caip-10.md) + +Permitted Chain Agnostic URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ChainAgnostic/CAIPs/blob/[0-9a-f]{40}/CAIPs/caip-[0-9]+\.md)$ +``` + +### Ethereum Yellow Paper + +Links to the Ethereum Yellow Paper may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Yellow Paper](https://github.com/ethereum/yellowpaper/blob/9c601d6a58c44928d4f2b837c0350cec9d9259ed/paper.pdf) +``` + +Which renders to: + +[Ethereum Yellow Paper](https://github.com/ethereum/yellowpaper/blob/9c601d6a58c44928d4f2b837c0350cec9d9259ed/paper.pdf) + +Permitted Yellow Paper URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github\.com/ethereum/yellowpaper/blob/[0-9a-f]{40}/paper\.pdf)$ +``` + +### Execution Client Specification Tests + +Links to the Ethereum Execution Client Specification Tests may be included using normal markdown syntax, such as: + +```markdown +[Ethereum Execution Client Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/d5a3188f122912e137aa2e21ed2a1403e806e424/README.md) +``` + +Which renders to: + +[Ethereum Execution Client Specification Tests](https://github.com/ethereum/execution-spec-tests/blob/d5a3188f122912e137aa2e21ed2a1403e806e424/README.md) + +Permitted Execution Client Specification Tests URLs must anchor to a specific commit, and so must match this regular expression: + +```regex +^(https://github.com/ethereum/execution-spec-tests/(blob|commit)/[0-9a-f]{40}/.*|https://github.com/ethereum/execution-spec-tests/tree/[0-9a-f]{40}/.*)$ ``` ### Digital Object Identifier System @@ -267,6 +429,9 @@ This is a sentence with a footnote.[^1] Which renders to: + + + This is a sentence with a footnote.[^1] [^1]: @@ -296,6 +461,8 @@ This is a sentence with a footnote.[^1] } ``` + + See the [Citation Style Language Schema](https://resource.citationstyles.org/schema/v1.0/input/json/csl-data.json) for the supported fields. In addition to passing validation against that schema, references must include a DOI and at least one URL. The top-level URL field must resolve to a copy of the referenced document which can be viewed at zero cost. Values under `additional-urls` must also resolve to a copy of the referenced document, but may charge a fee. @@ -319,15 +486,16 @@ If you are interested in assuming ownership of an EIP, send a message asking to The current EIP editors are - Alex Beregszaszi (@axic) -- Gavin John (@Pandapip1) - Greg Colvin (@gcolvin) - Matt Garnett (@lightclient) - Sam Wilson (@SamWilsn) - Zainan Victor Zhou (@xinbenlv) +- Gajinder Singh (@g11tech) Emeritus EIP editors are - Casey Detrio (@cdetrio) +- Gavin John (@Pandapip1) - Hudson Jameson (@Souptacular) - Martin Becze (@wanderer) - Micah Zoltu (@MicahZoltu) @@ -349,7 +517,7 @@ If the EIP isn't ready, the editor will send it back to the author for revision, Once the EIP is ready for the repository, the EIP editor will: -- Assign an EIP number (generally the PR number, but the decision is with the editors) +- Assign an EIP number (generally incremental; editors can reassign if number sniping is suspected) - Merge the corresponding [pull request](https://github.com/ethereum/EIPs/pulls) - Send a message back to the EIP author with the next step. diff --git a/EIPS/eip-101.md b/EIPS/eip-101.md index 19053a64bd2e2b..11723850ae517c 100644 --- a/EIPS/eip-101.md +++ b/EIPS/eip-101.md @@ -56,7 +56,7 @@ This essentially implements signature and nonce checking, and if both checks pas Miners can follow the following algorithm upon receiving transactions: 1. Run the code for a maximum of 50000 gas, stopping if they see an operation or call that threatens to go over this limit -2. Upon seeing that operation, make sure that it leaves at last 50000 gas to spare (either by checking that the static gas consumption is small enough or by checking that it is a call with `msg.gas - 50000` as its gas limit parameter) +2. Upon seeing that operation, make sure that it leaves at least 50000 gas to spare (either by checking that the static gas consumption is small enough or by checking that it is a call with `msg.gas - 50000` as its gas limit parameter) 3. Pattern-match to make sure that gas payment code at the end is *exactly* the same as in the code above. This process ensures that miners *waste* at most 50000 gas before knowing whether or not it will be worth their while to include the transaction, and is also highly general so users can experiment with new cryptography (eg. ed25519, Lamport), ring signatures, quasi-native multisig, etc. Theoretically, one can even create an account for which the *valid signature* type is a valid Merkle branch of a receipt, creating a quasi-native alarm clock. diff --git a/EIPS/eip-1011.md b/EIPS/eip-1011.md index 84c3844bf10f0e..a571322ed40ae4 100644 --- a/EIPS/eip-1011.md +++ b/EIPS/eip-1011.md @@ -342,7 +342,7 @@ Most other decisions were made to minimize changes across clients. For example, #### Deploying Casper Contract The `MSG_HASHER_CODE` and `PURITY_CHECKER_CODE` both do not require any initialization so the EVM bytecode can simply be placed at `MSG_HASHER_ADDR` and `PURITY_CHECKER_ADDR`. On the other hand, the casper contract _does_ require passing in parameters and initialization of state. This initialization would normally occur by the EVM init code interacting with the CREATE opcode. Due to the nature of this contract being deployed outside of normal block transactions and to a particular address, the EVM init code/CREATE method requires client specific "hacks" to make it work. For simplicity of specifying across clients, the EVM bytecode -- `CASPER_CODE` -- is placed at `CASPER_ADDR` followed by an explicit `CALL` to a one-time `init` method on the casper contract. `init` handles all of the logic that a constructor normally would, accepting contract parameters as arguments and setting initial variable values, and can only be run _once_. -`CASPER_INIT_DATA` is composed of the the byte signature of the `init` method of the casper contract concatenated with the 32-byte encodings of the following variables in the following order: +`CASPER_INIT_DATA` is composed of the byte signature of the `init` method of the casper contract concatenated with the 32-byte encodings of the following variables in the following order: * `EPOCH_LENGTH` * `WITHDRAWAL_DELAY` diff --git a/EIPS/eip-1015.md b/EIPS/eip-1015.md index 829cc00f3ffb5b..80fadd977b5fb2 100644 --- a/EIPS/eip-1015.md +++ b/EIPS/eip-1015.md @@ -20,7 +20,7 @@ These are current EIPs that are being developed or debated. They might seem unre #### Casper and PoS -Moving to PoS has been on the roadmap since day 0 for ethereum, along with a reduction in issuance to a cost equivalent to the Validator's cost of security (considered to be more eficient than PoW). But the exact issuance necessary for PoS has yet to be determined and is currently being researched. Casper validation will be an on chain contract and therefore it will need to be funded. It's unlikely that a definitive final answer on how much issuance is needed for validation will be reached in the next years as new research will uncover new arguments, so it would make sense to allow some flexibility on this matter +Moving to PoS has been on the roadmap since day 0 for ethereum, along with a reduction in issuance to a cost equivalent to the Validator's cost of security (considered to be more efficient than PoW). But the exact issuance necessary for PoS has yet to be determined and is currently being researched. Casper validation will be an on chain contract and therefore it will need to be funded. It's unlikely that a definitive final answer on how much issuance is needed for validation will be reached in the next years as new research will uncover new arguments, so it would make sense to allow some flexibility on this matter #### Issuance Cap at 120 Million diff --git a/EIPS/eip-1046.md b/EIPS/eip-1046.md index 80c789222d1712..d831616c7de4e3 100644 --- a/EIPS/eip-1046.md +++ b/EIPS/eip-1046.md @@ -1,87 +1,7 @@ --- eip: 1046 -title: ERC20 Metadata Extension -author: Tommy Nicholas (@tomasienrbc), Matt Russo (@mateosu), John Zettler (@JohnZettler), Matt Condon (@shrugs) -discussions-to: https://www.reddit.com/r/raredigitalart/comments/8hfh1g/erc20_metadata_extension_eip_1046/ -status: Stagnant -type: Standards Track category: ERC -created: 2018-04-13 -requires: 20 +status: Moved --- -## Simple Summary -Optionally extend ERC20 token interface to support the same metadata standard as ERC721 tokens. - -## Abstract -The ERC721 standard introduced the `tokenURI` parameter for non-fungible tokens to handle metadata such as: - -- thumbnail image -- title -- description -- special asset properties -- etc. - -Metadata is critical for assets such as crypto-collectibles and video game assets to have real utility and value. However, not all crypto-collectibles and gaming assets will be non-fungible. It is critical for fungible ERC20 tokens to have a metadata standard like that of ERC721 tokens. Standardization of metadata between ERC20 and ERC721 will simplify development of dApps and infrastructure that must support both fungible and non-fungible assets. - -## Motivation -The ERC721 standard was created to support the creation of perfectly unique, 1-of-1, non-divisible tokens known as "non-fungible tokens". - -The initial use case for the ERC721 standard was to support the creation of crypto-collectibles and gaming assets, initially for the ["Crypto Kitties"](https://www.cryptokitties.co/) collectibles game. The success of Crypto Kitties catalyzed significant application development to support the display of ERC721 assets using the `tokenURI` metadata parameter. - -However, not all crypto-collectibles and gaming assets need to be unique and non-fungible. Gaming assets (items, weapons, characters), crypto-artworks with non-unique "prints", and more will function more like traditional ERC20 tokens with a fungible `supply`. Many applications such as wallets, exchanges, games, etc. will want to support both fungible and non-fungible assets containing similar metadata. This proposal will extend the ERC20 standard to optionally include a nearly identical `tokenURI` parameter supporting the same JSON metadata schema as the ERC721 standard. - -## Specification - -The **metadata extension** will be OPTIONAL for ERC20 contracts. This allows your smart contract to be interrogated for its name and for details about the assets which your tokens represent. - -```solidity -/// @title ERC-20 optional metadata extension -interface TokenMetaData /* is ERC20 */ { - - /// @notice A distinct Uniform Resource Identifier (URI) for a given token. - function tokenURI() external view returns (string); -} -``` - -This is the "Token Metadata JSON Schema" referenced above. - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents", - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", - } - } -} -``` - -The token's name() and symbol() getters should be preferred over the name and/or symbol properties in the tokenURI JSON. - -## Rationale -This proposal will make adding metadata to ERC20 tokens straightforward for developers with minimal-to-no disruption to the overall ecosystem. By using the same parameter name and by consolidating the underlying Token JSON Metadata Standard, developers will confidently understand how to add and interpret token metadata between ERC20 and ERC721 tokens. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation simply extends the functionality of ERC20 tokens and is optional. - -## Test Cases -TO-DO - -## Implementation - -- [Rare Art Labs](https://rareart.io) (WIP) -- [Open Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity) (WIP) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1046.md diff --git a/EIPS/eip-1052.md b/EIPS/eip-1052.md index 73e00bb8041e0c..356404f1915b14 100644 --- a/EIPS/eip-1052.md +++ b/EIPS/eip-1052.md @@ -61,7 +61,7 @@ There are no backwards compatibility concerns. 1. The `EXTCODEHASH` of the account without code is `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` what is the keccack256 hash of empty data. 2. The `EXTCODEHASH` of non-existent account is `0`. -3. The `EXTCODEHASH` of an precompiled contract is either `c5d246...` or `0`. +3. The `EXTCODEHASH` of a precompiled contract is either `c5d246...` or `0`. 4. If `EXTCODEHASH` of `A` is `X`, then `EXTCODEHASH` of `A + 2**160` is `X`. 5. The `EXTCODEHASH` of an account that selfdestructed in the current transaction. 6. The `EXTCODEHASH` of an account that selfdestructed and later the selfdestruct has been reverted. diff --git a/EIPS/eip-1056.md b/EIPS/eip-1056.md index cb468d8eb173b4..12110c18a0d770 100644 --- a/EIPS/eip-1056.md +++ b/EIPS/eip-1056.md @@ -1,286 +1,7 @@ --- eip: 1056 -title: Ethereum Lightweight Identity -author: Pelle Braendgaard , Joel Torstensson -type: Standards Track category: ERC -discussions-to: https://github.com/ethereum/EIPs/issues/1056 -status: Stagnant -created: 2018-05-03 +status: Moved --- -## Simple Summary - -A registry for key and attribute management of lightweight blockchain identities. - -## Abstract - -This ERC describes a standard for creating and updating identities with a limited use of blockchain resources. An identity can have an unlimited number of `delegates` and `attributes` associated with it. Identity creation is as simple as creating a regular key pair ethereum account, which means that it's free (no gas costs) and all ethereum accounts are valid identities. Furthermore this ERC is fully [DID compliant](https://w3c-ccg.github.io/did-spec/). - -## Motivation - -As we have been developing identity systems for the last couple of years at uPort it has become apparent that the cost of identity creation is a large issue. The previous Identity proposal [ERC-725](./eip-725.md) faces this exact issue. Our requirements when creating this ERC is that identity creation should be free, and should be possible to do in an offline environment (e.g. refugee scenario). However it must also be possible to rotate keys without changing the primary identifier of the identity. The identity system should be fit to use off-chain as well as on-chain. - -## Definitions - -* `Identifier`: a piece of data that uniquely identifies the identity, an ethereum address - -* `delegate`: an address that is delegated for a specific time to perform some sort of function on behalf of an identity - -* `delegateType`: the type of a delegate, is determined by a protocol or application higher up - Examples: - - * `did-jwt` - * `raiden` - -* `attribute`: a piece of data associated with the identity - -## Specification - -This ERC specifies a contract called `EthereumDIDRegistry` that is deployed once and can then be commonly used by everyone. - -### Identity ownership - -By default an identity is owned by itself, meaning whoever controls the ethereum account with that address. The owner can be updated to a new key pair account or to a multisig account etc. - -#### identityOwner - -Returns the owner of the given identity. - -```js -function identityOwner(address identity) public view returns(address); -``` - -#### changeOwner - -Sets the owner of the given identity to another ethereum account. - -```js -function changeOwner(address identity, address newOwner) public; -``` - -#### changeOwnerSigned - -Same as above but with raw signature. - - -```js -function changeOwnerSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, address newOwner) public; -``` - -### Delegate management - -Delegates can be used both on- and off-chain. They all have a `delegateType` which can be used to specify the purpose of the delegate. - -#### validDelegate - -Returns true if the given `delegate` is a delegate with type `delegateType` of `identity`. - -```js -function validDelegate(address identity, bytes32 delegateType, address delegate) public view returns(bool); -``` - -#### addDelegate - -Adds a new delegate with the given type. `validity` indicates the number of seconds that the delegate will be valid for, after which it will no longer be a delegate of `identity`. - -```js -function addDelegate(address identity, bytes32 delegateType, address delegate, uint validity) public; -``` - - -#### addDelegateSigned - -Same as above but with raw signature. - - -```js -function addDelegateSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate, uint validity) public; -``` - - -#### revokeDelegate - -Revokes the given `delegate` for the given `identity`. - - -```js -function revokeDelegate(address identity, bytes32 delegateType, address delegate) public; -``` - - -#### revokeDelegateSigned - -Same as above but with raw signature. - - -```js -function revokeDelegateSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate) public; -``` - - -### Attribute management - -Attributes contain simple data about the identity. They can be managed only by the owner of the identity. - - -#### setAttribute - -Sets an attribute with the given `name` and `value`, valid for `validity` seconds. - - -```js -function setAttribute(address identity, bytes32 name, bytes value, uint validity) public; -``` - - -#### setAttributeSigned - -Same as above but with raw signature. - - -```js -function setAttributeSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes value, uint validity) public; -``` - - -#### revokeAttrubte - -Revokes an attribute. - - -```js -function revokeAttribute(address identity, bytes32 name, bytes value) public; -``` - - -#### revokeAttributeSigned - -Same as above but with raw signature. - - -```js -function revokeAttributeSigned(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes value) public; -``` - - -### Events - -#### DIDOwnerChanged - -MUST be triggered when `changeOwner` or `changeOwnerSigned` was successfully called. - - -```js -event DIDOwnerChanged( - address indexed identity, - address owner, - uint previousChange -); -``` - - -#### DIDDelegateChanged - -MUST be triggered when a change to a delegate was successfully made. - - -```js -event DIDDelegateChanged( - address indexed identity, - bytes32 delegateType, - address delegate, - uint validTo, - uint previousChange -); -``` - - -#### DIDAttritueChanged - -MUST be triggered when a change to an attribute was successfully made. - - -```js -event DIDAttributeChanged( - address indexed identity, - bytes32 name, - bytes value, - uint validTo, - uint previousChange -); -``` - - -### Efficient lookup of events through linked identity events - -Contract Events are a useful feature for storing data from smart contracts exclusively for off-chain use. Unfortunately current ethereum implementations provide a very inefficient lookup mechanism. By using linked events that always link to the previous block with a change for the identity, we can solve this problem with much improved performance. Each identity has its previously changed block stored in the `changed` mapping. - - - -1. Lookup `previousChange` block for identity - -2. Lookup all events for given identity address using web3, but only for the `previousChange` block - -3. Do something with event - -4. Find `previousChange` from the event and repeat - - - -Example code: - - -```js -const history = [] -previousChange = await didReg.changed(identity) -while (previousChange) { - const filter = await didReg.allEvents({topics: [identity], fromBlock: previousChange, toBlock: previousChange}) - const events = await getLogs(filter) - previousChange = undefined - for (let event of events) { - history.unshift(event) - previousChange = event.args.previousChange - } -} -``` - - -### Building a DID document for an identity - -The primary owner key should be looked up using `identityOwner(identity)`. This should be the first of the publicKeys listed. Iterate through the `DIDDelegateChanged` events to build a list of additional keys and authentication sections as needed. The list of delegateTypes to include is still to be determined. Iterate through `DIDAttributeChanged` events for service entries, encryption public keys and other public names. The attribute names are still to be determined. - - -## Rationale - -For on-chain interactions Ethereum has a built in account abstraction that can be used regardless of whether the account is a smart contract or a key pair. Any transaction has a `msg.sender` as the verified send of the transaction. - - -Since each Ethereum transaction has to be funded, there is a growing trend of on-chain transactions that are authenticated via an externally created signature and not by the actual transaction originator. This allows 3rd party funding services or receiver pays without any fundamental changes to the underlying Ethereum architecture. These kinds of transactions have to be signed by an actual key pair and thus can not be used to represent smart contract based Ethereum accounts. - - -We propose a way of a Smart Contract or regular key pair delegating signing for various purposes to externally managed key pairs. This allows a smart contract to be represented both on-chain as well as off-chain or in payment channels through temporary or permanent delegates. - - -## Backwards Compatibility - -All ethereum accounts are valid identities (and DID compatible) using this standard. This means that any wallet provider that uses key pair accounts already supports the bare minimum of this standard, and can implement `delegate` and `attribute` functionality by simply using the `ethr-did` referenced below. As the **DID Auth** standard solidifies it also means that all of these wallets will be compatible with the [DID decentralized login system](https://github.com/decentralized-identity). - - -## Implementation - -[ethr-did-registry](https://github.com/uport-project/ethr-did-registry/blob/develop/contracts/EthereumDIDRegistry.sol) (`EthereumDIDRegistry` contract implementation) - -[ethr-did-resolver](https://github.com/uport-project/ethr-did-resolver) (DID compatible resolver) - -[ethr-did](https://github.com/uport-project/ethr-did) (javascript library for using the identity) - - -### Deployment - -The address for the `EthereumDIDRegistry` is `0xdca7ef03e98e0dc2b855be647c39abe984fcf21b` on Mainnet, Ropsten, Rinkeby and Kovan. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1056.md diff --git a/EIPS/eip-1057.md b/EIPS/eip-1057.md index dc39734afbd714..cccc97a29c040a 100644 --- a/EIPS/eip-1057.md +++ b/EIPS/eip-1057.md @@ -326,12 +326,12 @@ uint32_t math(uint32_t a, uint32_t b, uint32_t r) The flow of the inner loop is: * Lane `(loop % LANES)` is chosen as the leader for that loop iteration -* The leader's `mix[0]` value modulo the number of 256-byte DAG entries is is used to select where to read from the full DAG +* The leader's `mix[0]` value modulo the number of 256-byte DAG entries is used to select where to read from the full DAG * Each lane reads `DAG_LOADS` sequential words, using `(lane ^ loop) % LANES` as the starting offset within the entry. * The random sequence of math and cache accesses is performed * The DAG data read at the start of the loop is merged at the end of the loop -`prog_seed` and `loop` come from the outer loop, corresponding to the current program seed (which is block_number/PROGPOW_PERIOD) and the loop iteration number. `mix` is the state array, initially filled by `fill_mix`. `dag` is the bytes of the Ethash DAG grouped into 32 bit unsigned ints in litte-endian format. On little-endian architectures this is just a normal int32 pointer to the existing DAG. +`prog_seed` and `loop` come from the outer loop, corresponding to the current program seed (which is block_number/PROGPOW_PERIOD) and the loop iteration number. `mix` is the state array, initially filled by `fill_mix`. `dag` is the bytes of the Ethash DAG grouped into 32 bit unsigned ints in little-endian format. On little-endian architectures this is just a normal int32 pointer to the existing DAG. `DAG_BYTES` is set to the number of bytes in the current DAG, which is generated identically to the existing Ethash algorithm. diff --git a/EIPS/eip-1062.md b/EIPS/eip-1062.md index 0f304b6cb2c8b7..186cc0b05e2eb5 100644 --- a/EIPS/eip-1062.md +++ b/EIPS/eip-1062.md @@ -1,84 +1,7 @@ --- eip: 1062 -title: Formalize IPFS hash into ENS(Ethereum Name Service) resolver -author: Phyrex Tsai , Portal Network Team -discussions-to: https://ethereum-magicians.org/t/eip-1062-formalize-ipfs-hash-into-ens-ethereum-name-service-resolver/281 -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-02 +status: Moved --- -## Simple Summary -To specify the mapping protocol between resources stored on IPFS and ENS(Ethereum Naming Service). - -## Abstract -The following standard details the implementation of how to combine the IPFS cryptographic hash unique fingerprint with ENS public resolver. This standard provides a functionality to get and set IPFS online resources to ENS resolver. - -We think that this implementation is not only aim to let more developers and communities to provide more use cases, but also leverage the human-readable features to gain more user adoption accessing decentralized resources. We considered the IPFS ENS resolver mapping standard a cornerstone for building future Web3.0 service. - -## Motivation -To build fully decentralized web service, it’s necessary to have a decentralized file storage system. Here comes the IPFS, for three following advantages : -- Address large amounts of data, and has unique cryptographic hash for every record. -- Since IPFS is also based on peer to peer network, it can be really helpful to deliver large amounts of data to users, with safer way and lower the millions of cost for the bandwidth. -- IPFS stores files in high efficient way via tracking version history for every file, and removing the duplications across the network. - -Those features makes perfect match for integrating into ENS, and these make users can easily access content through ENS, and show up in the normal browser. - - -## Specification -The condition now is that the IPFS file fingerprint using base58 and in the meantime, the Ethereum uses hex in API to encode the binary data. So that need a way to process the condition requires not only we need to transfer from IPFS to Ethereum, but also need to convert it back. - -To solve these requirements, we can use binary buffer bridging that gap. -When mapping the IPFS base58 string to ENS resolver, first we convert the Base58 to binary buffer, turn the buffer to hex encrypted format, and save to the contract. Once we want to get the IPFS resources address represented by the specific ENS, we can first find the mapping information stored as hex format before, extract the hex format to binary buffer, and finally turn that to IPFS Base58 address string. - - -## Rationale -To implement the specification, need two methods from ENS public resolver contract, when we want to store IPFS file fingerprint to contract, convert the Base58 string identifier to the hex format and invoke the `setMultihash` method below : - -```solidity -function setMultihash(bytes32 node, bytes hash) public only_owner(node); -``` - -Whenever users need to visit the ENS content, we call the `multihash` method to get the IPFS hex data, transfer to the Base58 format, and return the IPFS resources to use. - -```solidity -function multihash(bytes32 node) public view returns (bytes); -``` - -## Test Cases - -To implement the way to transfer from base58 to hex format and the reverse one, using the ‘multihashes’ library to deal with the problem. -The library link : [https://www.npmjs.com/package/multihashes](https://www.npmjs.com/package/multihashes) -To implement the method transfer from IPFS(Base58) to hex format : - -```javascript -import multihash from 'multihashes' - -export const toHex = function(ipfsHash) { - let buf = multihash.fromB58String(ipfsHash); - return '0x' + multihash.toHexString(buf); -} -``` - -To implement the method transfer from hex format to IPFS(Base58) : - -```javascript -import multihash from 'multihashes' - -export const toBase58 = function(contentHash) { - let hex = contentHash.substring(2) - let buf = multihash.fromHexString(hex); - return multihash.toB58String(buf); -} -``` - -## Implementation -The use case can be implemented as browser extension. Users can easily download the extension, and easily get decentralized resources by just typing the ENS just like we normally type the DNS to browser the website. Solve the current pain for normal people can not easily visit the total decentralized website. - -The workable implementation repository : [https://github.com/PortalNetwork/portal-network-browser-extension](https://github.com/PortalNetwork/portal-network-browser-extension) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1062.md diff --git a/EIPS/eip-1066.md b/EIPS/eip-1066.md index 5b29e2dd32c981..f5cbc61ae0e4a7 100644 --- a/EIPS/eip-1066.md +++ b/EIPS/eip-1066.md @@ -1,598 +1,7 @@ --- eip: 1066 -title: Status Codes -author: Brooklyn Zelenka (@expede), Tom Carchrae (@carchrae), Gleb Naumenko (@naumenkogs) -discussions-to: https://ethereum-magicians.org/t/erc-1066-ethereum-status-codes-esc/ -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-05 +status: Moved --- -## Simple Summary - -Broadly applicable status codes for smart contracts. - -## Abstract - -This standard outlines a common set of status codes in a similar vein to HTTP statuses. This provides a shared set of signals to allow smart contracts to react to situations autonomously, expose localized error messages to users, and so on. - -The current state of the art is to either `revert` on anything other than a clear success (ie: require human intervention), or return a low-context `true` or `false`. Status codes are similar-but-orthogonal to `revert`ing with a reason, but aimed at automation, debugging, and end-user feedback (including translation). _They are fully compatible with both `revert` and `revert`-with-reason._ - -As is the case with HTTP, having a standard set of known codes has many benefits for developers. They remove friction from needing to develop your own schemes for every contract, makes inter-contract automation easier, and makes it easier to broadly understand which of the finite states your request produced. Importantly, it makes it much easier to distinguish between expected errors states, truly exceptional conditions that require halting execution, normal state transitions, and various success cases. - -## Motivation - -### Semantic Density - -HTTP status codes are widely used for this purpose. BEAM languages use atoms and tagged tuples to signify much the same information. Both provide a lot of information both to the programmer (debugging for instance), and to the program that needs to decide what to do next. - -Status codes convey a much richer set of information [than Booleans](https://existentialtype.wordpress.com/2011/03/15/boolean-blindness/), and are able to be reacted to autonomously unlike arbitrary strings. - -### User Experience (UX) - -_End users get little to no feedback, and there is no translation layer._ - -Since ERC1066 status codes are finite and known in advance, we can leverage [ERC-1444](./eip-1444.md) to provide global, human-readable sets of status messages. These may also be translated into any language, differing levels of technical detail, added as `revert` messages, natspecs, and so on. - -Status codes convey a much richer set of information than Booleans, and are able to be reacted to autonomously unlike arbitrary strings. - -### Developer Experience (DX) - -_Developers currently have very little context exposed by their smart contracts._ - -At time of writing, other than stepping through EVM execution and inspecting memory dumps directly, it is very difficult to understand what is happening during smart contract execution. By returning more context, developers can write well-decomposed tests and assert certain codes are returned as an expression of where the smart contract got to. This includes status codes as bare values, `event`s, and `revert`s. - -Having a fixed set of codes also makes it possible to write common helper functions to react in common ways to certain signals. This can live off- or on-chain library, lowering the overhead in building smart contracts, and helping raise code quality with trusted shared components. - -We also see a desire for this [in transactions](./eip-658.md), and there's no reason that these status codes couldn't be used by the EVM itself. - -### Smart Contract Autonomy - -_Smart contracts don’t know much about the result of a request beyond pass/fail; they can be smarter with more context._ - -Smart contracts are largely intended to be autonomous. While each contract may define a specific interface, having a common set of semantic codes can help developers write code that can react appropriately to various situations. - -While clearly related, status codes are complementary to `revert`-with-reason. Status codes are not limited to rolling back the transaction, and may represent known error states without halting execution. They may also represent off-chain conditions, supply a string to revert, signal time delays, and more. - -All of this enables contracts to share a common vocabulary of state transitions, results, and internal changes, without having to deeply understand custom status enums or the internal business logic of collaborator contracts. - -## Specification - -### Format - -Codes are returned either on their own, or as the first value of a multiple return. - -```solidity -// Status only - -function isInt(uint num) public pure returns (byte status) { - return hex"01"; -} - -// Status and value - -uint8 private counter; - -function safeIncrement(uint8 interval) public returns (byte status, uint8 newCounter) { - uint8 updated = counter + interval; - - if (updated >= counter) { - counter = updated; - return (hex"01", updated); - } else { - return (hex"00", counter); - } -} -``` - -### Code Table - -Codes break nicely into a 16x16 matrix, represented as a 2-digit hex number. The high nibble represents the code's kind or "category", and the low nibble contains the state or "reason". We present them below as separate tables per range for explanatory and layout reasons. - -**NB: Unspecified codes are _not_ free for arbitrary use, but rather open for further specification.** - -#### `0x0*` Generic - -General codes. These double as bare "reasons", since `0x01 == 1`. - -| Code | Description | -|--------|-----------------------------------------| -| `0x00` | Failure | -| `0x01` | Success | -| `0x02` | Awaiting Others | -| `0x03` | Accepted | -| `0x04` | Lower Limit or Insufficient | -| `0x05` | Receiver Action Requested | -| `0x06` | Upper Limit | -| `0x07` | [reserved] | -| `0x08` | Duplicate, Unnecessary, or Inapplicable | -| `0x09` | [reserved] | -| `0x0A` | [reserved] | -| `0x0B` | [reserved] | -| `0x0C` | [reserved] | -| `0x0D` | [reserved] | -| `0x0E` | [reserved] | -| `0x0F` | Informational or Metadata | - -#### `0x1*` Permission & Control - -Also used for common state machine actions (ex. "stoplight" actions). - -| Code | Description | -|--------|---------------------------------------------------| -| `0x10` | Disallowed or Stop | -| `0x11` | Allowed or Go | -| `0x12` | Awaiting Other's Permission | -| `0x13` | Permission Requested | -| `0x14` | Too Open / Insecure | -| `0x15` | Needs Your Permission or Request for Continuation | -| `0x16` | Revoked or Banned | -| `0x17` | [reserved] | -| `0x18` | Not Applicable to Current State | -| `0x19` | [reserved] | -| `0x1A` | [reserved] | -| `0x1B` | [reserved] | -| `0x1C` | [reserved] | -| `0x1D` | [reserved] | -| `0x1E` | [reserved] | -| `0x1F` | Permission Details or Control Conditions | - -#### `0x2*` Find, Inequalities & Range - -This range is broadly intended for finding and matching. Data lookups and order matching are two common use cases. - -| Code | Description | -|--------|-------------------------------------| -| `0x20` | Not Found, Unequal, or Out of Range | -| `0x21` | Found, Equal or In Range | -| `0x22` | Awaiting Match | -| `0x23` | Match Request Sent | -| `0x24` | Below Range or Underflow | -| `0x25` | Request for Match | -| `0x26` | Above Range or Overflow | -| `0x27` | [reserved] | -| `0x28` | Duplicate, Conflict, or Collision | -| `0x29` | [reserved] | -| `0x2A` | [reserved] | -| `0x2B` | [reserved] | -| `0x2C` | [reserved] | -| `0x2D` | [reserved] | -| `0x2E` | [reserved] | -| `0x2F` | Matching Meta or Info | - -#### `0x3*` Negotiation & Governance - -Negotiation, and very broadly the flow of such transactions. Note that "other party" may be more than one actor (not necessarily the sender). - -| Code | Description | -|--------|-----------------------------------------| -| `0x30` | Sender Disagrees or Nay | -| `0x31` | Sender Agrees or Yea | -| `0x32` | Awaiting Ratification | -| `0x33` | Offer Sent or Voted | -| `0x34` | Quorum Not Reached | -| `0x35` | Receiver's Ratification Requested | -| `0x36` | Offer or Vote Limit Reached | -| `0x37` | [reserved] | -| `0x38` | Already Voted | -| `0x39` | [reserved] | -| `0x3A` | [reserved] | -| `0x3B` | [reserved] | -| `0x3C` | [reserved] | -| `0x3D` | [reserved] | -| `0x3E` | [reserved] | -| `0x3F` | Negotiation Rules or Participation Info | - -#### `0x4*` Availability & Time - -Service or action availability. - -| Code | Description | -|--------|------------------------------------------------------| -| `0x40` | Unavailable | -| `0x41` | Available | -| `0x42` | Paused | -| `0x43` | Queued | -| `0x44` | Not Available Yet | -| `0x45` | Awaiting Your Availability | -| `0x46` | Expired | -| `0x47` | [reserved] | -| `0x48` | Already Done | -| `0x49` | [reserved] | -| `0x4A` | [reserved] | -| `0x4B` | [reserved] | -| `0x4C` | [reserved] | -| `0x4D` | [reserved] | -| `0x4E` | [reserved] | -| `0x4F` | Availability Rules or Info (ex. time since or until) | - -#### `0x5*` Tokens, Funds & Finance - -Special token and financial concepts. Many related concepts are included in other ranges. - -| Code | Description | -|--------|---------------------------------| -| `0x50` | Transfer Failed | -| `0x51` | Transfer Successful | -| `0x52` | Awaiting Payment From Others | -| `0x53` | Hold or Escrow | -| `0x54` | Insufficient Funds | -| `0x55` | Funds Requested | -| `0x56` | Transfer Volume Exceeded | -| `0x57` | [reserved] | -| `0x58` | Funds Not Required | -| `0x59` | [reserved] | -| `0x5A` | [reserved] | -| `0x5B` | [reserved] | -| `0x5C` | [reserved] | -| `0x5D` | [reserved] | -| `0x5E` | [reserved] | -| `0x5F` | Token or Financial Information | - -#### `0x6*` TBD - -Currently unspecified. (Full range reserved) - -#### `0x7*` TBD - -Currently unspecifie. (Full range reserved) - -#### `0x8*` TBD - -Currently unspecified. (Full range reserved) - -#### `0x9*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xA*` Application-Specific Codes - -Contracts may have special states that they need to signal. This proposal only outlines the broadest meanings, but implementers may have very specific meanings for each, as long as they are coherent with the broader definition. - -| Code | Description | -|--------|----------------------------------------| -| `0xA0` | App-Specific Failure | -| `0xA1` | App-Specific Success | -| `0xA2` | App-Specific Awaiting Others | -| `0xA3` | App-Specific Acceptance | -| `0xA4` | App-Specific Below Condition | -| `0xA5` | App-Specific Receiver Action Requested | -| `0xA6` | App-Specific Expiry or Limit | -| `0xA7` | [reserved] | -| `0xA8` | App-Specific Inapplicable Condition | -| `0xA9` | [reserved] | -| `0xAA` | [reserved] | -| `0xAB` | [reserved] | -| `0xAC` | [reserved] | -| `0xAD` | [reserved] | -| `0xAE` | [reserved] | -| `0xAF` | App-Specific Meta or Info | - -#### `0xB*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xC*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xD*` TBD - -Currently unspecified. (Full range reserved) - -#### `0xE*` Encryption, Identity & Proofs - -Actions around signatures, cryptography, signing, and application-level authentication. - -The meta code `0xEF` is often used to signal a payload describing the algorithm or process used. - -| Code | Description | -|--------|-------------------------------------| -| `0xE0` | Decrypt Failure | -| `0xE1` | Decrypt Success | -| `0xE2` | Awaiting Other Signatures or Keys | -| `0xE3` | Signed | -| `0xE4` | Unsigned or Untrusted | -| `0xE5` | Signature Required | -| `0xE6` | Known to be Compromised | -| `0xE7` | [reserved] | -| `0xE8` | Already Signed or Not Encrypted | -| `0xE9` | [reserved] | -| `0xEA` | [reserved] | -| `0xEB` | [reserved] | -| `0xEC` | [reserved] | -| `0xED` | [reserved] | -| `0xEE` | [reserved] | -| `0xEF` | Cryptography, ID, or Proof Metadata | - -#### `0xF*` Off-Chain - -For off-chain actions. Much like th `0x0*: Generic` range, `0xF*` is very general, and does little to modify the reason. - -Among other things, the meta code `0xFF` may be used to describe what the off-chain process is. - -| Code | Description | -|--------|-----------------------------------| -| `0xF0` | Off-Chain Failure | -| `0xF1` | Off-Chain Success | -| `0xF2` | Awaiting Off-Chain Process | -| `0xF3` | Off-Chain Process Started | -| `0xF4` | Off-Chain Service Unreachable | -| `0xF5` | Off-Chain Action Required | -| `0xF6` | Off-Chain Expiry or Limit Reached | -| `0xF7` | [reserved] | -| `0xF8` | Duplicate Off-Chain Request | -| `0xF9` | [reserved] | -| `0xFA` | [reserved] | -| `0xFB` | [reserved] | -| `0xFC` | [reserved] | -| `0xFD` | [reserved] | -| `0xFE` | [reserved] | -| `0xFF` | Off-Chain Info or Meta | - -### As a Grid - -| | `0x0*` General | `0x1*` Permission & Control | `0x2*` Find, Inequalities & Range | `0x3*` Negotiation & Governance | `0x4*` Availability & Time | `0x5*` Tokens, Funds & Finance | `0x6*` TBD | `0x7*` TBD | `0x8*` TBD | `0x9*` TBD | `0xA*` Application-Specific Codes | `0xB*` TBD | `0xC*` TBD | `0xD*` TBD | `0xE*` Encryption, Identity & Proofs | `0xF*` Off-Chain | -|--------|------------------------------------------------|----------------------------------------------------------|--------------------------------------------|------------------------------------------------|-------------------------------------------------------------|----------------------------------------|-------------------|-------------------|-------------------|-------------------|-----------------------------------------------|-------------------|-------------------|-------------------|--------------------------------------------|------------------------------------------| -| `0x*0` | `0x00` Failure | `0x10` Disallowed or Stop | `0x20` Not Found, Unequal, or Out of Range | `0x30` Sender Disagrees or Nay | `0x40` Unavailable | `0x50` Transfer Failed | `0x60` [reserved] | `0x70` [reserved] | `0x80` [reserved] | `0x90` [reserved] | `0xA0` App-Specific Failure | `0xB0` [reserved] | `0xC0` [reserved] | `0xD0` [reserved] | `0xE0` Decrypt Failure | `0xF0` Off-Chain Failure | -| `0x*1` | `0x01` Success | `0x11` Allowed or Go | `0x21` Found, Equal or In Range | `0x31` Sender Agrees or Yea | `0x41` Available | `0x51` Transfer Successful | `0x61` [reserved] | `0x71` [reserved] | `0x81` [reserved] | `0x91` [reserved] | `0xA1` App-Specific Success | `0xB1` [reserved] | `0xC1` [reserved] | `0xD1` [reserved] | `0xE1` Decrypt Success | `0xF1` Off-Chain Success | -| `0x*2` | `0x02` Awaiting Others | `0x12` Awaiting Other's Permission | `0x22` Awaiting Match | `0x32` Awaiting Ratification | `0x42` Paused | `0x52` Awaiting Payment From Others | `0x62` [reserved] | `0x72` [reserved] | `0x82` [reserved] | `0x92` [reserved] | `0xA2` App-Specific Awaiting Others | `0xB2` [reserved] | `0xC2` [reserved] | `0xD2` [reserved] | `0xE2` Awaiting Other Signatures or Keys | `0xF2` Awaiting Off-Chain Process | -| `0x*3` | `0x03` Accepted | `0x13` Permission Requested | `0x23` Match Request Sent | `0x33` Offer Sent or Voted | `0x43` Queued | `0x53` Hold or Escrow | `0x63` [reserved] | `0x73` [reserved] | `0x83` [reserved] | `0x93` [reserved] | `0xA3` App-Specific Acceptance | `0xB3` [reserved] | `0xC3` [reserved] | `0xD3` [reserved] | `0xE3` Signed | `0xF3` Off-Chain Process Started | -| `0x*4` | `0x04` Lower Limit or Insufficient | `0x14` Too Open / Insecure | `0x24` Below Range or Underflow | `0x34` Quorum Not Reached | `0x44` Not Available Yet | `0x54` Insufficient Funds | `0x64` [reserved] | `0x74` [reserved] | `0x84` [reserved] | `0x94` [reserved] | `0xA4` App-Specific Below Condition | `0xB4` [reserved] | `0xC4` [reserved] | `0xD4` [reserved] | `0xE4` Unsigned or Untrusted | `0xF4` Off-Chain Service Unreachable | -| `0x*5` | `0x05` Receiver Action Required | `0x15` Needs Your Permission or Request for Continuation | `0x25` Request for Match | `0x35` Receiver's Ratification Requested | `0x45` Awaiting Your Availability | `0x55` Funds Requested | `0x65` [reserved] | `0x75` [reserved] | `0x85` [reserved] | `0x95` [reserved] | `0xA5` App-Specific Receiver Action Requested | `0xB5` [reserved] | `0xC5` [reserved] | `0xD5` [reserved] | `0xE5` Signature Required | `0xF5` Off-Chain Action Required | -| `0x*6` | `0x06` Upper Limit | `0x16` Revoked or Banned | `0x26` Above Range or Overflow | `0x36` Offer or Vote Limit Reached | `0x46` Expired | `0x56` Transfer Volume Exceeded | `0x66` [reserved] | `0x76` [reserved] | `0x86` [reserved] | `0x96` [reserved] | `0xA6` App-Specific Expiry or Limit | `0xB6` [reserved] | `0xC6` [reserved] | `0xD6` [reserved] | `0xE6` Known to be Compromised | `0xF6` Off-Chain Expiry or Limit Reached | -| `0x*7` | `0x07` [reserved] | `0x17` [reserved] | `0x27` [reserved] | `0x37` [reserved] | `0x47` [reserved] | `0x57` [reserved] | `0x67` [reserved] | `0x77` [reserved] | `0x87` [reserved] | `0x97` [reserved] | `0xA7` [reserved] | `0xB7` [reserved] | `0xC7` [reserved] | `0xD7` [reserved] | `0xE7` [reserved] | `0xF7` [reserved] | -| `0x*8` | `0x08` Duplicate, Unnecessary, or Inapplicable | `0x18` Not Applicable to Current State | `0x28` Duplicate, Conflict, or Collision | `0x38` Already Voted | `0x48` Already Done | `0x58` Funds Not Required | `0x68` [reserved] | `0x78` [reserved] | `0x88` [reserved] | `0x98` [reserved] | `0xA8` App-Specific Inapplicable Condition | `0xB8` [reserved] | `0xC8` [reserved] | `0xD8` [reserved] | `0xE8` Already Signed or Not Encrypted | `0xF8` Duplicate Off-Chain Request | -| `0x*9` | `0x09` [reserved] | `0x19` [reserved] | `0x29` [reserved] | `0x39` [reserved] | `0x49` [reserved] | `0x59` [reserved] | `0x69` [reserved] | `0x79` [reserved] | `0x89` [reserved] | `0x99` [reserved] | `0xA9` [reserved] | `0xB9` [reserved] | `0xC9` [reserved] | `0xD9` [reserved] | `0xE9` [reserved] | `0xF9` [reserved] | -| `0x*A` | `0x0A` [reserved] | `0x1A` [reserved] | `0x2A` [reserved] | `0x3A` [reserved] | `0x4A` [reserved] | `0x5A` [reserved] | `0x6A` [reserved] | `0x7A` [reserved] | `0x8A` [reserved] | `0x9A` [reserved] | `0xAA` [reserved] | `0xBA` [reserved] | `0xCA` [reserved] | `0xDA` [reserved] | `0xEA` [reserved] | `0xFA` [reserved] | -| `0x*B` | `0x0B` [reserved] | `0x1B` [reserved] | `0x2B` [reserved] | `0x3B` [reserved] | `0x4B` [reserved] | `0x5B` [reserved] | `0x6B` [reserved] | `0x7B` [reserved] | `0x8B` [reserved] | `0x9B` [reserved] | `0xAB` [reserved] | `0xBB` [reserved] | `0xCB` [reserved] | `0xDB` [reserved] | `0xEB` [reserved] | `0xFB` [reserved] | -| `0x*C` | `0x0C` [reserved] | `0x1C` [reserved] | `0x2C` [reserved] | `0x3C` [reserved] | `0x4C` [reserved] | `0x5C` [reserved] | `0x6C` [reserved] | `0x7C` [reserved] | `0x8C` [reserved] | `0x9C` [reserved] | `0xAC` [reserved] | `0xBC` [reserved] | `0xCC` [reserved] | `0xDC` [reserved] | `0xEC` [reserved] | `0xFC` [reserved] | -| `0x*D` | `0x0D` [reserved] | `0x1D` [reserved] | `0x2D` [reserved] | `0x3D` [reserved] | `0x4D` [reserved] | `0x5D` [reserved] | `0x6D` [reserved] | `0x7D` [reserved] | `0x8D` [reserved] | `0x9D` [reserved] | `0xAD` [reserved] | `0xBD` [reserved] | `0xCD` [reserved] | `0xDD` [reserved] | `0xED` [reserved] | `0xFD` [reserved] | -| `0x*E` | `0x0E` [reserved] | `0x1E` [reserved] | `0x2E` [reserved] | `0x3E` [reserved] | `0x4E` [reserved] | `0x5E` [reserved] | `0x6E` [reserved] | `0x7E` [reserved] | `0x8E` [reserved] | `0x9E` [reserved] | `0xAE` [reserved] | `0xBE` [reserved] | `0xCE` [reserved] | `0xDE` [reserved] | `0xEE` [reserved] | `0xFE` [reserved] | -| `0x*F` | `0x0F` Informational or Metadata | `0x1F` Permission Details or Control Conditions | `0x2F` Matching Meta or Info | `0x3F` Negotiation Rules or Participation Info | `0x4F` Availability Rules or Info (ex. time since or until) | `0x5F` Token or Financial Information | `0x6F` [reserved] | `0x7F` [reserved] | `0x8F` [reserved] | `0x9F` [reserved] | `0xAF` App-Specific Meta or Info | `0xBF` [reserved] | `0xCF` [reserved] | `0xDF` [reserved] | `0xEF` Cryptography, ID, or Proof Metadata | `0xFF` Off-Chain Info or Meta | - -### Example Function Change - -```solidity -uint256 private startTime; -mapping(address => uint) private counters; - -// Before -function increase() public returns (bool _available) { - if (now < startTime && counters[msg.sender] == 0) { - return false; - }; - - counters[msg.sender] += 1; - return true; -} - -// After -function increase() public returns (byte _status) { - if (now < start) { return hex"44"; } // Not yet available - if (counters[msg.sender] == 0) { return hex"10"; } // Not authorized - - counters[msg.sender] += 1; - return hex"01"; // Success -} -``` - -### Example Sequence Diagrams - -``` -0x03 = Waiting -0x31 = Other Party (ie: not you) Agreed -0x41 = Available -0x44 = Not Yet Available - - - Exchange - - -AwesomeCoin DEX TraderBot - + + + - | | buy(AwesomeCoin) | - | | <------------------------+ - | buy() | | - | <---------------------+ | - | | | - | Status [0x44] | | - +---------------------> | Status [0x44] | - | +------------------------> | - | | | - | | isDoneYet() | - | | <------------------------+ - | | | - | | Status [0x44] | - | +------------------------> | - | | | - | | | - | Status [0x41] | | - +---------------------> | | - | | | - | buy() | | - | <---------------------+ | - | | | - | | | - | Status [0x31] | | - +---------------------> | Status [0x31] | - | +------------------------> | - | | | - | | | - | | | - | | | - + + + -``` - - - -``` -0x01 = Generic Success -0x10 = Disallowed -0x11 = Allowed - - Token Validation - - - Buyer RegulatedToken TokenValidator IDChecker SpendLimiter - + + + + + - | buy() | | | | - +------------------------> | check() | | | - | +-----------------------> | check() | | - | | +-----------------------> | | - | | | | | - | | | Status [0x10] | | - | | Status [0x10] | <-----------------------+ | - | revert() | <-----------------------+ | | - | <------------------------+ | | | - | | | | | -+---------------------------+ | | | | -| | | | | | -| Updates ID with provider | | | | | -| | | | | | -+---------------------------+ | | | | - | | | | | - | buy() | | | | - +------------------------> | check() | | | - | +-----------------------> | check() | | - | | +-----------------------> | | - | | | | | - | | | Status [0x11] | | - | | | <-----------------------+ | - | | | | | - | | | | check() | - | | +-------------------------------------------> | - | | | | | - | | | | Status [0x11] | - | | Status [0x11] | <-------------------------------------------+ - | Status [0x01] | <-----------------------+ | | - | <------------------------+ | | | - | | | | | - | | | | | - | | | | | - + + + + + -``` - -## Rationale - -### Encoding - -Status codes are encoded as a `byte`. Hex values break nicely into high and low nibbles: `category` and `reason`. For instance, `0x01` stands for general success (ie: `true`) and `0x00` for general failure (ie: `false`). - -As a general approach, all even numbers are blocking conditions (where the receiver does not have control), and odd numbers are nonblocking (the receiver is free to contrinue as they wish). This aligns both a simple bit check with the common encoding of Booleans. - -`bytes1` is very lightweight, portable, easily interoperable with `uint8`, cast from `enum`s, and so on. - -#### Alternatives - -Alternate schemes include `bytes32` and `uint8`. While these work reasonably well, they have drawbacks. - -`uint8` feels even more similar to HTTP status codes, and enums don't require as much casting. However does not break as evenly as a square table (256 doesn't look as nice in base 10). - -Packing multiple codes into a single `bytes32` is nice in theory, but poses additional challenges. Unused space may be interpreted as `0x00 Failure`, you can only efficiently pack four codes at once, and there is a challenge in ensuring that code combinations are sensible. Forcing four codes into a packed representation encourages multiple status codes to be returned, which is often more information than strictly necessarily. This can lead to paradoxical results (ex `0x00` and `0x01` together), or greater resources allocated to interpreting 2564 (4.3 billion) permutations. - -### Multiple Returns - -While there may be cases where packing a byte array of status codes may make sense, the simplest, most forwards-compatible method of transmission is as the first value of a multiple return. - -Familiarity is also a motivating factor. A consistent position and encoding together follow the principle of least surprise. It is both viewable as a "header" in the HTTP analogy, or like the "tag" in BEAM tagged tuples. - -### Human Readable - -Developers should not be required to memorize 256 codes. However, they break nicely into a table. Cognitive load is lowered by organizing the table into categories and reasons. `0x10` and `0x11` belong to the same category, and `0x04` shares a reason with `0x24` - -While this repository includes helper enums, we have found working directly in the hex values to be quite natural. Status code `0x10` is just as comfortable as HTTP 401, for example. - -#### Localizations - -One commonly requested application of this spec is human-readable translations of codes. This has been moved to its own proposal: [ERC-1444](./eip-1444.md), primarily due to a desire to keep both specs focused. - -### Extensibility - -The `0xA` category is reserved for application-specific statuses. In the case that 256 codes become insufficient, `bytes1` may be embedded in larger byte arrays. - -### EVM Codes - -The EVM also returns a status code in transactions; specifically `0x00` and `0x01`. This proposal both matches the meanings of those two codes, and could later be used at the EVM level. - -### Empty Space - -Much like how HTTP status codes have large unused ranges, there are totally empty sections in this proposal. The intent is to not impose a complete set of codes up front, and to allow users to suggest uses for these spaces as time progresses. - -### Beyond Errors - -This spec is intended to be much more than a set of common errors. One design goal is to enable easier contract-to-contract communication, protocols built on top of status codes, and flows that cross off-chain. Many of these cases include either expected kinds of exception state (as opposed to true errors), neutral states, time logic, and various successes. - -Just like how HTTP 200 has a different meaning from HTTP 201, ERC-1066 status codes can relay information between contract beyond simply pass or fail. They can be thought of as the edges in a graph that has smart contracts as nodes. - -### Fully `revert`able - -_This spec is fully compatible with `revert`-with-reason and does not intend to supplant it in any way._ Both by reverting with a common code, the developer can determine what went wrong from a set of known error states. - -Further, by leveraging ERC-1066 and a translation table (such as in ERC-1444) in conjunction, developers and end users alike can receive fully automated human-readable error messages in the language and phrasing of their choice. - -### Nibble Order - -Nibble order makes no difference to the machine, and is purely mnemonic. This design was originally in opposite order, but changed it for a few convenience factors. Since it's a different scheme from HTTP, it may feel strange initially, but becomes very natural after a couple hours of use. - -#### Short Forms - -Generic is `0x0*`, general codes are consistent with their integer representations - -```solidity -hex"1" == hex"01" == 1 // with casting -``` - -#### Contract Categories - -Many applications will always be part of the same category. For instance, validation will generally be in the `0x10` range. - -```solidity -contract Whitelist { - mapping(address => bool) private whitelist; - uint256 private deadline; - byte constant private prefix = hex"10"; - - check(address _, address _user) returns (byte _status) { - if (now >= deadline) { return prefix | 5; } - if (whitelist[_user]) { return prefix | 1; } - return prefix; - } -} -``` - -#### Helpers - -This above also means that working with app-specific enums is slightly easier, and also saves gas (fewer operations required). - -```solidity -enum Sleep { - Awake, - Asleep, - BedOccupied, - WindingDown -} - -// From the helper library - -function appCode(Sleep _state) returns (byte code) { - return byte(160 + _state); // 160 = 0xA0 -} - -// Versus - -function appCode(Sleep _state) returns (byte code) { - return byte((16 * _state) + 10); // 10 = 0xA -} -``` - -## Implementation - -Reference cases and helper libraries (Solidity and JS) can be found at: -* [Source Code](https://github.com/fission-suite/fission-codes/) -* [Package on npm](https://www.npmjs.com/package/fission-codes/) - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1066.md diff --git a/EIPS/eip-107.md b/EIPS/eip-107.md index 3920c20a5bd02e..c730bd4d3c084f 100644 --- a/EIPS/eip-107.md +++ b/EIPS/eip-107.md @@ -8,14 +8,14 @@ type: Standards Track category: Interface --- -Abstract -======== +## Abstract + This draft EIP describes the details of an authorization method that if provided by rpc enabled ethereum nodes would allow regular websites to send transactions (via ```eth_sendTransaction```) without the need to enable CORS. Instead, user would be asked to confirm the transaction via an html popup. Every read only rpc call the dapp wants to perform is redirected to an invisible iframe from the node's domain and for every transaction that the dapp wish to execute, an html popup is presented to the user to allow him/her to cancel or confirm the transaction. This allows the dapp to connect to the node's rpc api without being granted any kind of privileges. This allows users to safely interact with dapps running in their everyday web browser while their accounts are unlocked. In case the account is not unlocked, and the node has allowed the "personal" api via rpc,the html page also allow the user to enter their password to unlock the account for the scope of the transaction. -Motivation -========== +## Motivation + Currently, if a user navigates to a dapp running on a website using her/his everyday browser, the dapp will by default have no access to the rpc api for security reasons. The user will have to enable CORS for the website's domain in order for the dapp to work. Unfortunately if the user does so, the dapp will be able to send transactions from any unlocked account without the need for any user consent. In other words, not only does the user need to change the node's default setting, but the user is also forced to trust the dapp in order to use it. This is of course not acceptable and forces existing dapps to rely on the use of workarounds like: - if the transaction is a plain ether transfer, the user is asked to enter it in a dedicated trusted wallet like "Mist" - For more complex case, the user is asked to enter the transaction manually via the node command line interface. @@ -25,27 +25,27 @@ This proposal aims to provide a safe and user friendly alternative. Here are some screenshots of the provided implementation of that html popup: -Account unlocked : ------------------ +### Account unlocked + When the account is already unlocked, the user is presented with the following popup for every transaction that the dapp attempts to make: ![](../assets/eip-107/authorization.png) -Account locked and no "personal" api exposed via rpc: ------------------ +### Account locked and no "personal" api exposed via rpc: + When the account is locked, and the node does not provide access to account unlocking via its rpc interface, the following popup will be presented. This is not ideal since this requires the user to know how to unlock an account: ![](../assets/eip-107/authorization-locked.png) -Account locked but node exposing the "personal" api via rpc : ------------------ +### Account locked but node exposing the "personal" api via rpc : + A better option is to ask the user for their password, but this is only possible if the node allows access to the "personal" api via rpc. In such case, the following dialog will be presented to the user so he/she can accept the transaction by providing the password required to unlock the account: ![](../assets/eip-107/authorization-password.png) -Specification -============= +## Specification + In order for the mechanism to work, the node needs to serve an html file via http at the url \/authorization.html This file will then be used by the dapp in 2 different modes (invisible iframe and popup window). @@ -90,22 +90,22 @@ the error object cannot be a javascript Error object due to postMessage limitati ``` -Rationale -========= +## Rationale + The design for that proposal was chosen for its simplicity and security. A previous idea was to use an oauth-like protocol in order for the user to accept or deny a transaction request. It would have required deeper code change in the node and some geth contributors argues that such change did not fit into geth code base as it would have required dapp aware code. -The current design, instead has a very simple implementation (self contained html file that can be shared across node's implementation) and its safeness is guarantess by browsers' cross domain policies. +The current design, instead has a very simple implementation (self contained html file that can be shared across node's implementation) and its safeness is guaranteed by browsers' cross domain policies. The use of iframe/ window was required to have both security and user friendliness. The invisible iframe allows the dapp to execute read only calls without the need for user input, and the window ensures user approval before making a call. While we could have made it without the window mode by making the iframe confirmation use the native browser ```window.confirm``` dialog, this would have prevented the use of a more elegant confirmation popup that the current design allows. It also happens to be that the ```window.confirm``` is not safe in some browsers, as it gives focus to the accept option and can be triggered automatically (https://bugs.chromium.org/p/chromium/issues/detail?id=260653). -Implementations -=============== +## Implementations + In order to implement this design, the following html file or an equivalent one needs to be served at the url \/authorization.html That's it. -``` +```html @@ -612,6 +612,7 @@ That's it. ``` + ## Copyright Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1077.md b/EIPS/eip-1077.md index 1efe6a144ddf8b..470bf46b6f1727 100644 --- a/EIPS/eip-1077.md +++ b/EIPS/eip-1077.md @@ -1,229 +1,7 @@ --- eip: 1077 -title: Gas relay for contract calls -author: Alex Van de Sande , Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://ethereum-magicians.org/t/erc1077-and-1078-the-magic-of-executable-signed-messages-to-login-and-do-actions/351 -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-04 -requires: 20, 191, 1271, 1344 +status: Moved --- - -## Simple Summary - -A standard interface for gas abstraction in top of smart contracts. - -Allows users to offer [EIP-20] token for paying the gas used in a call. - -## Abstract - -A main barrier for adoption of DApps is the requirement of multiple tokens for executing in chain actions. Allowing users to sign messages to show intent of execution, but allowing a third party relayer to execute them can circumvent this problem, while ETH will always be required for ethereum transactions, it's possible for smart contract to take [EIP-191] signatures and forward a payment incentive to an untrusted party with ETH for executing the transaction. - -## Motivation - -Standardizing a common format for them, as well as a way in which the user allows the transaction to be paid in tokens, gives app developers a lot of flexibility and can become the main way in which app users interact with the Blockchain. - - -## Specification - -### Methods - -#### executeGasRelay - -Executes `_execData` with current `lastNonce()` and pays `msg.sender` the gas used in specified `_gasToken`. - -```solidity -function executeGasRelay(bytes calldata _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer, bytes calldata _signature) external; -``` - -### executeGasRelayMsg - -Returns the `executeGasRelay` message used for signing messages.. - -```solidity -function executeGasRelayMsg(uint256 _nonce, bytes memory _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer) public pure returns (bytes memory); -``` - -#### executeGasRelayERC191Msg - -Returns the [EIP-191] of `executeGasRelayMsg` used for signing messages and for verifying the execution. - -```solidity -function executeGasRelayERC191Msg(uint256 _nonce, bytes memory _execData, uint256 _gasPrice, uint256 _gasLimit, address _gasToken, address _gasRelayer) public view returns (bytes memory); -``` - -#### lastNonce - -Returns the current nonce for the gas relayed messages. - -```solidity -function lastNonce() public returns (uint nonce); -``` - -### Signed Message - -The signed message require the following fields: - -* Nonce: A nonce *or* a timestamp; -* Execute Data: the bytecode to be executed by the account contract; -* Gas Price: The gas price (paid in the selected token); -* Gas Limit: The gas reserved to the relayed execution; -* Gas Token: A token in which the gas will be paid (leave 0 for ether); -* Gas Relayer: the beneficiary of gas refund for this call (leave 0 for `block.coinbase`) . - -#### Signing the message - -The message **MUST** be signed as [EIP-191] standard, and the called contract **MUST** also implement [EIP-1271] which must validate the signed messages. - -Messages **MUST** be signed by the owner of the account contract executing. If the owner is a contract, it must implement [EIP-1271] interface and forward validation to it. - -In order to be compliant, the transaction **MUST** request to sign a "messageHash" that is a concatenation of multiple fields. - -The fields **MUST** be constructed as this method: - -The first and second fields are to make it [EIP-191] compliant. Starting a transaction with `byte(0x19)` ensure the signed data from being a [valid ethereum transaction](https://github.com/ethereum/wiki/wiki/RLP). The second argument is a version control byte. The third being the validator address (the account contract address) according to version 0 of [EIP-191]. The remaining arguments being the application specific data for the gas relay: chainID as per [EIP-1344], execution nonce, execution data, agreed gas Price, gas limit of gas relayed call, gas token to pay back and gas relayer authorized to receive reward. - -The [EIP-191] message must be constructed as following: -```solidity -keccak256( - abi.encodePacked( - byte(0x19), //ERC-191 - the initial 0x19 byte - byte(0x0), //ERC-191 - the version byte - address(this), //ERC-191 - version data (validator address) - chainID, - bytes4( - keccak256("executeGasRelay(uint256,bytes,uint256,uint256,address,address)") - ), - _nonce, - _execData, - _gasPrice, - _gasLimit, - _gasToken, - _gasRelayer - ) -) -``` - -## Rationale - -User pain points: - -* users don't want to think about ether -* users don't want to think about backing up private keys or seed phrases -* users want to be able to pay for transactions using what they already have on the system, be apple pay, xbox points or even a credit card -* Users don’t want to sign a new transaction at every move -* Users don’t want to download apps/extensions (at least on the desktop) to connect to their apps - -App developer pain points: -* Many apps use their own token and would prefer to use those as the main accounting -* Apps want to be able to have apps in multiple platforms without having to share private keys between devices or have to spend transaction costs moving funds between them -* Token developers want to be able for their users to be able to move funds and pay fees in the token -* While the system provides fees and incentives for miners, there are no inherent business model for wallet developers (or other apps that initiate many transactions) - -Using signed messages, specially combined with an account contract that holds funds, and multiple disposable ether-less keys that can sign on its behalf, solves many of these pain points. - -### Multiple signatures - -More than one signed transaction with the same parameter can be executed by this function at the same time, by passing all signatures in the `messageSignatures` field. That field will split the signature in multiple 72 character individual signatures and evaluate each one. This is used for cases in which one action might require the approval of multiple parties, in a single transaction. - -If multiple signatures are required, then all signatures should then be *ordered by account* and the account contract should implement signatures checks locally (`JUMP`) on [EIP-1271] interface which might forward (`STATIC_CALL`) the [EIP-1271] signature check to owner contract. - -### Keep track of nonces: - -Note that `executeGasRelay` function does not take a `_nonce` as parameter. The contract knows what is the current nonce, and can only execute the transactions in order, therefore there is no reason - -Nonces work similarly to normal ethereum transactions: a transaction can only be executed if it matches the last nonce + 1, and once a transaction has occurred, the `lastNonce` will be updated to the current one. This prevents transactions to be executed out of order or more than once. - -Contracts may accept transactions without nonce (nonce = 0). The contract then must keep the full hash of the transaction to prevent it from being replayed. This would allows contracts to have more flexibilities as you can sign a transaction that can be executed out of order or not at all, but it uses more memory for each transaction. It can be used, for instance, for transactions that the user wants to schedule in the future but cannot know its future nonce, or transactions that are made for state channel contracts that are not guaranteed to be executed or are only executed when there's some dispute. - -### Execute transaction - -After signature validation, the evaluation of `_execBytes` is up to the account contract implementation, it's role of the wallet to properly use the account contract and it's gas relay method. -A common pattern is to expose an interface which can be only called by the contract itself. The `_execBytes` could entirely forward the call in this way, as example: `address(this).call.gas(_gasLimit)(_execData);` -Where `_execData` could call any method of the contract itself, for example: - -- `call(address to, uint256 value, bytes data)`: allow any type of ethereum call be performed; -- `create(uint256 value, bytes deployData)`: allows create contract -- `create2(uint256 value, bytes32 salt, bytes deployData)`: allows create contract with deterministic address -- `approveAndCall(address token, address to, uint256 value, bytes data)`: allows safe approve and call of an ERC20 token. -- `delegatecall(address codeBase, bytes data)`: allows executing code stored on other contract -- `changeOwner(address newOwner)`: Some account contracts might allow change of owner -- `foo(bytes bar)`: Some account contracts might have custom methods of any format. - -The standardization of account contracts is not scope of this ERC, and is presented here only for illustration on possible implementations. -Using a self call to evaluate `_execBytes` is not mandatory, depending on the account contract logic, the evaluation could be done locally. - -### Gas accounting and refund - -The implementing contract must keep track of the gas spent. One way to do it is to first call `gasLeft()` at the beginning of the function and then after executing the desired action and compare the difference. - -The contract then will make a token transfer (or ether, if `tokenAddress` is nil) in the value of `gasSpent * gasPrice` to the `_gasRelayer`, that is the account that deployed the message. - -If `_gasRelayer` is zero, then the funds **MUST** go to `block.coinbase`. - -If there are not enough funds, or if the total surpasses `gasLimit` then the transaction **MUST** revert. - -If the executed transaction fails internally, nonces should still be updated and gas needs to be paid. - -Contracts are not obligated to support ether or any other token they don’t want and can be implemented to only accept refunds in a few tokens of their choice. - -### Usage examples - -This scheme opens up a great deal of possibilities on interaction as well as different experiments on business models: - -* Apps can create individual identities contract for their users which holds the actual funds and then create a different private key for each device they log into. Other apps can use the same identity and just ask to add permissioned public keys to manage the device, so that if one individual key is lost, no ether is lost. -* An app can create its own token and only charge their users in its internal currency for any ethereum transaction. The currency units can be rounded so it looks more similar to to actual amount of transactions: a standard transaction always costs 1 token, a very complex transaction costs exactly 2, etc. Since the app is the issuer of the transactions, they can do their own Sybil verifications and give a free amount of currency units to new users to get them started. -* A game company creates games with a traditional monthly subscription, either by credit card or platform-specific microtransactions. Private keys never leave the device and keep no ether and only the public accounts are sent to the company. The game then signs transactions on the device with gas price 0, sends them to the game company which checks who is an active subscriber and batches all transactions and pays the ether themselves. If the company goes bankrupt, the gamers themselves can set up similar subscription systems or just increase the gas price. End result is a **ethereum based game in which gamers can play by spending apple, google or xbox credits**. -* A standard token is created that doesn’t require its users to have ether, and instead allows tokens to be transferred by paying in tokens. A wallet is created that signs messages and send them via whisper to the network, where other nodes can compete to download the available transactions, check the current gas price, and select those who are paying enough tokens to cover the cost. **The result is a token that the end users never need to keep any ether and can pay fees in the token itself.** -* A DAO is created with a list of accounts of their employees. Employees never need to own ether, instead they sign messages, send them to whisper to a decentralized list of relayers which then deploy the transactions. The DAO contract then checks if the transaction is valid and sends ether to the deployers. Employees have an incentive not to use too many of the companies resources because they’re identifiable. The result is that the users of the DAO don't need to keep ether, and **the contract ends up paying for it's own gas usage**. - -## Backwards Compatibility - -There is no issues with backwards compatibility, however for future upgrades, as `_execData` contains arbitrary data evaluated by the account contract, it's up to the contract to handle properly this data and therefore contracts can gas relay any behavior with the current interface. - -## Test Cases - -TBD - -## Implementation - -One initial implementation of such a contract can be found at [Status.im account-contracts repository](https://github.com/status-im/account-contracts/blob/develop/contracts/account/AccountGasAbstract.sol) - -Other version is implemented as Gnosis Safe variant in: https://github.com/status-im/safe-contracts - -### Similar implementations - -The idea of using signed messages as executable intent has been around for a while and many other projects are taking similar approaches, which makes it a great candidate for a standard that guarantees interoperability: - -* [EIP-877](https://github.com/ethereum/EIPs/pull/877) An attempt of doing the same but with a change in the protocol -* [Status](https://github.com/status-im/ideas/issues/73) -* [Aragon](https://github.com/aragonlabs/pay-protocol) (this might not be the best link to show their work in this area) -* [Token Standard Functions for Preauthorized Actions](https://github.com/ethereum/EIPs/issues/662) -* [Token Standard Extension 865](https://github.com/ethereum/EIPs/issues/865) -* [Iuri Matias: Transaction Relay](https://github.com/iurimatias/TransactionRelay) -* [uPort: Meta transactions](https://github.com/uport-project/uport-identity#send-a-meta-tx) -* [uPort: safe Identities](https://github.com/uport-project/uport-identity/blob/develop/docs/txRelay.md) -* [Gnosis safe contracts](https://github.com/gnosis/safe-contracts) - -Swarm city uses a similar proposition for etherless transactions, called [Gas Station Service](https://github.com/swarmcity/SCLabs-gasstation-service), but it's a different approach. Instead of using signed messages, a traditional ethereum transaction is signed on an etherless account, the transaction is then sent to a service that immediately sends the exact amount of ether required and then publishes the transaction. - -## Security Considerations - -Deployers of transactions (relayers) should be able to call untrusted contracts, which provides no guarantees that the contract they are interacting with correctly implements the standard and they will be reimbursed for gas. To prevent being fooled by bad implementations, relayers must **estimate the outcome of a transaction**, and only include/sign transactions which have a desired outcome. - -Is also interest of relayers to maintaining a private reputation of contracts they interact with, as well as keep track of which tokens and for which `gasPrice` they’re willing to deploy transactions. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - -## References - -* [Universal Logins talk at UX Unconf, Toronto](https://www.youtube.com/watch?v=qF2lhJzngto) - -[EIP-20]: ./eip-20.md -[EIP-191]: ./eip-191.md -[EIP-1271]: ./eip-1271.md -[EIP-1344]: ./eip-1344.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1077.md diff --git a/EIPS/eip-1078.md b/EIPS/eip-1078.md index 7990475fbcd98b..12678b4b874462 100644 --- a/EIPS/eip-1078.md +++ b/EIPS/eip-1078.md @@ -1,121 +1,7 @@ --- eip: 1078 -title: Universal login / signup using ENS subdomains -author: Alex Van de Sande -discussions-to: https://ethereum-magicians.org/t/erc1077-and-1078-the-magic-of-executable-signed-messages-to-login-and-do-actions/351 -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-04 -requires: 191, 681, 725, 1077 +status: Moved --- -## Abstract - -This presents a method to replace the usual signup/login design pattern with a minimal ethereum native scheme, that doesn’t require passwords, backing up private keys nor typing seed phrases. From the user point of view it will be very similar to patterns they’re already used to with second factor authentication (without relying in a central server), but for dapp developers it requires a new way to think about ethereum transactions. - - -## Simple Summary - -The unique identifier of the user is a contract which implements both Identity and the Executable Signed Messages ERCs. The user should not need provide this address directly, only a ens name pointing to it. These types of contracts are indirectly controlled by private keys that can sign messages indicating intents, which are then deployed to the contract by a third party (or a decentralized network of deployers). - -In this context, therefore, a device "logging into" an app using an identity, means that the device will generate a private key locally and then request an authorization to add that key as one of the signers of that identity, with a given set of permissions. Since that private key is only used for signing messages, it is not required to hold ether, tokens or assets, and if lost, it can be simply be replaced by a new one – the user's funds are kept on the identity contract. - -In this context, ethereum accounts are used in a manner more similar to auth tokens, rather than unique keys. - -The login process is as follows: - -#### 1) Request a name from the user - -The first step of the process is to request from the user the ENS name that points to their identity. If the user doesn’t have a login set up, the app should–if they have an integrated identity manager–provide an option to provide a subdomain or a name they own. - -**UX Note:** there are many ways to provide this interface, the app can ask if they want to signup/login before hand or simply directly ask them to type the name. Note that since it’s trivial to verify if a username exists, your app should adapt to it gracefully and not require the user to type their name twice. If they ask to signup and provide a name that exists then ask them if they want to login using that name, or similarly if they ask to connect to an existing name but type a non-existent name show them a nice alert and ask them if they want to create that name now. Don’t force them to type the same name twice in two different fields. - -#### 2.a) Create a new identity - -If the user doesn’t have an identity, the app should provide the option to create one for them. Each app must have one or more domains they control which they can create immediate subdomains on demand. The app therefore will make these actions on the background: - -1. Generate a private key which it will keep saved locally on the device or browser, the safest way possible. -2. Create (or set up) an identity contract which supports both ERC720 and ERC1077 -3. Register the private key created on step 1 as the *only* admin key of the contract (the app must not add any app-controlled key, except as recovery option - see 5) -4. Register the requested subdomain and transfer its ownership to the contract (while the app controls the main domain and may keep the option to reassign them at will, the ownership of the subdomain itself should belong to the identity, therefore allowing them to transfer it) -5. (Optionally) Register a recovery method on the contract, which allows the user to regain access to the contract in case the main key is lost. - -All those steps can be designed to be set up in a single ethereum transaction. Since this step is not free, the app reserves the right to charge for registering users, or require the user to be verified in a sybil resistant manner of the app’s choosing (captcha, device ID registration, proof of work, etc) - -The user shouldn’t be forced to wait for transaction confirmation times. Instead, have an indicator somewhere on the app the shows the progress and then allow the user to interact with your app normally. It’s unlikely that they’ll need the identity in the first few minutes and if something goes wrong (username gets registered at the same time), you can then ask the user for an action. - -**Implementation note:** in order to save gas, some of these steps can be done in advance. The app can automatically deploy a small number of contracts when the gas price is low, and set up all their main variables to be 0xFFFFFF...FFFFF. These should be considered ‘vacant’ and when the user registers one, they will get a gas discount for freeing up space on the chain. This has the added benefit of allowing the user a choice in contract address/icon. - -#### 2.b) Connect to an existing identity - -If the user wants to connect with an existing identity, then the first thing the app needs to understand is what level of privilege it’s going to ask for: - -**Manager** the higher level, allows the key to initiate or sign transactions that change the identity itself, like adding or removing keys. An app should only require this level if it integrates an identity manager. Depending on how the identity is set up, it might require signature from more keys before these transactions can be deployed. - -**Action** this level allows the key to initiate or sign transactions on address other than itself. It can move funds, ether, assets etc. An app should only require this level of privilege if it’s a general purpose wallet or browser for sending ethereum transactions. Depending on how the identity is set up, it might require signature from more keys before these transactions can be deployed. - -**Encryption** the lower level has no right to initiate any transactions, but it can be used to represent the user in specific instances or off-chain signed messages. It’s the ideal level of privilege for games, chat or social media apps, as they can be used to sign moves, send messages, etc. If a game requires actual funds (say, to start a game with funds in stake) then it should still use the encryption level, and then require the main wallet/browser of the user to sign messages using the ethereum URI standard. - -Once the desired level is known, the app must take these steps: - -1. **Generate a private key** which it will keep saved locally on the device or browser, the safest way possible. -2. **Query ens** to figure the existing address of the identity -3. **Generate the bytecode** for a transaction calling the function `addKey(PUBLICKEY,LEVEL)`. -4. **Broadcast a transaction request on a whisper channel** or some other decentralized network of peers. Details on this step require further discussions -1. **If web3 is available** then attempt calling web3.eth.sendTransaction. This can be automatic or prompted by user action. -1. **Attempt calling a URI** if the app supports [URL format for transaction requests EIP](./eip-681.md) then attempt calling this. This can be automatic or prompted by user action. -1. **Show a QR code**: with an EIP681 formatted URL. That QR code can be clickable to attempt to retry the other options, but it should be done last: if step 1 works, the user should receive a notification on their compatible device and won't need to use the QR code. - -Here's an example of a EIP681 compatible address to add a public key generated locally in the app: - -`ethereum:bob.example.eth?function=addKey(address='0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',uint=1)` - -If adding the new key requires multiple signatures, or if the app receiving that request exclusiveky deals with executable signed messages and has no ether on itself, then it should follow the steps in the next section on how to request transactions. - -As before, the user shouldn’t be forced to wait for transaction confirmation times. Instead, have an indicator somewhere on the app the shows the progress and then allow the user to interact with your app normally. - - - -#### 3) Request transactions - -After step 2, the end result should be that your app should have the identity address of the user, their main ens name and a private key, whose public account is listed on the identity as one of their keys, with roles being either manager, action or encryption. Now it can start using that information to sign and execute transactions. - -**Not all transactions need to be on chain**, actually most common uses of signed messages should be off chain. If you have a chat app, for instance, you can use the local key for signing messages and sending it to the other parties, and they can just query the identity contract to see if that key actually comes from the user. If you have a game with funds at stake, only the first transaction moving funds and setting up the initial game needs to be executed by the identity: at each turn the players can sign a hash of the current state of the board and at the end, the last two plays can be used to determine the winner. Notice that keys can be revoked at any time, so your app should take that in consideration, for instance saving all keys at the start of the game. Keys that only need this lower level of privilege, should be set at level 4 (encryption). - -Once you decided you actually need an on-chain transaction, follow these steps: - -1. **Figure out the TO, FROM, VALUE and DATA**. These are the basics of any ethereum transaction. `from` is the compatible contract you want the transaction to be deployed from. -2. **Check the privilege level you need:** if the `to` and `from` fields are the same contract, ie, if the transaction requires the identity to act upon itself (for instance, when adding or removing a key) then you need level 1 (management), otherwise it's 2 (action). Verify if the key your app owns correspond to the required level. -3. **Verify how many keys are required** by calling `requiredSignatures(uint level)` on the target contract -4. **Figure out gasLimit**: Estimate the gas cost of the desired transaction, and add a margin (recommended: add 100k gas) -5. **Figure out gasToken and gasPrice**: Check the current gas price considering network congestions and the market price of the token the user is going to pay with. Leave gasToken as 0 for ether. Leave gasPrice as 0 if you are deploying it yourself and subsidizing the costs elsewhere. -6. **Sign an executable signed transaction** by following that standard. - -After having all the signed executable message, we need to deploy it to the chain. If the transaction only requires a single signature, then the app provider can deploy it themselves. Send the transaction to the `from` address and attempt to call the function `executeSigned`, using the parameters and signature you just collected. - -If the transaction need to collect more signatures or the app doesn't have a deployable server, the app should follow these steps: - -1. **Broadcast the transaction on a whisper channel** or some other decentralized network of peers. Details on this step require further discussions -2. **If web3 is available** then attempt calling web3.eth.personal_sign. This can be automatic or prompted by user action. -3. **Show a QR code**: with the signed transaction and the new data to be signed. That QR code can be clickable to attempt to retry the other options, but it should be done last: if step 1 works, the user should receive a notification on their compatible device and won't need to use the QR code. - -The goal is to keep broadcasting signatures via whisper until a node that is willing to deploy them is able to collect all messages. - -Once you've followed the above steps, watch the transaction pool to any transaction to that address and then take the user to your app. Once you seen the desired transaction, you can stop showing the QRcode and proceed with the app, while keeping some indication that the transaction is in progress. Subscribe to the event `ExecutedSigned` of the desired contract: once you see the transaction with the nonce, you can call it a success. If you see a different transaction with the same or higher nonce (or timestamp) then you consider the transaction permanently failed and restart the process. - - -### Implementation - -No working examples of this implementation exists, but many developers have expressed interest in adopting it. This section will be edited in the future to reflect that. - -### Conclusion and future improvements - -This scheme would allow much more lighter apps, that don't require to hold ether, and can keep unlocked private keys on the device to be able to send messages and play games without requesting user prompt every time. More work is needed to standardize common decentralized messaging protocols as well as open source tools for deployment nodes, in order to create a decentralized and reliable layer for message deployment. - -### References - -* [Universal Logins talk at UX Unconf, Toronto](https://www.youtube.com/watch?v=qF2lhJzngto) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1078.md diff --git a/EIPS/eip-1080.md b/EIPS/eip-1080.md index d704fc840655ea..bc247bd4034492 100644 --- a/EIPS/eip-1080.md +++ b/EIPS/eip-1080.md @@ -1,184 +1,7 @@ --- eip: 1080 -title: Recoverable Token -author: Bradley Leatherwood -discussions-to: https://ethereum-magicians.org/t/erc-1080-recoverabletoken-standard/364 -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-02 +status: Moved --- -## Simple Summary - -A standard interface for tokens that support chargebacks, theft prevention, and lost & found resolutions. - -## Abstract - -The following standard allows for the implementation of a standard API for tokens extending ERC-20 or ERC-791. This standard provides basic functionality to recover stolen or lost accounts, as well as provide for the chargeback of tokens. - -## Motivation - -To mitigate the effects of reasonably provable token or asset loss or theft and to help resolve other conflicts. Ethereum's protocol should not be modified because of loss, theft, or conflicts, but it is possible to solve these problems in the smart contract layer. - -## Specification - -## RecoverableToken - -### Methods - -#### claimLost - -Reports the `lostAccount` address as being lost. MUST trigger the `AccountClaimedLost` event. - -After the time configured in `getLostAccountRecoveryTimeInMinutes` the implementer MUST provide a mechanism for determining the correct owner of the tokens held and moving the tokens to a new account. - -Account recoveries must trigger the `AccountRecovered` event. - -``` js -function claimLost(address lostAccount) returns (bool success) -``` - -#### cancelLostClaim - -Reports the `msg.sender`'s account as being not being lost. MUST trigger the `AccountClaimedLostCanceled` event. - -MUST fail if an account recovery process has already begun. - -Otherwise, this method MUST stop a dispute from being started to recover funds. - -``` js -function claimLost() returns (bool success) -``` - -#### reportStolen - -Reports the current address as being stolen. MUST trigger the `AccountFrozen` event. -Successful calls MUST result in the `msg.sender`'s tokens being frozen. - -The implementer MUST provide a mechanism for determining the correct owner of the tokens held and moving the tokens to a new account. - -Account recoveries must trigger the `AccountRecovered` event. - -``` js -function reportStolen() returns (bool success) -``` - -#### chargeback - -Requests a reversal of transfer on behalf of `msg.sender`. - -The implementer MUST provide a mechanism for determining the correct owner of the tokens disputed and moving the tokens to the correct account. - -MUST comply with sender's chargeback window as value configured by `setPendingTransferTimeInMinutes`. - -``` js -function chargeback(uint256 pendingTransferNumber) returns (bool success) -``` - -#### getPendingTransferTimeInMinutes - -Get the time an account has to chargeback a transfer. - -``` js -function getPendingTransferTime(address account) view returns (uint256 minutes) -``` - -#### setPendingTransferTimeInMinutes - -Sets the time `msg.sender`'s account has to chargeback a transfer. - -MUST NOT change the time if the account has any pending transfers. - -``` js -function setPendingTransferTime(uint256 minutes) returns (bool success) -``` - -#### getLostAccountRecoveryTimeInMinutes - -Get the time account has to wait before a lost account dispute can start. - -``` js -function getLostAccountRecoveryTimeInMinutes(address account) view returns (uint256 minutes) -``` - -#### setLostAccountRecoveryTimeInMinutes - -Sets the time `msg.sender`'s account has to sit before a lost account dispute can start. - -MUST NOT change the time if the account has open disputes. - -``` js -function setLostAccountRecoveryTimeInMinutes(uint256 minutes) returns (bool success) -``` - -### Events - -#### AccountRecovered - -The recovery of an account that was lost or stolen. - -``` js -event AccountClaimedLost(address indexed account, address indexed newAccount) -``` - -#### AccountClaimedLostCanceled - -An account claimed as being lost. - -``` js -event AccountClaimedLost(address indexed account) -``` - -#### AccountClaimedLost - -An account claimed as being lost. - -``` js -event AccountClaimedLost(address indexed account) -``` - -#### PendingTransfer - -A record of a transfer pending. - -``` js -event PendingTransfer(address indexed from, address indexed to, uint256 value, uint256 pendingTransferNumber) -``` - -#### ChargebackRequested - -A record of a chargeback being requested. - -``` js -event ChargebackRequested(address indexed from, address indexed to, uint256 value, uint256 pendingTransferNumber) -``` - -#### Chargeback - -A record of a transfer being reversed. - -``` js -event Chargeback(address indexed from, address indexed to, uint256 value, uint256 indexed pendingTransferNumber) -``` - -#### AccountFrozen - -A record of an account being frozen. MUST trigger when an account is frozen. - -``` js -event AccountFrozen(address indexed reported) -``` - -## Rationale - -* A recoverable token standard can provide configurable safety for users or contracts who desire this safety. -* Implementations of this standard will give users the ability to select a dispute resolution process on an opt-in basis and benefit the community by decreasing the necessity of consideration of token recovery actions. - - -## Implementation - -Pending. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1080.md diff --git a/EIPS/eip-1081.md b/EIPS/eip-1081.md index f73b2c7011410b..4c333bdccbb2f3 100644 --- a/EIPS/eip-1081.md +++ b/EIPS/eip-1081.md @@ -1,121 +1,7 @@ --- eip: 1081 -title: Standard Bounties -author: Mark Beylin , Kevin Owocki , Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://gitter.im/bounties-network/Lobby -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-14 -requires: 20 +status: Moved --- - -## Simple Summary -A standard contract and interface for issuing bounties on Ethereum, usable for any type of task, paying in any ERC20 token or in ETH. -## Abstract -In order to encourage cross-platform interoperability of bounties on Ethereum, and for easier reputational tracking, StandardBounties can facilitate the administration of funds in exchange for deliverables corresponding to a completed task, in a publicly auditable and immutable fashion. - -## Motivation -In the absence of a standard for bounties on Ethereum, it would be difficult for platforms to collaborate and share the bounties which users create (thereby recreating the walled gardens which currently exist on Web2.0 task outsourcing platforms). A standardization of these interactions across task types also makes it far easier to track various reputational metrics (such as how frequently you pay for completed submissions, or how frequently your work gets accepted). - -## Specification -After studying bounties as they've existed for thousands of years (and after implementing and processing over 300 of them on main-net in beta), we've discovered that there are 3 core steps to every bounty: -- a bounty is **issued**: an `issuer` specifies the requirements for the task, describing the desired outcome, and how much they would be willing to pay for the completion of that task (denoted in one or several tokens). -- a bounty is **fulfilled**: a bounty `fulfiller` may see the bounty, complete the task, and produce a deliverable which is itself the desired outcome of the task, or simply a record that it was completed. Hashes of these deliverables should be stored immutably on-chain, to serve as proof after the fact. -- a fulfillment is **accepted**: a bounty `issuer` or `arbiter` may select one or more submissions to be accepted, thereby releasing payment to the bounty fulfiller(s), and transferring ownership over the given deliverable to the `issuer`. - -To implement these steps, a number of functions are needed: -- `initializeBounty(address _issuer, address _arbiter, string _data, uint _deadline)`: This is used when deploying a new StandardBounty contract, and is particularly useful when applying the proxy design pattern, whereby bounties cannot be initialized in their constructors. Here, the data string should represent an IPFS hash, corresponding to a JSON object which conforms to the schema (described below). -- `fulfillBounty(address[] _fulfillers, uint[] _numerators, uint _denomenator, string _data)`: This is called to submit a fulfillment, submitting a string representing an IPFS hash which contains the deliverable for the bounty. Initially fulfillments could only be submitted by one individual at a time, however users consistently told us they desired to be able to collaborate on fulfillments, thereby allowing the credit for submissions to be shared by several parties. The lines along which eventual payouts are split are determined by the fractions of the submission credited to each fulfiller (using the array of numerators and single denominator). Here, a bounty platform may also include themselves as a collaborator to collect a small fee for matching the bounty with fulfillers. -- `acceptFulfillment(uint _fulfillmentId, StandardToken[] _payoutTokens, uint[] _tokenAmounts)`: This is called by the `issuer` or the `arbiter` to pay out a given fulfillment, using an array of tokens, and an array of amounts of each token to be split among the contributors. This allows for the bounty payout amount to move as it needs to based on incoming contributions (which may be transferred directly to the contract address). It also allows for the easy splitting of a given bounty's balance among several fulfillments, if the need should arise. - - `drainBounty(StandardToken[] _payoutTokens)`: This may be called by the `issuer` to drain a bounty of it's funds, if the need should arise. -- `changeBounty(address _issuer, address _arbiter, string _data, uint _deadline)`: This may be called by the `issuer` to change the `issuer`, `arbiter`, `data`, and `deadline` fields of their bounty. -- `changeIssuer(address _issuer)`: This may be called by the `issuer` to change to a new `issuer` if need be -- `changeArbiter(address _arbiter)`: This may be called by the `issuer` to change to a new `arbiter` if need be -- `changeData(string _data)`: This may be called by the `issuer` to change just the `data` -- `changeDeadline(uint _deadline)`: This may be called by the `issuer` to change just the `deadline` - -Optional Functions: -- `acceptAndFulfill(address[] _fulfillers, uint[] _numerators, uint _denomenator, string _data, StandardToken[] _payoutTokens, uint[] _tokenAmounts)`: During the course of the development of this standard, we discovered the desire for fulfillers to avoid paying gas fees on their own, entrusting the bounty's `issuer` to make the submission for them, and at the same time accept it. This is useful since it still immutably stores the exchange of tokens for completed work, but avoids the need for new bounty fulfillers to have any ETH to pay for gas costs in advance of their earnings. -- `changeMasterCopy(StandardBounty _masterCopy)`: For `issuer`s to be able to change the masterCopy which their proxy contract relies on, if the proxy design pattern is being employed. -- `refundableContribute(uint[] _amounts, StandardToken[] _tokens)`: While non-refundable contributions may be sent to a bounty simply by transferring those tokens to the address where it resides, one may also desire to contribute to a bounty with the option to refund their contribution, should the bounty never receive a correct submission which is paid out. -`refundContribution(uint _contributionId)`: If a bounty hasn't yet paid out to any correct submissions and is past it's deadline, those individuals who employed the `refundableContribute` function may retrieve their funds from the contract. - -**Schemas** -Persona Schema: -``` -{ - name: // optional - A string representing the name of the persona - email: // optional - A string representing the preferred contact email of the persona - githubUsername: // optional - A string representing the github username of the persona - address: // required - A string web3 address of the persona -} -``` -Bounty issuance `data` Schema: -``` -{ - payload: { - title: // A string representing the title of the bounty - description: // A string representing the description of the bounty, including all requirements - issuer: { - // persona for the issuer of the bounty - }, - funders:[ - // array of personas of those who funded the issue. - ], - categories: // an array of strings, representing the categories of tasks which are being requested - tags: // an array of tags, representing various attributes of the bounty - created: // the timestamp in seconds when the bounty was created - tokenSymbol: // the symbol for the token which the bounty pays out - tokenAddress: // the address for the token which the bounty pays out (0x0 if ETH) - - // ------- add optional fields here ------- - sourceFileName: // A string representing the name of the file - sourceFileHash: // The IPFS hash of the file associated with the bounty - sourceDirectoryHash: // The IPFS hash of the directory which can be used to access the file - webReferenceURL: // The link to a relevant web reference (ie github issue) - }, - meta: { - platform: // a string representing the original posting platform (ie 'gitcoin') - schemaVersion: // a string representing the version number (ie '0.1') - schemaName: // a string representing the name of the schema (ie 'standardSchema' or 'gitcoinSchema') - } -} -``` -Bounty `fulfillment` data Schema: - -``` -{ - payload: { - description: // A string representing the description of the fulfillment, and any necessary links to works - sourceFileName: // A string representing the name of the file being submitted - sourceFileHash: // A string representing the IPFS hash of the file being submitted - sourceDirectoryHash: // A string representing the IPFS hash of the directory which holds the file being submitted - fulfillers: { - // personas for the individuals whose work is being submitted - } - - // ------- add optional fields here ------- - }, - meta: { - platform: // a string representing the original posting platform (ie 'gitcoin') - schemaVersion: // a string representing the version number (ie '0.1') - schemaName: // a string representing the name of the schema (ie 'standardSchema' or 'gitcoinSchema') - } -} -``` -## Rationale -The development of this standard began a year ago, with the goal of encouraging interoperability among bounty implementations on Ethereum. The initial version had significantly more restrictions: a bounty's `data` could not be changed after issuance (it seemed unfair for bounty `issuer`s to change the requirements after work is underway), and the bounty payout could not be changed (all funds needed to be deposited in the bounty contract before it could accept submissions). - -The initial version was also far less extensible, and only allowed for fixed payments to a given set of fulfillments. This new version makes it possible for funds to be split among several correct submissions, for submissions to be shared among several contributors, and for payouts to not only be in a single token as before, but in as many tokens as the `issuer` of the bounty desires. These design decisions were made after the 8+ months which Gitcoin, the Bounties Network, and Status Open Bounty have been live and meaningfully facilitating bounties for repositories in the Web3.0 ecosystem. - -## Test Cases -Tests for our implementation can be found here: https://github.com/Bounties-Network/StandardBounties/tree/develop/test - -## Implementation -A reference implementation can be found here: https://github.com/Bounties-Network/StandardBounties/blob/develop/contracts/StandardBounty.sol -**Although this code has been tested, it has not yet been audited or bug-bountied, so we cannot make any assertions about it's correctness, nor can we presently encourage it's use to hold funds on the Ethereum mainnet.** - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1081.md diff --git a/EIPS/eip-1109.md b/EIPS/eip-1109.md index f9df787b1e56fa..2e9cd53070da4f 100644 --- a/EIPS/eip-1109.md +++ b/EIPS/eip-1109.md @@ -47,7 +47,7 @@ The return will be 1 in case of success call and 0 in any of the next cases: 1.- mu_s[0] is an address of an undefined precompiled smart contract. 2.- The precompiled smart contract fails (as defined on each smart contract). Invalid input parameters for example. -Precompiled smart contracs, does not execute opcodes, so there is no need to pass a gas parameter as a normal `CALL` (`0xf1`). If the available gas is less that 2 plus the required gas required for the specific precompiled smart cotract, the context just STOPS executing with an "Out of Gas" error. +Precompiled smart contracts, does not execute opcodes, so there is no need to pass a gas parameter as a normal `CALL` (`0xf1`). If the available gas is less that 2 plus the required gas required for the specific precompiled smart contract, the context just STOPS executing with an "Out of Gas" error. There is no stack check for this call. diff --git a/EIPS/eip-1123.md b/EIPS/eip-1123.md index 06ca527c46d66b..41eb06e8f8005f 100644 --- a/EIPS/eip-1123.md +++ b/EIPS/eip-1123.md @@ -1,1881 +1,7 @@ --- eip: 1123 -title: Revised Ethereum Smart Contract Packaging Standard -author: g. nicholas d’andrea (@gnidan), Piper Merriam (@pipermerriam), Nick Gheorghita (@njgheorghita), Danny Ryan (@djrtwo) -discussions-to: https://github.com/ethereum/EIPs/issues/1123 -status: Withdrawn -type: Standards Track category: ERC -created: 2018-06-01 +status: Moved --- -This ERC has been abandoned in favor of the EthPM V3 smart contract packaging standard defined in [ERC-2678](./eip-2678.md) - -Simple Summary -============== - -A data format describing a smart contract software package. - - -Abstract -========== - -This EIP defines a data format for *package manifest* documents, -representing a package of one or more smart contracts, optionally -including source code and any/all deployed instances across multiple -networks. Package manifests are minified JSON objects, to be distributed -via content addressable storage networks, such as IPFS. - -This document presents a natural language description of a formal -specification for version **2** of this format. - - -Motivation -========== - -This standard aims to encourage the Ethereum development ecosystem -towards software best practices around code reuse. By defining an open, -community-driven package data format standard, this effort seeks to -provide support for package management tools development by offering a -general-purpose solution that has been designed with observed common -practices in mind. - -As version 2 of this specification, this standard seeks to address a -number of areas of improvement found for the previous version (defined -in -[EIP-190](./eip-190.md)). -This version: - -- Generalizes storage URIs to represent any content addressable URI - scheme, not only IPFS. - -- Renames *release lockfile* to *package manifest*. - -- Adds support for languages other than Solidity by generalizing the - compiler information format. - -- Redefines link references to be more flexible, to represent - arbitrary gaps in bytecode (besides only addresses), in a more - straightforward way. - -- Forces format strictness, requiring that package manifests contain - no extraneous whitespace, and sort object keys in alphabetical - order, to prevent hash mismatches. - - -
- -Specification -============= - -This document defines the specification for an EthPM package manifest. A -package manifest provides metadata about a [Package](#term-package), and -in most cases should provide sufficient information about the packaged -contracts and its dependencies to do bytecode verification of its -contracts. - -> **Note** -> -> A [hosted -> version](https://ethpm.github.io/ethpm-spec) of this -> specification is available via GitHub Pages. This EIP and the hosted -> HTML document were both autogenerated from the same documentation -> source. - - -Guiding Principles ------------------- - -This specification makes the following assumptions about the document -lifecycle. - -1. Package manifests are intended to be generated programmatically by - package management software as part of the release process. - -2. Package manifests will be consumed by package managers during tasks - like installing package dependencies or building and deploying new - releases. - -3. Package manifests will typically **not** be stored alongside the - source, but rather by package registries *or* referenced by package - registries and stored in something akin to IPFS. - - -Conventions ------------ - - -### RFC2119 - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, -“SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this -document are to be interpreted as described in RFC 2119. - -- - - -### Prefixed vs Unprefixed - -A [prefixed](#term-prefixed) hexadecimal value begins with `0x`. -[Unprefixed](#term-unprefixed) values have no prefix. Unless otherwise -specified, all hexadecimal values **should** be represented with the -`0x` prefix. - - ---- - - - - - - - - - - -

Prefixed

0xdeadbeef

Unprefixed

deadbeef

- - -Document Format ---------------- - -The canonical format is a single JSON object. Packages **must** conform -to the following serialization rules. - -- The document **must** be tightly packed, meaning no linebreaks or - extra whitespace. - -- The keys in all objects must be sorted alphabetically. - -- Duplicate keys in the same object are invalid. - -- The document **must** use - [UTF-8](https://en.wikipedia.org/wiki/UTF-8) - encoding. - -- The document **must** not have a trailing newline. - - -Document Specification ----------------------- - -The following fields are defined for the package. Custom fields **may** -be included. Custom fields **should** be prefixed with `x-` to prevent -name collisions with future versions of the specification. - - ---- - - - - - - - - - - -

See Also

Formalized (JSON-Schema) version of this specification: package.spec.json

Jump To

Definitions

- - -
- -### EthPM Manifest Version: `manifest_version` - -The `manifest_version` field defines the specification version that this -document conforms to. Packages **must** include this field. - - ---- - - - - - - - - - - - - - - - - - - -

Required

Yes

Key

manifest_version

Type

String

Allowed Values

2

- - -
- -### Package Name: `package_name` - -The `package_name` field defines a human readable name for this package. -Packages **must** include this field. Package names **must** begin with -a lowercase letter and be comprised of only lowercase letters, numeric -characters, and the dash character `-`. Package names **must** not -exceed 214 characters in length. - - ---- - - - - - - - - - - - - - - - - - - -

Required

Yes

Key

package_name

Type

String

Format

must match the regular expression ^[a-zA-Z][a-zA-Z0-9_]{0,255}$

- - -### Package Meta: `meta` - -The `meta` field defines a location for metadata about the package which -is not integral in nature for package installation, but may be important -or convenient to have on-hand for other reasons. This field **should** -be included in all Packages. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

meta

Type

Package Meta Object

- - -### Version: `version` - -The `version` field declares the version number of this release. This -value **must** be included in all Packages. This value **should** -conform to the [semver](https://semver.org/) version -numbering specification. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

version

Type

String

- - -### Sources: `sources` - -The `sources` field defines a source tree that **should** comprise the -full source tree necessary to recompile the contracts contained in this -release. Sources are declared in a key/value mapping. - - ---- - - - - - - - - - - - - - - -

Key

sources

Type

Object (String: String)

Format

See Below.

- - -#### Format - -Keys **must** be relative filesystem paths beginning with a `./`. - -Paths **must** resolve to a path that is within the current working -directory. - -Values **must** conform to *one of* the following formats. - -- Source string. - -- [Content Addressable URI](#term-content-addressable-uri). - -When the value is a source string the key should be interpreted as a -file path. - -- If the resulting document is a directory the key should be - interpreted as a directory path. - -- If the resulting document is a file the key should be interpreted as - a file path. - - -### Contract Types: `contract_types` - -The `contract_types` field holds the [Contract -Types](#term-contract-type) which have been included in this release. -[Packages](#term-package) **should** only include contract types that -can be found in the source files for this package. Packages **should -not** include contract types from dependencies. Packages **should not** -include abstract contracts in the contract types section of a release. - - ---- - - - - - - - - - - - - - - -

Key

contract_types

Type

Object (String: Contract Type Object)

Format

Keys must be valid Contract Aliases.

-

Values must conform to the Contract Type Object definition.

- - -### Deployments: `deployments` - -The `deployments` field holds the information for the chains on which -this release has [Contract Instances](#term-contract-instance) as well -as the [Contract Types](#term-contract-type) and other deployment -details for those deployed contract instances. The set of chains defined -by the `*BIP122 URI <#bip122-uris>*` keys for this object **must** be -unique. - - ---- - - - - - - - - - - - - - - -

Key

deployments

Type

Object (String: Object(String: Contract Instance Object))

Format

See Below.

- - -#### Format - -Keys **must** be a valid BIP122 URI chain definition. - -Values **must** be objects which conform to the following format. - -- Keys **must** be valid [Contract Instance - Names](#term-contract-instance-name). - -- Values **must** be a valid [Contract Instance - Object](#contract-instance-object). - - -### Build Dependencies: `build_dependencies` - -The `build_dependencies` field defines a key/value mapping of Ethereum -[Packages](#term-package) that this project depends on. - - ---- - - - - - - - - - - - - - - - - - - -

Required

No

Key

build_dependencies

Type

Object (String: String)

Format

Keys must be valid package names matching the regular expression [a-z][-a-z0-9]{0,213}.

-

Values must be valid IPFS URIs which resolve to a valid package.

- - -Definitions ------------ - -Definitions for different objects used within the Package. All objects -allow custom fields to be included. Custom fields **should** be prefixed -with `x-` to prevent name collisions with future versions of the -specification. - - - - -### The *Link Reference* Object - -A [Link Reference](#term-link-reference) object has the following -key/value pairs. All link references are assumed to be associated with -some corresponding [Bytecode](#term-bytecode). - - -#### Offsets: `offsets` - -The `offsets` field is an array of integers, corresponding to each of -the start positions where the link reference appears in the bytecode. -Locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. This field is invalid if it references a -position that is beyond the end of the bytecode. - - ---- - - - - - - - - - - -

Required

Yes

Type

Array

- - -#### Length: `length` - -The `length` field is an integer which defines the length in bytes of -the link reference. This field is invalid if the end of the defined link -reference exceeds the end of the bytecode. - - ---- - - - - - - - - - - -

Required

Yes

Type

Integer

- - -#### Name: `name` - -The `name` field is a string which **must** be a valid -[Identifier](#term-identifier). Any link references which **should** be -linked with the same link value **should** be given the same name. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

must conform to the Identifier format.

- - - - -### The *Link Value* Object - -Describes a single [Link Value](#term-link-value). - -A **Link Value object** is defined to have the following key/value -pairs. - - -
- -#### Offsets: `offsets` - -The `offsets` field defines the locations within the corresponding -bytecode where the `value` for this link value was written. These -locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

Integer

Format

See Below.

- -**Format** - -Array of integers, where each integer **must** conform to all of the -following. - -- greater than or equal to zero - -- strictly less than the length of the unprefixed hexadecimal - representation of the corresponding bytecode. - - -#### Type: `type` - -The `type` field defines the `value` type for determining what is -encoded when [linking](#term-linking) the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Allowed Values

"literal" for bytecode literals

-

"reference" for named references to a particular Contract Instance

- - -#### Value: `value` - -The `value` field defines the value which should be written when -[linking](#term-linking) the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

Determined based on type, see below.

- -**Format** - -For static value *literals* (e.g. address), value **must** be a *byte -string* - -To reference the address of a [Contract -Instance](#term-contract-instance) from the current package the value -should be the name of that contract instance. - -- This value **must** be a valid contract instance name. - -- The chain definition under which the contract instance that this - link value belongs to must contain this value within its keys. - -- This value **may not** reference the same contract instance that - this link value belongs to. - -To reference a contract instance from a [Package](#term-package) from -somewhere within the dependency tree the value is constructed as -follows. - -- Let `[p1, p2, .. pn]` define a path down the dependency tree. - -- Each of `p1, p2, pn` **must** be valid package names. - -- `p1` **must** be present in keys of the `build_dependencies` for the - current package. - -- For every `pn` where `n > 1`, `pn` **must** be present in the keys - of the `build_dependencies` of the package for `pn-1`. - -- The value is represented by the string - `::<...>::` where all of ``, - ``, `` are valid package names and `` is - a valid [Contract Name](#term-contract-name). - -- The `` value **must** be a valid [Contract - Instance Name](#term-contract-instance-name). - -- Within the package of the dependency defined by ``, all of the - following must be satisfiable: - - - There **must** be *exactly* one chain defined under the - `deployments` key which matches the chain definition that this - link value is nested under. - - - The `` value **must** be present in the keys - of the matching chain. - - -### The *Bytecode* Object - -A bytecode object has the following key/value pairs. - - -#### Bytecode: `bytecode` - -The `bytecode` field is a string containing the `0x` prefixed -hexadecimal representation of the bytecode. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

0x prefixed hexadecimal.

- - -#### Link References: `link_references` - -The `link_references` field defines the locations in the corresponding -bytecode which require [linking](#term-linking). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Array

Format

All values must be valid Link Reference objects. See also below.

- -**Format** - -This field is considered invalid if *any* of the [Link -References](#term-link-reference) are invalid when applied to the -corresponding `bytecode` field, *or* if any of the link references -intersect. - -Intersection is defined as two link references which overlap. - - -#### Link Dependencies: `link_dependencies` - -The `link_dependencies` defines the [Link Values](#term-link-value) that -have been used to link the corresponding bytecode. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Array

Format

All values must be valid Link Value objects. See also below.

- -**Format** - -Validation of this field includes the following: - -- Two link value objects **must not** contain any of the same values - for `offsets`. - -- Each [link value object](#link-value-object) **must** have a - corresponding [link reference object](#link-reference-object) under - the `link_references` field. - -- The length of the resolved `value` **must** be equal to the `length` - of the corresponding [Link Reference](#term-link-reference). - - -
- -### The *Package Meta* Object - -The *Package Meta* object is defined to have the following key/value -pairs. - - -#### Authors: `authors` - -The `authors` field defines a list of human readable names for the -authors of this package. Packages **may** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

authors

Type

Array (String)

- - -#### License: `license` - -The `license` field declares the license under which this package is -released. This value **should** conform to the -[SPDX](https://en.wikipedia.org/wiki/Software_Package_Data_Exchange) -format. Packages **should** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

license

Type

String

- - -#### Description: `description` - -The `description` field provides additional detail that may be relevant -for the package. Packages **may** include this field. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

description

Type

String

- - -#### Keywords: `keywords` - -The `keywords` field provides relevant keywords related to this package. - - ---- - - - - - - - - - - - - - - -

Required

No

Key

keywords

Type

List of Strings

- - -#### Links: `links` - -The `links` field provides URIs to relevant resources associated with -this package. When possible, authors **should** use the following keys -for the following common resources. - -- `website`: Primary website for the package. - -- `documentation`: Package Documentation - -- `repository`: Location of the project source code. - - ---- - - - - - - - - - - -

Key

links

Type

Object (String: String)

- - -
- -### The *Contract Type* Object - -A *Contract Type* object is defined to have the following key/value -pairs. - - -#### Contract Name: `contract_name` - -The `contract_name` field defines the [Contract -Name](#term-contract-name) for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

If the Contract Name and Contract Alias are not the same.

Type

String

Format

must be a valid Contract Name.

- - -#### Deployment Bytecode: `deployment_bytecode` - -The `deployment_bytecode` field defines the bytecode for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- - -#### Runtime Bytecode: `runtime_bytecode` - -The `runtime_bytecode` field defines the unlinked `0x`-prefixed runtime -portion of [Bytecode](#term-bytecode) for this [Contract -Type](#term-contract-type). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- - -#### ABI: `abi` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

List

Format

must conform to the Ethereum Contract ABI JSON format.

- - -#### Natspec: `natspec` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

The union of the UserDoc and DevDoc formats.

- - -#### Compiler: `compiler` - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Compiler Information object format.

- - -
- -### The *Contract Instance* Object - -A **Contract Instance Object** represents a single deployed [Contract -Instance](#term-contract-instance) and is defined to have the following -key/value pairs. - - -#### Contract Type: `contract_type` - -The `contract_type` field defines the [Contract -Type](#term-contract-type) for this [Contract -Instance](#term-contract-instance). This can reference any of the -contract types included in this [Package](#term-package) *or* any of the -contract types found in any of the package dependencies from the -`build_dependencies` section of the [Package -Manifest](#term-package-manifest). - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

See Below.

- -**Format** - -Values for this field **must** conform to *one of* the two formats -herein. - -To reference a contract type from this Package, use the format -``. - -- The `` value **must** be a valid [Contract - Alias](#term-contract-alias). - -- The value **must** be present in the keys of the `contract_types` - section of this Package. - -To reference a contract type from a dependency, use the format -`:`. - -- The `` value **must** be present in the keys of the - `build_dependencies` of this Package. - -- The `` value **must** be be a valid [Contract - Alias](#term-contract-alias). - -- The resolved package for `` must contain the - `` value in the keys of the `contract_types` - section. - - -#### Address: `address` - -The `address` field defines the [Address](#term-address) of the -[Contract Instance](#term-contract-instance). - - ---- - - - - - - - - - - - - - - -

Required

Yes

Type

String

Format

Hex encoded 0x prefixed Ethereum address matching the regular expression 0x[0-9a-fA-F]{40}.

- - -#### Transaction: `transaction` - -The `transaction` field defines the transaction hash in which this -[Contract Instance](#term-contract-instance) was created. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

0x prefixed hex encoded transaction hash.

- - -#### Block: `block` - -The `block` field defines the block hash in which this the transaction -which created this *contract instance* was mined. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

String

Format

0x prefixed hex encoded block hash.

- - -
- -#### Runtime Bytecode: `runtime_bytecode` - -The `runtime_bytecode` field defines the runtime portion of bytecode for -this [Contract Instance](#term-contract-instance). When present, the -value from this field supersedes the `runtime_bytecode` from the -[Contract Type](#term-contract-type) for this [Contract -Instance](#term-contract-instance). - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Bytecode Object format.

- -Every entry in the `link_references` for this bytecode **must** have a -corresponding entry in the `link_dependencies` section. - - -#### Compiler: `compiler` - -The `compiler` field defines the compiler information that was used -during compilation of this [Contract Instance](#term-contract-instance). -This field **should** be present in all [Contract -Types](#term-contract-type) which include `bytecode` or -`runtime_bytecode`. - - ---- - - - - - - - - - - - - - - -

Required

No

Type

Object

Format

must conform to the Compiler Information Object format.

- - -
- -### The *Compiler Information* Object - -The `compiler` field defines the compiler information that was used -during compilation of this [Contract Instance](#term-contract-instance). -This field **should** be present in all contract instances that locally -declare `runtime_bytecode`. - -A *Compiler Information* object is defined to have the following -key/value pairs. - - -#### Name `name` - -The `name` field defines which compiler was used in compilation. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

name

Type

String

- - -#### Version: `version` - -The `version` field defines the version of the compiler. The field -**should** be OS agnostic (OS not included in the string) and take the -form of either the stable version in -[semver](https://semver.org/) format or if built on a -nightly should be denoted in the form of `-` ex: -`0.4.8-commit.60cc1668`. - - ---- - - - - - - - - - - - - - - -

Required

Yes

Key

version

Type

String

- - -#### Settings: `settings` - -The `settings` field defines any settings or configuration that was used -in compilation. For the `"solc"` compiler, this **should** conform to -the [Compiler Input and Output -Description](https://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description). - - ---- - - - - - - - - - - - - - - -

Required

No

Key

settings

Type

Object

- - -### BIP122 URIs - -BIP122 URIs are used to define a blockchain via a subset of the -[BIP-122](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki) -spec. - - blockchain:///block/ - -The `` represents the blockhash of the first block on the -chain, and `` represents the hash of the -latest block that’s been reliably confirmed (package managers should be -free to choose their desired level of confirmations). - - -Rationale -========= - -The following use cases were considered during the creation of this -specification. - - ---- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

owned

A package which contains contracts which are not meant to be used by themselves but rather as base contracts to provide functionality to other contracts through inheritance.

transferable

A package which has a single dependency.

standard-token

A package which contains a reusable contract.

safe-math-lib

A package which contains deployed instance of one of the package contracts.

piper-coin

A package which contains a deployed instance of a reusable contract from a dependency.

escrow

A package which contains a deployed instance of a local contract which is linked against a deployed instance of a local library.

wallet

A package with a deployed instance of a local contract which is linked against a deployed instance of a library from a dependency.

wallet-with-send

A package with a deployed instance which links against a deep dependency.

- -Each use case builds incrementally on the previous one. - -A full listing of [Use -Cases](https://ethpm.github.io/ethpm-spec/use-cases.html) -can be found on the hosted version of this specification. - - -Glossary -========== - - -
- -ABI ---- - -The JSON representation of the application binary interface. See the -official -[specification](https://solidity.readthedocs.io/en/develop/abi-spec.html) -for more information. - - -
- -Address -------- - -A public identifier for an account on a particular chain - - -
- -Bytecode --------- - -The set of EVM instructions as produced by a compiler. Unless otherwise -specified this should be assumed to be hexadecimal encoded, representing -a whole number of bytes, and [prefixed](#term-prefixed) with `0x`. - -Bytecode can either be linked or unlinked. (see -[Linking](#term-linking)) - - ---- - - - - - - - - - - -

Unlinked Bytecode

The hexadecimal representation of a contract’s EVM instructions that contains sections of code that requires linking for the contract to be functional.

-

The sections of code which are unlinked must be filled in with zero bytes.

-

Example: 0x606060405260e06000730000000000000000000000000000000000000000634d536f

Linked Bytecode

The hexadecimal representation of a contract’s EVM instructions which has had all Link References replaced with the desired Link Values.

-

Example: 0x606060405260e06000736fe36000604051602001526040518160e060020a634d536f

- - -
- -Chain Definition ----------------- - -This definition originates from [BIP122 -URI](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki). - -A URI in the format `blockchain:///block/` - -- `chain_id` is the unprefixed hexadecimal representation of the - genesis hash for the chain. - -- `block_hash` is the unprefixed hexadecimal representation of the - hash of a block on the chain. - -A chain is considered to match a chain definition if the the genesis -block hash matches the `chain_id` and the block defined by `block_hash` -can be found on that chain. It is possible for multiple chains to match -a single URI, in which case all chains are considered valid matches - - -
- -Content Addressable URI ------------------------ - -Any URI which contains a cryptographic hash which can be used to verify -the integrity of the content found at the URI. - -The URI format is defined in RFC3986 - -It is **recommended** that tools support IPFS and Swarm. - - -
- -Contract Alias --------------- - -This is a name used to reference a specific [Contract -Type](#term-contract-type). Contract aliases **must** be unique within a -single [Package](#term-package). - -The contract alias **must** use *one of* the following naming schemes: - -- `` - -- `[]` - -The `` portion **must** be the same as the [Contract -Name](#term-contract-name) for this contract type. - -The `[]` portion **must** match the regular expression -`\[[-a-zA-Z0-9]{1,256}]`. - - -
- -Contract Instance ------------------ - -A contract instance a specific deployed version of a [Contract -Type](#term-contract-type). - -All contract instances have an [Address](#term-address) on some specific -chain. - - -
- -Contract Instance Name ----------------------- - -A name which refers to a specific [Contract -Instance](#term-contract-instance) on a specific chain from the -deployments of a single [Package](#term-package). This name **must** be -unique across all other contract instances for the given chain. The name -must conform to the regular expression `[a-zA-Z][a-zA-Z0-9_]{0,255}` - -In cases where there is a single deployed instance of a given [Contract -Type](#term-contract-type), package managers **should** use the -[Contract Alias](#term-contract-alias) for that contract type for this -name. - -In cases where there are multiple deployed instances of a given contract -type, package managers **should** use a name which provides some added -semantic information as to help differentiate the two deployed instances -in a meaningful way. - - -
- -Contract Name -------------- - -The name found in the source code that defines a specific [Contract -Type](#term-contract-type). These names **must** conform to the regular -expression `[a-zA-Z][-a-zA-Z0-9_]{0,255}`. - -There can be multiple contracts with the same contract name in a -projects source files. - - -
- -Contract Type -------------- - -Refers to a specific contract in the package source. This term can be -used to refer to an abstract contract, a normal contract, or a library. -Two contracts are of the same contract type if they have the same -bytecode. - -Example: - - contract Wallet { - ... - } - -A deployed instance of the `Wallet` contract would be of of type -`Wallet`. - - -
- -Identifier ----------- - -Refers generally to a named entity in the [Package](#term-package). - -A string matching the regular expression `[a-zA-Z][-_a-zA-Z0-9]{0,255}` - - - - -Link Reference --------------- - -A location within a contract’s bytecode which needs to be linked. A link -reference has the following properties. - - ---- - - - - - - - - - - - - - - -

offset

Defines the location within the bytecode where the link reference begins.

length

Defines the length of the reference.

name

(optional.) A string to identify the reference

- - - - -Link Value ----------- - -A link value is the value which can be inserted in place of a [Link -Reference](#term-link-reference) - - -
- -Linking -------- - -The act of replacing [Link References](#term-link-reference) with [Link -Values](#term-link-value) within some [Bytecode](#term-bytecode). - - -
- -Package -------- - -Distribution of an application’s source or compiled bytecode along with -metadata related to authorship, license, versioning, et al. - -For brevity, the term **Package** is often used metonymously to mean -[Package Manifest](#term-package-manifest). - - -
- -Package Manifest ----------------- - -A machine-readable description of a package (See -[Specification](#package-specification) for information about the format -for package manifests.) - - -
- -Prefixed --------- - -[Bytecode](#term-bytecode) string with leading `0x`. - - ---- - - - - - - -

Example

0xdeadbeef

- - -
- -Unprefixed ----------- - -Not [Prefixed](#term-prefixed). - - ---- - - - - - - -

Example

deadbeef

- - -Backwards Compatibility -======================= - -This specification supports backwards compatibility by use of the -[manifest\_version](#manifest-version) property. This -specification corresponds to version `2` as the value for that field. - - -Implementations -=============== - -This submission aims to coincide with development efforts towards -widespread implementation in commonly-used development tools. - -The following tools are known to have begun or are nearing completion of -a supporting implementation. - -- [Truffle](https://trufflesuite.com/) - -- [Populus](https://populus.readthedocs.io/en/latest/) - -- [Embark](https://embark.status.im/) - -Full support in implementation **may** require [Further -Work](#further-work), specified below. - - -Further Work -============ - -This EIP addresses only the data format for package descriptions. -Excluded from the scope of this specification are: - -- Package registry interface definition - -- Tooling integration, or how packages are stored on disk. - -These efforts **should** be considered separate, warranting future -dependent EIP submssions. - - -Acknowledgements -================ - -The authors of this document would like to thank the original authors of -[EIP-190](./eip-190.md), -[ETHPrize](http://ethprize.io/) for their funding -support, all community -[contributors](https://github.com/ethpm/ethpm-spec/graphs/contributors), -and the Ethereum community at large. - - -Copyright -========= - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1123.md diff --git a/EIPS/eip-1129.md b/EIPS/eip-1129.md index ca6acdcd754975..a9a2238c60965f 100644 --- a/EIPS/eip-1129.md +++ b/EIPS/eip-1129.md @@ -1,144 +1,7 @@ --- eip: 1129 -title: Standardised DAPP announcements -author: Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/eip-sda-standardised-dapp-announcements/508?u=thunderdeliverer -status: Stagnant -type: Standards Track category: ERC -created: 2018-05-31 +status: Moved --- -## Simple Summary -Standardisation of announcements in DAPPs and services on Ethereum network. This ERC provides proposed mechanics to increase the quality of service provided by DAPP developers and service providers, by setting a framework for announcements. Be it transitioning to a new smart contract or just freezing the service for some reason. - -## Abstract -The proposed ERC defines format on how to post announcements about the service as well as how to remove them. It also defines mechanics on posting permissions and human friendly interface. - -## Motivation -Currently there are no guidelines on how to notify the users of the service status in the DAPPs. This is especially obvious in ERC20 and it's derivates. If the service is impeded by any reason it is good practice to have some sort of guidelines on how to announce that to the user. The standardisation would also provide traceability of the service's status. - -## Specification - -### Structures - -#### Announcer - -Stores information about the announcement maker. The `allowedToPost` stores posting permissions and is used for modifiers limiting announcement posting only to authorised entities. The `name` is used for human friendly identifier of the author to be stored. - -``` js -struct Announcer{ - bool allowedToPost; - string name; -} -``` - - -#### Announcement - -Stores information about the individual announcement. The human friendly author identifier is stored in `author`. Ethereum address associated with the author is stored in `authorAddress`. The announcement itself is stored in `post`. - -``` js -struct Announcement{ - string author; - address authorAddress; - string post; -} -``` - - - -### Methods -#### the number of ammouncements - -Returns the number of announcement currently active. - -OPTIONAL - this method can be used to provide quicker information for the UI, but could also be retrieved from `numberOfMessages` variable. - -``` js -function theNumberOfAnnouncements() public constant returns(uint256 _numberOfAnnouncements) -``` - - -#### read posts - -Returns the specified announcement as well as human friendly poster identificator (name or nickname). - -``` js -function readPosts(uint256 _postNumber) public constant returns(string _author, string _post) -``` - - -#### give posting permission - -Sets posting permissions of the address `_newAnnouncer` to `_postingPrivileges` and can also be used to revoke those permissions. The `_posterName` is human friendly author identificator used in the announcement data. - -``` js -function givePostingPermission(address _newAnnouncer, bool _postingPrivileges, string _posterName) public onlyOwner returns(bool success) -``` - - -#### can post - -Checks if the entity that wants to post an announcement has the posting privilieges. - -``` js -modifier canPost{ - require(posterData[msg.sender].allowedToPost); - _; -} -``` - - -#### post announcement - -Lets user post announcements, but only if they have their posting privileges set to `true`. The announcement is sent in `_message` variable. - -``` js -function postAnnouncement(string _message) public canPost -``` - - -#### remove announcement - -Removes an announcement with `_messageNumber` announcement identifier and rearranges the mapping so there are no empty slots. The `_removalReason` is used to update users if the issue that caused the announcement is resolved or what are the next steps from the service provider / DAPP development team. - -``` js -function removeAnnouncement(uint256 _messageNumber, string _removalReason) public -``` - - - -### Events - -#### New announcement - -MUST trigger when new announcement is created. - -Every time there is a new announcement it should be advertised in this event. It holds the information about author `author` and the announcement istelf `message`. - -``` js -event NewAnnouncement(string author, string message) -``` - - -#### Removed announcement - -MUST trigger when an announcement is removed. - -Every time an announcement is removed it should be advertised in this event. It holds the information about author `author`, the announcement itself `message`, the reason for removal or explanation of the solution `reason` and the address of the entity that removed the announcement `remover`. - -``` js -event RemovedAnnouncement(string author, string message, string reason, address remover); -``` - -## Rationale -The proposed solution was designed with UX in mind . It provides mechanics that serve to present the announcements in the user friendly way. It is meant to be deployed as a Solidity smart contract on Ethereum network. - -## Test Cases -The proposed version is deployed on Ropsten testnet all of the information can be found [here](https://ropsten.etherscan.io/address/0xb04f67172b9733837e59ebaf03d277279635c8e6#readContract). - -## Implementation - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1129.md diff --git a/EIPS/eip-1132.md b/EIPS/eip-1132.md index 373a0dd4c3ffe3..3f0b801c8073f5 100644 --- a/EIPS/eip-1132.md +++ b/EIPS/eip-1132.md @@ -1,152 +1,7 @@ --- eip: 1132 -title: Extending ERC20 with token locking capability -author: nitika-goel -type: Standards Track category: ERC -status: Stagnant -created: 2018-06-03 -discussions-to: https://github.com/ethereum/EIPs/issues/1132 +status: Moved --- -## Simple Summary - -An extension to the ERC20 standard with methods for time-locking of tokens within a contract. - -## Abstract - -This proposal provides basic functionality to time-lock tokens within an ERC20 smart contract for multiple utilities without the need of transferring tokens to an external escrow smart contract. It also allows fetching balance of locked and transferable tokens. - -Time-locking can also be achieved via staking (#900), but that requires transfer of tokens to an escrow contract / stake manager, resulting in the following six concerns: - -1. additional trust on escrow contract / stake manager -2. additional approval process for token transfer -3. increased ops costs due to gas requirements in transfers -4. tough user experience as the user needs to claim the amount back from external escrows -5. inability for the user to track their true token balance / token activity -6. inability for the user to utilize their locked tokens within the token ecosystem. - -## Motivation - -dApps often require tokens to be time-locked against transfers for letting members 1) adhere to vesting schedules and 2) show skin in the game to comply with the underlying business process. I realized this need while building Nexus Mutual and GovBlocks. - -In [Nexus Mutual](https://nexusmutual.io), claim assessors are required to lock their tokens before passing a vote for claims assessment. This is important as it ensures assessors’ skin in the game. The need here was that once a claim assessor locks his tokens for ‘n’ days, he should be able to cast multiple votes during that period of ‘n’ days, which is not feasible with staking mechanism. There are other scenarios like skills/identity verification or participation in gamified token curated registries where time-locked tokens are required as well. - -In [GovBlocks](https://govblocks.io), I wanted to allow dApps to lock member tokens for governance, while still allowing members to use those locked tokens for other activities within the dApp business. This is also the case with DGX governance model where they’ve proposed quarterly token locking for participation in governance activities of DGX. - -In addition to locking functionality, I have proposed a `Lock()` and `Unlock()` event, just like the `Transfer()` event , to track token lock and unlock status. From token holder’s perspective, it gets tough to manage token holdings if certain tokens are transferred to another account for locking, because whenever `balanceOf()` queries are triggered on token holder’s account – the result does not include locked tokens. A `totalBalanceOf()` function intends to solve this problem. - -The intention with this proposal is to enhance the ERC20 standard with token-locking capability so that dApps can time-lock tokens of the members without having to transfer tokens to an escrow / stake manager and at the same time allow members to use the locked tokens for multiple utilities. - -## Specification - -I’ve extended the ERC20 interface with the following enhancements: - -### Locking of tokens -```solidity -/** - * @dev Locks a specified amount of tokens against an address, - * for a specified reason and time - * @param _reason The reason to lock tokens - * @param _amount Number of tokens to be locked - * @param _time Lock time in seconds - */ -function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) -``` - -### Fetching number of tokens locked under each utility -```solidity -/** - * @dev Returns tokens locked for a specified address for a - * specified reason - * - * @param _of The address whose tokens are locked - * @param _reason The reason to query the lock tokens for - */ - tokensLocked(address _of, bytes32 _reason) view returns (uint256 amount) -``` - -### Fetching number of tokens locked under each utility at a future timestamp -```solidity -/** - * @dev Returns tokens locked for a specified address for a - * specified reason at a specific time - * - * @param _of The address whose tokens are locked - * @param _reason The reason to query the lock tokens for - * @param _time The timestamp to query the lock tokens for - */ - function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) -``` - -### Fetching number of tokens held by an address -```solidity -/** - * @dev @dev Returns total tokens held by an address (locked + transferable) - * @param _of The address to query the total balance of - */ -function totalBalanceOf(address _of) view returns (uint256 amount) -``` - -### Extending lock period -```solidity -/** - * @dev Extends lock for a specified reason and time - * @param _reason The reason to lock tokens - * @param _time Lock extension time in seconds - */ - function extendLock(bytes32 _reason, uint256 _time) public returns (bool) -``` - -### Increasing number of tokens locked -```solidity -/** - * @dev Increase number of tokens locked for a specified reason - * @param _reason The reason to lock tokens - * @param _amount Number of tokens to be increased - */ - function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool) -``` -### Fetching number of unlockable tokens under each utility -```solidity -/** - * @dev Returns unlockable tokens for a specified address for a specified reason - * @param _of The address to query the the unlockable token count of - * @param _reason The reason to query the unlockable tokens for - */ - function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) - ``` -### Fetching number of unlockable tokens -```solidity -/** - * @dev Gets the unlockable tokens of a specified address - * @param _of The address to query the the unlockable token count of - */ - function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) -``` -### Unlocking tokens -```solidity -/** - * @dev Unlocks the unlockable tokens of a specified address - * @param _of Address of user, claiming back unlockable tokens - */ - function unlock(address _of) public returns (uint256 unlockableTokens) -``` - -### Lock event recorded in the token contract -`event Locked(address indexed _of, uint256 indexed _reason, uint256 _amount, uint256 _validity)` - -### Unlock event recorded in the token contract -`event Unlocked(address indexed _of, uint256 indexed _reason, uint256 _amount)` - -## Test Cases - -Test cases are available at [https://github.com/nitika-goel/lockable-token](https://github.com/nitika-goel/lockable-token). - -## Implementation - -- Complete implementation available at https://github.com/nitika-goel/lockable-token -- [GovBlocks](https://govblocks.io) Project specific implementation available at https://github.com/somish/govblocks-protocol/blob/Locking/contracts/GBTStandardToken.sol - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1132.md diff --git a/EIPS/eip-1153.md b/EIPS/eip-1153.md index 3ea30688b16741..1eb863b534a5a3 100644 --- a/EIPS/eip-1153.md +++ b/EIPS/eip-1153.md @@ -1,11 +1,10 @@ --- eip: 1153 title: Transient storage opcodes -description: Add opcodes for manipulating state that behaves identically to storage but is discarded after every transaction +description: Add opcodes for manipulating state that behaves almost identically to storage but is discarded after every transaction author: Alexey Akhunov (@AlexeyAkhunov), Moody Salem (@moodysalem) discussions-to: https://ethereum-magicians.org/t/eip-transient-storage-opcodes/553 -status: Last Call -last-call-deadline: 2022-12-08 +status: Final type: Standards Track category: Core created: 2018-06-15 @@ -14,11 +13,11 @@ requires: 2200, 3529 ## Abstract -This proposal introduces transient storage opcodes, which manipulate state that behaves identically to storage, except that transient storage is discarded after every transaction. In other words, the values of transient storage are never deserialized from storage or serialized to storage. Thus transient storage is cheaper since it never requires disk access. Transient storage is accessible to smart contracts via 2 new opcodes, `TLOAD` and `TSTORE`, where “T” stands for "transient:" +This proposal introduces transient storage opcodes, which manipulate state that behaves identically to storage, except that transient storage is discarded after every transaction, and `TSTORE` is not subject to the gas stipend check as defined in [EIP-2200](./eip-2200.md). In other words, the values of transient storage are never deserialized from storage or serialized to storage. Thus transient storage is cheaper since it never requires disk access. Transient storage is accessible to smart contracts via 2 new opcodes, `TLOAD` and `TSTORE`, where “T” stands for "transient:" ``` -TLOAD (0xb3) -TSTORE (0xb4) +TLOAD (0x5c) +TSTORE (0x5d) ``` ## Motivation @@ -33,7 +32,7 @@ Potential use cases enabled or improved by this EIP include: 1. Reentrancy locks 2. On-chain computable CREATE2 addresses: constructor arguments are read from the factory contract instead of passed as part of init code hash -3. Single transaction [EIP-20](./eip-20.md) approvals, e.g. `#temporaryApprove(address spender, uint256 amount)` +3. Single transaction [ERC-20](./eip-20.md) approvals, e.g. `#temporaryApprove(address spender, uint256 amount)` 4. Fee-on-transfer contracts: pay a fee to a token contract to unlock transfers for the duration of a transaction 5. "Till" pattern: allowing users to perform all actions as part of a callback, and checking the "till" is balanced at the end 6. Proxy call metadata: pass additional metadata to an implementation contract without using calldata, e.g. values of immutable proxy constructor arguments @@ -42,11 +41,11 @@ These opcodes are more efficient to execute than the `SSTORE` and `SLOAD` opcode ## Specification -Two new opcodes are added to EVM, `TLOAD` (`0xb3`) and `TSTORE` (`0xb4`). Note that previous drafts of this EIP specified the values `0x5c` and `0x5d` for `TLOAD` and `TSTORE` respectively, but these have been modified so as not to conflict with other draft EIPs. +Two new opcodes are added to EVM, `TLOAD` (`0x5c`) and `TSTORE` (`0x5d`). (Note that previous drafts of this EIP specified the values `0xb3` and `0xb4` for `TLOAD` and `TSTORE` respectively to avoid conflict with other EIPs. The conflict has since been removed.) They use the same arguments on stack as `SLOAD` (`0x54`) and `SSTORE` (`0x55`). -`TLOAD` pops one 32-byte word from the top of the stack, treats this value as the address, fetches 32-byte word from the transient storage at that address, and pops the value on top of the stack. +`TLOAD` pops one 32-byte word from the top of the stack, treats this value as the address, fetches 32-byte word from the transient storage at that address, and pushes the value on top of the stack. `TSTORE` pops two 32-byte words from the top of the stack. The word on the top is the address, and the next is the value. `TSTORE` saves the value at the given address in the transient storage. @@ -64,13 +63,15 @@ If a frame reverts, all writes to transient storage that took place between entr If the `TSTORE` opcode is called within the context of a `STATICCALL`, it will result in an exception instead of performing the modification. `TLOAD` is allowed within the context of a `STATICCALL`. +The behavior of the opcodes for transient storage differs from the opcodes for storage in that `TSTORE` does not require _gasleft_, as defined in [EIP-2200](./eip-2200.md), to be less than or equal to the gas stipend (currently 2,300). + ## Rationale Another option to solve the problem of inter-frame communication is repricing the `SSTORE` and `SLOAD` opcodes to be cheaper for the transient storage use case. This has already been done as of [EIP-2200](./eip-2200.md). However, [EIP-3529](./eip-3529.md) reduced the maximum refund to only 20% of the transaction gas cost, which means the use of transient storage is severely limited. Another approach is to keep the refund counter for transient storage separate from the refund counter for other storage uses, and remove the refund cap for transient storage. However, that approach is more complex to implement and understand. For example, the 20% refund cap must be applied to the gas used _after_ subtracting the uncapped gas refund. Otherwise, the refund amount available subject to the 20% refund cap could be increased by executing transient storage writes. Thus it is preferable to have a separate mechanism that does not interact with the refund counter. Future hard forks can remove the complex refund behavior meant to support the transient storage use case, encouraging migration to contracts that are more efficient for the Ethereum clients to execute. -There is a known objection to the word-addressed storage-like interface of the `TSTORE` and `TLOAD` opcodes since transient storage is more akin to memory than storage in lifecycle. A byte-addressed memory-like interface is another option. The storage-like word-addressed interface is preferred due to the usefulness of mappings in combination with the transaction-scoped memory region. Often times, you will need to keep transient state with arbitrary keys, such as in the [EIP-20](./eip-20.md) temporary approval use case which uses a mapping of `(owner, spender)` to `allowance`. Mappings are difficult to implement using linear memory, and linear memory must also have dynamic gas costs. It is also more complicated to handle reverts with a linear memory. It is possible to have a memory-like interface while the underlying implementation uses a map to allow for storage in arbitrary offsets, but this would result in a third memory-storage hybrid interface that would require new code paths in compilers. +There is a known objection to the word-addressed storage-like interface of the `TSTORE` and `TLOAD` opcodes since transient storage is more akin to memory than storage in lifecycle. A byte-addressed memory-like interface is another option. The storage-like word-addressed interface is preferred due to the usefulness of mappings in combination with the transaction-scoped memory region. Often times, you will need to keep transient state with arbitrary keys, such as in the [ERC-20](./eip-20.md) temporary approval use case which uses a mapping of `(owner, spender)` to `allowance`. Mappings are difficult to implement using linear memory, and linear memory must also have dynamic gas costs. It is also more complicated to handle reverts with a linear memory. It is possible to have a memory-like interface while the underlying implementation uses a map to allow for storage in arbitrary offsets, but this would result in a third memory-storage hybrid interface that would require new code paths in compilers. Some think that a unique transaction identifier may obviate the need for transient storage as described in this EIP. This is a misconception: a transaction identifier used in combination with regular storage has all the same issues that motivate this EIP. The two features are orthogonal. @@ -96,9 +97,13 @@ This EIP requires a hard fork to implement. Since this EIP does not change behavior of any existing opcodes, it is backwards compatible with all existing smart contracts. +## Test Cases + +A test suite for this EIP can be found [here](https://github.com/ethereum/execution-spec-tests/tree/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip1153_tstore). + ## Reference Implementation -Because the transient storage must behave identically to storage within the context of a single transaction with regards to revert behavior, it is necessary to be able to revert to a previous state of transient storage within a transaction. At the same time reverts are exceptional cases and loads, stores and returns should be cheap. +Because the transient storage must behave almost identically to storage within the context of a single transaction with regards to revert behavior, it is necessary to be able to revert to a previous state of transient storage within a transaction. At the same time reverts are exceptional cases and loads, stores and returns should be cheap. A map of current state plus a journal of all changes and a list of checkpoints is recommended. This has the following time complexities: diff --git a/EIPS/eip-1154.md b/EIPS/eip-1154.md index 417ae863f31b72..2873d8496253c6 100644 --- a/EIPS/eip-1154.md +++ b/EIPS/eip-1154.md @@ -1,110 +1,7 @@ --- eip: 1154 -title: Oracle Interface -author: Alan Lu (@cag) -discussions-to: https://github.com/ethereum/EIPs/issues/1161 -status: Withdrawn -type: Standards Track category: ERC -created: 2018-06-13 +status: Moved --- -## Simple Summary -A standard interface for oracles. - -## Abstract -In order for ethereum smart contracts to interact with off-chain systems, oracles must be used. These oracles report values which are normally off-chain, allowing smart contracts to react to the state of off-chain systems. A distinction and a choice is made between push and pull based oracle systems. Furthermore, a standard interface for oracles is described here, allowing different oracle implementations to be interchangeable. - -## Motivation -The Ethereum ecosystem currently has many different oracle implementations available, but they do not provide a unified interface. Smart contract systems would be locked into a single set of oracle implementations, or they would require developers to write adapters/ports specific to the oracle system chosen in a given project. - -Beyond naming differences, there is also the issue of whether or not an oracle report-resolving transaction _pushes_ state changes by calling affected contracts, or changes the oracle state allowing dependent contracts to _pull_ the updated value from the oracle. These differing system semantics could introduce inefficiencies when adapting between them. - -Ultimately, the value in different oracle systems comes from their underlying resolution mechanics, and points where these systems are virtually identical should be standardized. - -These oracles may be used for answering questions about "real-world events", where each ID can be correlated with a specification of a question and its answers (so most likely for prediction markets, basically). - -Another use case could be for decision-making processes, where the results given by the oracle represent decisions made by the oracle (e.g. futarchies). DAOs may require their use in decision making processes. - -Both the ID and the results are intentionally unstructured so that things like time series data (via splitting the ID) and different sorts of results (like one of a few, any subset of up to 256, or some value in a range with up to 256 bits of granularity) can be represented. - -## Specification - -
-
Oracle
-
An entity which reports data to the blockchain.
- -
Oracle consumer
-
A smart contract which receives data from an oracle.
- -
ID
-
A way of indexing the data which an oracle reports. May be derived from or tied to a question for which the data provides the answer.
- -
Result
-
Data associated with an id which is reported by an oracle. This data oftentimes will be the answer to a question tied to the id. Other equivalent terms that have been used include: answer, data, outcome.
- -
Report
-
A pair (ID, result) which an oracle sends to an oracle consumer.
-
- -```solidity -interface OracleConsumer { - function receiveResult(bytes32 id, bytes result) external; -} -``` - -`receiveResult` MUST revert if the `msg.sender` is not an oracle authorized to provide the `result` for that `id`. - -`receiveResult` MUST revert if `receiveResult` has been called with the same `id` before. - -`receiveResult` MAY revert if the `id` or `result` cannot be handled by the consumer. - -Consumers MUST coordinate with oracles to determine how to encode/decode results to and from `bytes`. For example, `abi.encode` and `abi.decode` may be used to implement a codec for results in Solidity. `receiveResult` SHOULD revert if the consumer receives a unexpected result format from the oracle. - -The oracle can be any Ethereum account. - -## Rationale -The specs are currently very similar to what is implemented by ChainLink (which can use any arbitrarily-named callback) and Oraclize (which uses `__callback`). - -With this spec, the oracle _pushes_ state to the consumer, which must react accordingly to the updated state. An alternate _pull_-based interface can be prescribed, as follows: - -### Alternate Pull-based Interface -Here are alternate specs loosely based on Gnosis prediction market contracts v1. Reality Check also exposes a similar endpoint (`getFinalAnswer`). - -```solidity -interface Oracle { - function resultFor(bytes32 id) external view returns (bytes result); -} -``` - -`resultFor` MUST revert if the result for an `id` is not available yet. - -`resultFor` MUST return the same result for an `id` after that result is available. - -### Push vs Pull -Note that push-based interfaces may be adapted into pull-based interfaces. Simply deploy an oracle consumer which stores the result received and implements `resultFor` accordingly. - -Similarly, every pull-based system can be adapted into a push-based system: just add a method on the oracle smart contract which takes an oracle consumer address and calls `receiveResult` on that address. - -In both cases, an additional transaction would have to be performed, so the choice to go with push or pull should be based on the dominant use case for these oracles. - -In the simple case where a single account has the authority to decide the outcome of an oracle question, there is no need to deploy an oracle contract and store the outcome on that oracle contract. Similarly, in the case where the outcome comes down to a vote, existing multisignature wallets can be used as the authorized oracle. - -#### Multiple Oracle Consumers -In the case that many oracle consumers depend on a single oracle result and all these consumers expect the result to be pushed to them, the push and pull adaptations mentioned before may be combined if the pushing oracle cannot be trusted to send the same result to every consumer (in a sense, this forwards the trust to the oracle adaptor implementation). - -In a pull-based system, each of the consumers would have to be called to pull the result from the oracle contract, but in the proposed push-based system, the adapted oracle would have to be called to push the results to each of the consumers. - -Transaction-wise, both systems are roughly equivalent in efficiency in this scenario, but in the push-based system, there's a need for the oracle consumers to store the results again, whereas in the pull-based system, the consumers may continue to refer to the oracle for the results. Although this may be somewhat less efficient, requiring the consumers to store the results can also provide security guarantees, especially with regards to result immutability. - -#### Result Immutability -In both the proposed specification and the alternate specification, results are immutable once they are determined. This is due to the expectation that typical consumers will require results to be immutable in order to determine a resulting state consistently. With the proposed push-based system, the consumer enforces the result immutability requirement, whereas in the alternate pull-based system, either the oracle would have to be trusted to implement the spec correctly and enforce the immutability requirement, or the consumer would also have to handle result immutability. - -For data which mutates over time, the `id` field may be structured to specify "what" and "when" for the data (using 128 bits to specify "when" is still safe for many millennia). - -## Implementation - -* [Tidbit](https://github.com/levelkdev/tidbit) tracks this EIP. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1154.md diff --git a/EIPS/eip-1155.md b/EIPS/eip-1155.md index 7444f76954ec53..f7c6bc8c1c84ce 100644 --- a/EIPS/eip-1155.md +++ b/EIPS/eip-1155.md @@ -1,710 +1,7 @@ --- eip: 1155 -title: Multi Token Standard -author: Witek Radomski , Andrew Cooke , Philippe Castonguay , James Therien , Eric Binet , Ronan Sandford -type: Standards Track category: ERC -status: Final -created: 2018-06-17 -discussions-to: https://github.com/ethereum/EIPs/issues/1155 -requires: 165 +status: Moved --- -## Simple Summary - -A standard interface for contracts that manage multiple token types. A single deployed contract may include any combination of fungible tokens, non-fungible tokens or other configurations (e.g. semi-fungible tokens). - -## Abstract - -This standard outlines a smart contract interface that can represent any number of fungible and non-fungible token types. Existing standards such as ERC-20 require deployment of separate contracts per token type. The ERC-721 standard's token ID is a single non-fungible index and the group of these non-fungibles is deployed as a single contract with settings for the entire collection. In contrast, the ERC-1155 Multi Token Standard allows for each token ID to represent a new configurable token type, which may have its own metadata, supply and other attributes. - -The `_id` argument contained in each function's argument set indicates a specific token or token type in a transaction. - -## Motivation - -Tokens standards like ERC-20 and ERC-721 require a separate contract to be deployed for each token type or collection. This places a lot of redundant bytecode on the Ethereum blockchain and limits certain functionality by the nature of separating each token contract into its own permissioned address. With the rise of blockchain games and platforms like Enjin Coin, game developers may be creating thousands of token types, and a new type of token standard is needed to support them. However, ERC-1155 is not specific to games and many other applications can benefit from this flexibility. - -New functionality is possible with this design such as transferring multiple token types at once, saving on transaction costs. Trading (escrow / atomic swaps) of multiple tokens can be built on top of this standard and it removes the need to "approve" individual token contracts separately. It is also easy to describe and mix multiple fungible or non-fungible token types in a single contract. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Smart contracts implementing the ERC-1155 standard MUST implement all of the functions in the `ERC1155` interface.** - -**Smart contracts implementing the ERC-1155 standard MUST implement the ERC-165 `supportsInterface` function and MUST return the constant value `true` if `0xd9b67a26` is passed through the `interfaceID` argument.** - -```solidity -pragma solidity ^0.5.9; - -/** - @title ERC-1155 Multi Token Standard - @dev See https://eips.ethereum.org/EIPS/eip-1155 - Note: The ERC-165 identifier for this interface is 0xd9b67a26. - */ -interface ERC1155 /* is ERC165 */ { - /** - @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - The `_from` argument MUST be the address of the holder whose balance is decreased. - The `_to` argument MUST be the address of the recipient whose balance is increased. - The `_id` argument MUST be the token type being transferred. - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). - */ - event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); - - /** - @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - The `_from` argument MUST be the address of the holder whose balance is decreased. - The `_to` argument MUST be the address of the recipient whose balance is increased. - The `_ids` argument MUST be the list of tokens being transferred. - The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). - */ - event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); - - /** - @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled). - */ - event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); - - /** - @dev MUST emit when the URI is updated for a token ID. - URIs are defined in RFC 3986. - The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". - */ - event URI(string _value, uint256 indexed _id); - - /** - @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). - @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). - MUST revert if `_to` is the zero address. - MUST revert if balance of holder for token `_id` is lower than the `_value` sent. - MUST revert on any other error. - MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). - After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). - @param _from Source address - @param _to Target address - @param _id ID of the token type - @param _value Transfer amount - @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` - */ - function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; - - /** - @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). - @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). - MUST revert if `_to` is the zero address. - MUST revert if length of `_ids` is not the same as length of `_values`. - MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. - MUST revert on any other error. - MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). - Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). - After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). - @param _from Source address - @param _to Target address - @param _ids IDs of each token type (order and length must match _values array) - @param _values Transfer amounts per token type (order and length must match _ids array) - @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` - */ - function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; - - /** - @notice Get the balance of an account's tokens. - @param _owner The address of the token holder - @param _id ID of the token - @return The _owner's balance of the token type requested - */ - function balanceOf(address _owner, uint256 _id) external view returns (uint256); - - /** - @notice Get the balance of multiple account/token pairs - @param _owners The addresses of the token holders - @param _ids ID of the tokens - @return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair) - */ - function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); - - /** - @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. - @dev MUST emit the ApprovalForAll event on success. - @param _operator Address to add to the set of authorized operators - @param _approved True if the operator is approved, false to revoke approval - */ - function setApprovalForAll(address _operator, bool _approved) external; - - /** - @notice Queries the approval status of an operator for a given owner. - @param _owner The owner of the tokens - @param _operator Address of authorized operator - @return True if the operator is approved, false if not - */ - function isApprovedForAll(address _owner, address _operator) external view returns (bool); -} -``` - -### ERC-1155 Token Receiver - -**Smart contracts MUST implement all of the functions in the `ERC1155TokenReceiver` interface to accept transfers. See "Safe Transfer Rules" for further detail.** - -**Smart contracts MUST implement the ERC-165 `supportsInterface` function and signify support for the `ERC1155TokenReceiver` interface to accept transfers. See "ERC1155TokenReceiver ERC-165 rules" for further detail.** - -```solidity -pragma solidity ^0.5.9; - -/** - Note: The ERC-165 identifier for this interface is 0x4e2312e0. -*/ -interface ERC1155TokenReceiver { - /** - @notice Handle the receipt of a single ERC1155 token type. - @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. - This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. - This function MUST revert if it rejects the transfer. - Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. - @param _operator The address which initiated the transfer (i.e. msg.sender) - @param _from The address which previously owned the token - @param _id The ID of the token being transferred - @param _value The amount of tokens being transferred - @param _data Additional data with no specified format - @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` - */ - function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); - - /** - @notice Handle the receipt of multiple ERC1155 token types. - @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. - This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). - This function MUST revert if it rejects the transfer(s). - Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. - @param _operator The address which initiated the batch transfer (i.e. msg.sender) - @param _from The address which previously owned the token - @param _ids An array containing ids of each token being transferred (order and length must match _values array) - @param _values An array containing amounts of each token being transferred (order and length must match _ids array) - @param _data Additional data with no specified format - @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - */ - function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); -} -``` - -### Safe Transfer Rules - -To be more explicit about how the standard `safeTransferFrom` and `safeBatchTransferFrom` functions MUST operate with respect to the `ERC1155TokenReceiver` hook functions, a list of scenarios and rules follows. - -#### Scenarios - -**_Scenario#1 :_** The recipient is not a contract. -* `onERC1155Received` and `onERC1155BatchReceived` MUST NOT be called on an EOA (Externally Owned Account). - -**_Scenario#2 :_** The transaction is not a mint/transfer of a token. -* `onERC1155Received` and `onERC1155BatchReceived` MUST NOT be called outside of a mint or transfer process. - -**_Scenario#3 :_** The receiver does not implement the necessary `ERC1155TokenReceiver` interface function(s). -* The transfer MUST be reverted with the one caveat below. - - If the token(s) being sent are part of a hybrid implementation of another standard, that particular standard's rules on sending to a contract MAY now be followed instead. See "Backwards Compatibility" section. - -**_Scenario#4 :_** The receiver implements the necessary `ERC1155TokenReceiver` interface function(s) but returns an unknown value. -* The transfer MUST be reverted. - -**_Scenario#5 :_** The receiver implements the necessary `ERC1155TokenReceiver` interface function(s) but throws an error. -* The transfer MUST be reverted. - -**_Scenario#6 :_** The receiver implements the `ERC1155TokenReceiver` interface and is the recipient of one and only one balance change (e.g. `safeTransferFrom` called). -* The balances for the transfer MUST have been updated before the `ERC1155TokenReceiver` hook is called on a recipient contract. -* The transfer event MUST have been emitted to reflect the balance changes before the `ERC1155TokenReceiver` hook is called on the recipient contract. -* One of `onERC1155Received` or `onERC1155BatchReceived` MUST be called on the recipient contract. -* The `onERC1155Received` hook SHOULD be called on the recipient contract and its rules followed. - - See "onERC1155Received rules" for further rules that MUST be followed. -* The `onERC1155BatchReceived` hook MAY be called on the recipient contract and its rules followed. - - See "onERC1155BatchReceived rules" for further rules that MUST be followed. - -**_Scenario#7 :_** The receiver implements the `ERC1155TokenReceiver` interface and is the recipient of more than one balance change (e.g. `safeBatchTransferFrom` called). -* All balance transfers that are referenced in a call to an `ERC1155TokenReceiver` hook MUST be updated before the `ERC1155TokenReceiver` hook is called on the recipient contract. -* All transfer events MUST have been emitted to reflect current balance changes before an `ERC1155TokenReceiver` hook is called on the recipient contract. -* `onERC1155Received` or `onERC1155BatchReceived` MUST be called on the recipient as many times as necessary such that every balance change for the recipient in the scenario is accounted for. - - The return magic value for every hook call MUST be checked and acted upon as per "onERC1155Received rules" and "onERC1155BatchReceived rules". -* The `onERC1155BatchReceived` hook SHOULD be called on the recipient contract and its rules followed. - - See "onERC1155BatchReceived rules" for further rules that MUST be followed. -* The `onERC1155Received` hook MAY be called on the recipient contract and its rules followed. - - See "onERC1155Received rules" for further rules that MUST be followed. - -**_Scenario#8 :_** You are the creator of a contract that implements the `ERC1155TokenReceiver` interface and you forward the token(s) onto another address in one or both of `onERC1155Received` and `onERC1155BatchReceived`. -* Forwarding should be considered acceptance and then initiating a new `safeTransferFrom` or `safeBatchTransferFrom` in a new context. - - The prescribed keccak256 acceptance value magic for the receiver hook being called MUST be returned after forwarding is successful. -* The `_data` argument MAY be re-purposed for the new context. -* If forwarding fails the transaction MAY be reverted. - - If the contract logic wishes to keep the ownership of the token(s) itself in this case it MAY do so. - -**_Scenario#9 :_** You are transferring tokens via a non-standard API call i.e. an implementation specific API and NOT `safeTransferFrom` or `safeBatchTransferFrom`. -* In this scenario all balance updates and events output rules are the same as if a standard transfer function had been called. - - i.e. an external viewer MUST still be able to query the balance via a standard function and it MUST be identical to the balance as determined by `TransferSingle` and `TransferBatch` events alone. -* If the receiver is a contract the `ERC1155TokenReceiver` hooks still need to be called on it and the return values respected the same as if a standard transfer function had been called. - - However while the `safeTransferFrom` or `safeBatchTransferFrom` functions MUST revert if a receiving contract does not implement the `ERC1155TokenReceiver` interface, a non-standard function MAY proceed with the transfer. - - See "Implementation specific transfer API rules". - - -#### Rules - -**_safeTransferFrom rules:_** -* Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section). -* MUST revert if `_to` is the zero address. -* MUST revert if balance of holder for token `_id` is lower than the `_value` sent to the recipient. -* MUST revert on any other error. -* MUST emit the `TransferSingle` event to reflect the balance change (see "TransferSingle and TransferBatch event rules" section). -* After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "onERC1155Received rules" section). - - The `_data` argument provided by the sender for the transfer MUST be passed with its contents unaltered to the `onERC1155Received` hook function via its `_data` argument. - -**_safeBatchTransferFrom rules:_** -* Caller must be approved to manage all the tokens being transferred out of the `_from` account (see "Approval" section). -* MUST revert if `_to` is the zero address. -* MUST revert if length of `_ids` is not the same as length of `_values`. -* MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. -* MUST revert on any other error. -* MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "TransferSingle and TransferBatch event rules" section). -* The balance changes and events MUST occur in the array order they were submitted (_ids[0]/_values[0] before _ids[1]/_values[1], etc). -* After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` or `onERC1155BatchReceived` on `_to` and act appropriately (see "onERC1155Received and onERC1155BatchReceived rules" section). - - The `_data` argument provided by the sender for the transfer MUST be passed with its contents unaltered to the `ERC1155TokenReceiver` hook function(s) via their `_data` argument. - -**_TransferSingle and TransferBatch event rules:_** -* `TransferSingle` SHOULD be used to indicate a single balance transfer has occurred between a `_from` and `_to` pair. - - It MAY be emitted multiple times to indicate multiple balance changes in the transaction, but note that `TransferBatch` is designed for this to reduce gas consumption. - - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - - The `_from` argument MUST be the address of the holder whose balance is decreased. - - The `_to` argument MUST be the address of the recipient whose balance is increased. - - The `_id` argument MUST be the token type being transferred. - - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. - - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". -* `TransferBatch` SHOULD be used to indicate multiple balance transfers have occurred between a `_from` and `_to` pair. - - It MAY be emitted with a single element in the list to indicate a singular balance change in the transaction, but note that `TransferSingle` is designed for this to reduce gas consumption. - - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). - - The `_from` argument MUST be the address of the holder whose balance is decreased for each entry pair in `_ids` and `_values`. - - The `_to` argument MUST be the address of the recipient whose balance is increased for each entry pair in `_ids` and `_values`. - - The `_ids` array argument MUST contain the ids of the tokens being transferred. - - The `_values` array argument MUST contain the number of token to be transferred for each corresponding entry in `_ids`. - - `_ids` and `_values` MUST have the same length. - - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". - - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). See "Minting/creating and burning/destroying rules". -* The total value transferred from address `0x0` minus the total value transferred to `0x0` observed via the `TransferSingle` and `TransferBatch` events MAY be used by clients and exchanges to determine the "circulating supply" for a given token ID. -* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the `TransferSingle` event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_value` of 0. -* All `TransferSingle` and `TransferBatch` events MUST be emitted to reflect all the balance changes that have occurred before any call(s) to `onERC1155Received` or `onERC1155BatchReceived`. - - To make sure event order is correct in the case of valid re-entry (e.g. if a receiver contract forwards tokens on receipt) state balance and events balance MUST match before calling an external contract. - -**_onERC1155Received rules:_** -- The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). -* The `_from` argument MUST be the address of the holder whose balance is decreased. - - `_from` MUST be 0x0 for a mint. -* The `_id` argument MUST be the token type being transferred. -* The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. -* The `_data` argument MUST contain the information provided by the sender for the transfer with its contents unaltered. - - i.e. it MUST pass on the unaltered `_data` argument sent via the `safeTransferFrom` or `safeBatchTransferFrom` call for this transfer. -* The recipient contract MAY accept an increase of its balance by returning the acceptance magic value `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` - - If the return value is `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` the transfer MUST be completed or MUST revert if any other conditions are not met for success. -* The recipient contract MAY reject an increase of its balance by calling revert. - - If the recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` the transaction MUST be reverted. -* `onERC1155Received` (and/or `onERC1155BatchReceived`) MAY be called multiple times in a single transaction and the following requirements must be met: - - All callbacks represent mutually exclusive balance changes. - - The set of all calls to `onERC1155Received` and `onERC1155BatchReceived` describes all balance changes that occurred during the transaction in the order submitted. -* A contract MAY skip calling the `onERC1155Received` hook function if the transfer operation is transferring the token to itself. - -**_onERC1155BatchReceived rules:_** -- The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). -* The `_from` argument MUST be the address of the holder whose balance is decreased. - - `_from` MUST be 0x0 for a mint. -* The `_ids` argument MUST be the list of tokens being transferred. -* The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in `_ids`) the holder balance is decreased by and match what the recipient balance is increased by. -* The `_data` argument MUST contain the information provided by the sender for the transfer with its contents unaltered. - - i.e. it MUST pass on the unaltered `_data` argument sent via the `safeBatchTransferFrom` call for this transfer. -* The recipient contract MAY accept an increase of its balance by returning the acceptance magic value `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` - - If the return value is `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` the transfer MUST be completed or MUST revert if any other conditions are not met for success. -* The recipient contract MAY reject an increase of its balance by calling revert. - - If the recipient contract throws/reverts the transaction MUST be reverted. -* If the return value is anything other than `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` the transaction MUST be reverted. -* `onERC1155BatchReceived` (and/or `onERC1155Received`) MAY be called multiple times in a single transaction and the following requirements must be met: - - All callbacks represent mutually exclusive balance changes. - - The set of all calls to `onERC1155Received` and `onERC1155BatchReceived` describes all balance changes that occurred during the transaction in the order submitted. -* A contract MAY skip calling the `onERC1155BatchReceived` hook function if the transfer operation is transferring the token(s) to itself. - -**_ERC1155TokenReceiver ERC-165 rules:_** -* The implementation of the ERC-165 `supportsInterface` function SHOULD be as follows: - ```solidity - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return interfaceID == 0x01ffc9a7 || // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`). - interfaceID == 0x4e2312e0; // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). - } - ``` -* The implementation MAY differ from the above but: - - It MUST return the constant value `true` if `0x01ffc9a7` is passed through the `interfaceID` argument. This signifies ERC-165 support. - - It MUST return the constant value `true` if `0x4e2312e0` is passed through the `interfaceID` argument. This signifies ERC-1155 `ERC1155TokenReceiver` support. - - It MUST NOT consume more than 10,000 gas. - - This keeps it below the ERC-165 requirement of 30,000 gas, reduces the gas reserve needs and minimises possible side-effects of gas exhaustion during the call. - -**_Implementation specific transfer API rules:_** -* If an implementation specific API function is used to transfer ERC-1155 token(s) to a contract, the `safeTransferFrom` or `safeBatchTransferFrom` (as appropriate) rules MUST still be followed if the receiver implements the `ERC1155TokenReceiver` interface. If it does not the non-standard implementation SHOULD revert but MAY proceed. -* An example: - 1. An approved user calls a function such as `function myTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values);`. - 2. `myTransferFrom` updates the balances for `_from` and `_to` addresses for all `_ids` and `_values`. - 3. `myTransferFrom` emits `TransferBatch` with the details of what was transferred from address `_from` to address `_to`. - 4. `myTransferFrom` checks if `_to` is a contract address and determines that it is so (if not, then the transfer can be considered successful). - 5. `myTransferFrom` calls `onERC1155BatchReceived` on `_to` and it reverts or returns an unknown value (if it had returned `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` the transfer can be considered successful). - 6. At this point `myTransferFrom` SHOULD revert the transaction immediately as receipt of the token(s) was not explicitly accepted by the `onERC1155BatchReceived` function. - 7. If however `myTransferFrom` wishes to continue it MUST call `supportsInterface(0x4e2312e0)` on `_to` and if it returns the constant value `true` the transaction MUST be reverted, as it is now known to be a valid receiver and the previous acceptance step failed. - - NOTE: You could have called `supportsInterface(0x4e2312e0)` at a previous step if you wanted to gather and act upon that information earlier, such as in a hybrid standards scenario. - 8. If the above call to `supportsInterface(0x4e2312e0)` on `_to` reverts or returns a value other than the constant value `true` the `myTransferFrom` function MAY consider this transfer successful. - - __NOTE__: this MAY result in unrecoverable tokens if sent to an address that does not expect to receive ERC-1155 tokens. -* The above example is not exhaustive but illustrates the major points (and shows that most are shared with `safeTransferFrom` and `safeBatchTransferFrom`): - - Balances that are updated MUST have equivalent transfer events emitted. - - A receiver address has to be checked if it is a contract and if so relevant `ERC1155TokenReceiver` hook function(s) have to be called on it. - - Balances (and events associated) that are referenced in a call to an `ERC1155TokenReceiver` hook MUST be updated (and emitted) before the `ERC1155TokenReceiver` hook is called. - - The return values of the `ERC1155TokenReceiver` hook functions that are called MUST be respected if they are implemented. - - Only non-standard transfer functions MAY allow tokens to be sent to a recipient contract that does NOT implement the necessary `ERC1155TokenReceiver` hook functions. `safeTransferFrom` and `safeBatchTransferFrom` MUST revert in that case (unless it is a hybrid standards implementation see "Backwards Compatibility"). - -**_Minting/creating and burning/destroying rules:_** -* A mint/create operation is essentially a specialized transfer and MUST follow these rules: - - To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the `TransferSingle` event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_value` of 0. - - The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the mint(s) (i.e. singles or batches) however the `_from` argument MUST be set to `0x0` (i.e. zero address) to flag the transfer as a mint to contract observers. - - __NOTE:__ This includes tokens that are given an initial balance in the contract. The balance of the contract MUST also be able to be determined by events alone meaning initial contract balances (for eg. in construction) MUST emit events to reflect those balances too. -* A burn/destroy operation is essentially a specialized transfer and MUST follow these rules: - - The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the burn(s) (i.e. singles or batches) however the `_to` argument MUST be set to `0x0` (i.e. zero address) to flag the transfer as a burn to contract observers. - - When burning/destroying you do not have to actually transfer to `0x0` (that is impl specific), only the `_to` argument in the event MUST be set to `0x0` as above. -* The total value transferred from address `0x0` minus the total value transferred to `0x0` observed via the `TransferSingle` and `TransferBatch` events MAY be used by clients and exchanges to determine the "circulating supply" for a given token ID. -* As mentioned above mint/create and burn/destroy operations are specialized transfers and so will likely be accomplished with custom transfer functions rather than `safeTransferFrom` or `safeBatchTransferFrom`. If so the "Implementation specific transfer API rules" section would be appropriate. - - Even in a non-safe API and/or hybrid standards case the above event rules MUST still be adhered to when minting/creating or burning/destroying. -* A contract MAY skip calling the `ERC1155TokenReceiver` hook function(s) if the mint operation is transferring the token(s) to itself. In all other cases the `ERC1155TokenReceiver` rules MUST be followed as appropriate for the implementation (i.e. safe, custom and/or hybrid). - - -##### A solidity example of the keccak256 generated constants for the various magic values (these MAY be used by implementation): - -```solidity -bytes4 constant public ERC1155_ERC165 = 0xd9b67a26; // ERC-165 identifier for the main token standard. -bytes4 constant public ERC1155_ERC165_TOKENRECEIVER = 0x4e2312e0; // ERC-165 identifier for the `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). -bytes4 constant public ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`). -bytes4 constant public ERC1155_BATCH_ACCEPTED = 0xbc197c81; // Return value from `onERC1155BatchReceived` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`). -``` - -### Metadata - -The URI value allows for ID substitution by clients. If the string `{id}` exists in any URI, clients MUST replace this with the actual token ID in hexadecimal form. This allows for a large number of tokens to use the same on-chain string by defining a URI once, for that large number of tokens. - -* The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: `[0-9a-f]` with no 0x prefix. -* The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary. - -Example of such a URI: `https://token-cdn-domain/{id}.json` would be replaced with `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` if the client is referring to token ID 314592/0x4CCE0. - -#### Metadata Extensions - -The optional `ERC1155Metadata_URI` extension can be identified with the [ERC-165 Standard Interface Detection](./eip-165.md). - -If the optional `ERC1155Metadata_URI` extension is included: -* The ERC-165 `supportsInterface` function MUST return the constant value `true` if `0x0e89341c` is passed through the `interfaceID` argument. -* _Changes_ to the URI MUST emit the `URI` event if the change can be expressed with an event (i.e. it isn't dynamic/programmatic). - - An implementation MAY emit the `URI` event during a mint operation but it is NOT mandatory. An observer MAY fetch the metadata uri at mint time from the `uri` function if it was not emitted. -* The `uri` function SHOULD be used to retrieve values if no event was emitted. -* The `uri` function MUST return the same value as the latest event for an `_id` if it was emitted. -* The `uri` function MUST NOT be used to check for the existence of a token as it is possible for an implementation to return a valid string even if the token does not exist. - -```solidity -pragma solidity ^0.5.9; - -/** - Note: The ERC-165 identifier for this interface is 0x0e89341c. -*/ -interface ERC1155Metadata_URI { - /** - @notice A distinct Uniform Resource Identifier (URI) for a given token. - @dev URIs are defined in RFC 3986. - The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". - @return URI string - */ - function uri(uint256 _id) external view returns (string memory); -} -``` - -#### ERC-1155 Metadata URI JSON Schema - -This JSON schema is loosely based on the "ERC721 Metadata JSON Schema", but includes optional formatting to allow for ID substitution by clients. If the string `{id}` exists in any JSON value, it MUST be replaced with the actual token ID, by all client software that follows this standard. - -* The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: `[0-9a-f]` with no 0x prefix. -* The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary. - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents" - }, - "decimals": { - "type": "integer", - "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation." - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, object or arrays." - } - } -} -``` - -An example of an ERC-1155 Metadata JSON file follows. The properties array proposes some SUGGESTED formatting for token-specific display properties and metadata. - -```json -{ - "name": "Asset Name", - "description": "Lorem ipsum...", - "image": "https:\/\/s3.amazonaws.com\/your-bucket\/images\/{id}.png", - "properties": { - "simple_property": "example value", - "rich_property": { - "name": "Name", - "value": "123", - "display_value": "123 Example Value", - "class": "emphasis", - "css": { - "color": "#ffffff", - "font-weight": "bold", - "text-decoration": "underline" - } - }, - "array_property": { - "name": "Name", - "value": [1,2,3,4], - "class": "emphasis" - } - } -} -``` - -##### Localization - -Metadata localization should be standardized to increase presentation uniformity across all languages. As such, a simple overlay method is proposed to enable localization. If the metadata JSON file contains a `localization` attribute, its content MAY be used to provide localized values for fields that need it. The `localization` attribute should be a sub-object with three attributes: `uri`, `default` and `locales`. If the string `{locale}` exists in any URI, it MUST be replaced with the chosen locale by all client software. - -##### JSON Schema - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "decimals": { - "type": "integer", - "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation." - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.", - }, - "localization": { - "type": "object", - "required": ["uri", "default", "locales"], - "properties": { - "uri": { - "type": "string", - "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request." - }, - "default": { - "type": "string", - "description": "The locale of the default data within the base JSON" - }, - "locales": { - "type": "array", - "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)." - } - } - } - } -} -``` - -##### Localized Sample - -Base URI: -```json -{ - "name": "Advertising Space", - "description": "Each token represents a unique Ad space in the city.", - "localization": { - "uri": "ipfs://QmWS1VAdMD353A6SDk9wNyvkT14kyCiZrNDYAad4w1tKqT/{locale}.json", - "default": "en", - "locales": ["en", "es", "fr"] - } -} -``` - -es.json: -```json -{ - "name": "Espacio Publicitario", - "description": "Cada token representa un espacio publicitario único en la ciudad." -} -``` - -fr.json: -```json -{ - "name": "Espace Publicitaire", - "description": "Chaque jeton représente un espace publicitaire unique dans la ville." -} -``` - -### Approval - -The function `setApprovalForAll` allows an operator to manage one's entire set of tokens on behalf of the approver. To permit approval of a subset of token IDs, an interface such as [ERC-1761 Scoped Approval Interface](./eip-1761.md) is suggested. -The counterpart `isApprovedForAll` provides introspection into any status set by `setApprovalForAll`. - -An owner SHOULD be assumed to always be able to operate on their own tokens regardless of approval status, so should SHOULD NOT have to call `setApprovalForAll` to approve themselves as an operator before they can operate on them. - -## Rationale - -### Metadata Choices - -The `symbol` function (found in the ERC-20 and ERC-721 standards) was not included as we do not believe this is a globally useful piece of data to identify a generic virtual item / asset and are also prone to collisions. Short-hand symbols are used in tickers and currency trading, but they aren't as useful outside of that space. - -The `name` function (for human-readable asset names, on-chain) was removed from the standard to allow the Metadata JSON to be the definitive asset name and reduce duplication of data. This also allows localization for names, which would otherwise be prohibitively expensive if each language string was stored on-chain, not to mention bloating the standard interface. While this decision may add a small burden on implementers to host a JSON file containing metadata, we believe any serious implementation of ERC-1155 will already utilize JSON Metadata. - -### Upgrades - -The requirement to emit `TransferSingle` or `TransferBatch` on balance change implies that a valid implementation of ERC-1155 redeploying to a new contract address MUST emit events from the new contract address to replicate the deprecated contract final state. It is valid to only emit a minimal number of events to reflect only the final balance and omit all the transactions that led to that state. The event emit requirement is to ensure that the current state of the contract can always be traced only through events. To alleviate the need to emit events when changing contract address, consider using the proxy pattern, such as described in [EIP-2535](./eip-2535.md). This will also have the added benefit of providing a stable contract address for users. - -### Design decision: Supporting non-batch - -The standard supports `safeTransferFrom` and `onERC1155Received` functions because they are significantly cheaper for single token-type transfers, which is arguably a common use case. - -### Design decision: Safe transfers only - -The standard only supports safe-style transfers, making it possible for receiver contracts to depend on `onERC1155Received` or `onERC1155BatchReceived` function to be always called at the end of a transfer. - -### Guaranteed log trace - -As the Ethereum ecosystem continues to grow, many dapps are relying on traditional databases and explorer API services to retrieve and categorize data. The ERC-1155 standard guarantees that event logs emitted by the smart contract will provide enough data to create an accurate record of all current token balances. A database or explorer may listen to events and be able to provide indexed and categorized searches of every ERC-1155 token in the contract. - -### Approval - -The function `setApprovalForAll` allows an operator to manage one's entire set of tokens on behalf of the approver. It enables frictionless interaction with exchange and trade contracts. - -Restricting approval to a certain set of token IDs, quantities or other rules MAY be done with an additional interface or an external contract. The rationale is to keep the ERC-1155 standard as generic as possible for all use-cases without imposing a specific approval scheme on implementations that may not need it. Standard token approval interfaces can be used, such as the suggested [ERC-1761 Scoped Approval Interface](./eip-1761.md) which is compatible with ERC-1155. - -## Backwards Compatibility - -There have been requirements during the design discussions to have this standard be compatible with existing standards when sending to contract addresses, specifically ERC-721 at time of writing. -To cater for this scenario, there is some leeway with the revert logic should a contract not implement the `ERC1155TokenReceiver` as per "Safe Transfer Rules" section above, specifically "Scenario#3 : The receiver does not implement the necessary `ERC1155TokenReceiver` interface function(s)". - -Hence in a hybrid ERC-1155 contract implementation an extra call MUST be made on the recipient contract and checked before any hook calls to `onERC1155Received` or `onERC1155BatchReceived` are made. -Order of operation MUST therefore be: -1. The implementation MUST call the function `supportsInterface(0x4e2312e0)` on the recipient contract, providing at least 10,000 gas. -2. If the function call succeeds and the return value is the constant value `true` the implementation proceeds as a regular ERC-1155 implementation, with the call(s) to the `onERC1155Received` or `onERC1155BatchReceived` hooks and rules associated. -3. If the function call fails or the return value is NOT the constant value `true` the implementation can assume the recipient contract is not an `ERC1155TokenReceiver` and follow its other standard's rules for transfers. - -*__Note that a pure implementation of a single standard is recommended__* rather than a hybrid solution, but an example of a hybrid ERC-1155/ERC-721 contract is linked in the references section under implementations. - -An important consideration is that even if the tokens are sent with another standard's rules the *__ERC-1155 transfer events MUST still be emitted.__* This is so the balances can still be determined via events alone as per ERC-1155 standard rules. - -## Usage - -This standard can be used to represent multiple token types for an entire domain. Both fungible and non-fungible tokens can be stored in the same smart-contract. - -### Batch Transfers - -The `safeBatchTransferFrom` function allows for batch transfers of multiple token IDs and values. The design of ERC-1155 makes batch transfers possible without the need for a wrapper contract, as with existing token standards. This reduces gas costs when more than one token type is included in a batch transfer, as compared to single transfers with multiple transactions. - -Another advantage of standardized batch transfers is the ability for a smart contract to respond to the batch transfer in a single operation using `onERC1155BatchReceived`. - -It is RECOMMENDED that clients and wallets sort the token IDs and associated values (in ascending order) when posting a batch transfer, as some ERC-1155 implementations offer significant gas cost savings when IDs are sorted. See [Horizon Games - Multi-Token Standard](https://github.com/horizon-games/multi-token-standard) "packed balance" implementation for an example of this. - -### Batch Balance - -The `balanceOfBatch` function allows clients to retrieve balances of multiple owners and token IDs with a single call. - -### Enumerating from events - -In order to keep storage requirements light for contracts implementing ERC-1155, enumeration (discovering the IDs and values of tokens) must be done using event logs. It is RECOMMENDED that clients such as exchanges and blockchain explorers maintain a local database containing the token ID, Supply, and URI at the minimum. This can be built from each TransferSingle, TransferBatch, and URI event, starting from the block the smart contract was deployed until the latest block. - -ERC-1155 contracts must therefore carefully emit `TransferSingle` or `TransferBatch` events in any instance where tokens are created, minted, transferred or destroyed. - -### Non-Fungible Tokens - -The following strategies are examples of how you MAY mix fungible and non-fungible tokens together in the same contract. The standard does NOT mandate how an implementation must do this. - -##### Split ID bits - -The top 128 bits of the uint256 `_id` parameter in any ERC-1155 function MAY represent the base token ID, while the bottom 128 bits MAY represent the index of the non-fungible to make it unique. - -Non-fungible tokens can be interacted with using an index based accessor into the contract/token data set. Therefore to access a particular token set within a mixed data contract and a particular non-fungible within that set, `_id` could be passed as ``. - -To identify a non-fungible set/category as a whole (or a fungible) you COULD just pass in the base id via the `_id` argument as ``. If your implementation uses this technique this naturally means the index of a non-fungible SHOULD be 1-based. - -Inside the contract code the two pieces of data needed to access the individual non-fungible can be extracted with uint128(~0) and the same mask shifted by 128. - -```solidity -uint256 baseTokenNFT = 12345 << 128; -uint128 indexNFT = 50; - -uint256 baseTokenFT = 54321 << 128; - -balanceOf(baseTokenNFT, msg.sender); // Get balance of the base token for non-fungible set 12345 (this MAY be used to get balance of the user for all of this token set if the implementation wishes as a convenience). -balanceOf(baseTokenNFT + indexNFT, msg.sender); // Get balance of the token at index 50 for non-fungible set 12345 (should be 1 if user owns the individual non-fungible token or 0 if they do not). -balanceOf(baseTokenFT, msg.sender); // Get balance of the fungible base token 54321. -``` - -Note that 128 is an arbitrary number, an implementation MAY choose how they would like this split to occur as suitable for their use case. An observer of the contract would simply see events showing balance transfers and mints happening and MAY track the balances using that information alone. -For an observer to be able to determine type (non-fungible or fungible) from an ID alone they would have to know the split ID bits format on a implementation by implementation basis. - -The [ERC-1155 Reference Implementation](https://github.com/enjin/erc-1155) is an example of the split ID bits strategy. - -##### Natural Non-Fungible tokens - -Another simple way to represent non-fungibles is to allow a maximum value of 1 for each non-fungible token. This would naturally mirror the real world, where unique items have a quantity of 1 and fungible items have a quantity greater than 1. - -## References - -**Standards** -- [ERC-721 Non-Fungible Token Standard](./eip-721.md) -- [ERC-165 Standard Interface Detection](./eip-165.md) -- [ERC-1538 Transparent Contract Standard](./eip-1538.md) -- [JSON Schema](https://json-schema.org/) -- [RFC 2119 Key words for use in RFCs to Indicate Requirement Levels](https://www.ietf.org/rfc/rfc2119.txt) - -**Implementations** -- [ERC-1155 Reference Implementation](https://github.com/enjin/erc-1155) -- [Horizon Games - Multi-Token Standard](https://github.com/horizon-games/multi-token-standard) -- [Enjin Coin](https://enjincoin.io) ([GitHub](https://github.com/enjin)) -- [The Sandbox - Dual ERC-1155/721 Contract](https://github.com/pixowl/thesandbox-contracts/tree/master/src/Asset) - -**Articles & Discussions** -- [GitHub - Original Discussion Thread](https://github.com/ethereum/EIPs/issues/1155) -- [ERC-1155 - The Crypto Item Standard](https://blog.enjincoin.io/erc-1155-the-crypto-item-standard-ac9cf1c5a226) -- [Here Be Dragons - Going Beyond ERC-20 and ERC-721 To Reduce Gas Cost by ~80%](https://medium.com/horizongames/going-beyond-erc20-and-erc721-9acebd4ff6ef) -- [Blockonomi - Ethereum ERC-1155 Token Perfect for Online Games, Possibly More](https://blockonomi.com/erc1155-gaming-token/) -- [Beyond Gaming - Exploring the Utility of ERC-1155 Token Standard!](https://blockgeeks.com/erc-1155-token/) -- [ERC-1155: A new standard for The Sandbox](https://medium.com/sandbox-game/erc-1155-a-new-standard-for-the-sandbox-c95ee1e45072) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1155.md diff --git a/EIPS/eip-1167.md b/EIPS/eip-1167.md index ebb2d0a3278c3d..c8ce36929836ca 100644 --- a/EIPS/eip-1167.md +++ b/EIPS/eip-1167.md @@ -1,115 +1,7 @@ --- eip: 1167 -title: Minimal Proxy Contract -author: Peter Murray (@yarrumretep), Nate Welch (@flygoing), Joe Messerman (@JAMesserman) -discussions-to: https://github.com/optionality/clone-factory/issues/10 -status: Final -type: Standards Track category: ERC -created: 2018-06-22 -requires: 211 +status: Moved --- -## Simple Summary -To simply and cheaply clone contract functionality in an immutable way, this standard specifies a minimal bytecode implementation that delegates all calls to a known, fixed address. -## Abstract -By standardizing on a known minimal bytecode redirect implementation, this standard allows users and third party tools (e.g. Etherscan) to (a) simply discover that a contract will always redirect in a known manner and (b) depend on the behavior of the code at the destination contract as the behavior of the redirecting contract. Specifically, tooling can interrogate the bytecode at a redirecting address to determine the location of the code that will run - and can depend on representations about that code (verified source, third-party audits, etc). This implementation forwards all calls and 100% of the gas to the implementation contract and then relays the return value back to the caller. In the case where the implementation reverts, the revert is passed back along with the payload data (for revert with message). - -## Motivation -This standard supports use-cases wherein it is desirable to clone exact contract functionality with a minimum of side effects (e.g. memory slot stomping) and with low gas cost deployment of duplicate proxies. - -## Specification -The exact bytecode of the standard clone contract is this: `363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3` wherein the bytes at indices 10 - 29 (inclusive) are replaced with the 20 byte address of the master functionality contract. - -A reference implementation of this can be found at the [optionality/clone-factory](https://github.com/optionality/clone-factory) github repo. - -## Rationale -The goals of this effort have been the following: -- inexpensive deployment (low gas to deploy clones) -- support clone initialization in creation transaction (through factory contract model) -- simple clone bytecode to encourage directly bytecode interrogation (see CloneProbe.sol in the clone-factory project) -- dependable, locked-down behavior - this is not designed to handle upgradability, nor should it as the representation we are seeking is stronger. -- small operational overhead - adds a single call cost to each call -- handles error return bubbling for revert messages - -## Backwards Compatibility -There are no backwards compatibility issues. There may be some systems that are using earlier versions of the proxy contract bytecode. They will not be compliant with this standard. - -## Test Cases -Test cases include: -- invocation with no arguments -- invocation with arguments -- invocation with fixed length return values -- invocation with variable length return values -- invocation with revert (confirming reverted payload is transferred) - -Tests for these cases are included in the reference implementation project. - -## Implementation -Deployment bytecode is not included in this specification. One approach is defined in the proxy-contract reference implementation. - -### Standard Proxy -The disassembly of the standard deployed proxy contract code (from r2 and edited to include stack visualization) - -``` -| 0x00000000 36 calldatasize cds -| 0x00000001 3d returndatasize 0 cds -| 0x00000002 3d returndatasize 0 0 cds -| 0x00000003 37 calldatacopy -| 0x00000004 3d returndatasize 0 -| 0x00000005 3d returndatasize 0 0 -| 0x00000006 3d returndatasize 0 0 0 -| 0x00000007 36 calldatasize cds 0 0 0 -| 0x00000008 3d returndatasize 0 cds 0 0 0 -| 0x00000009 73bebebebebe. push20 0xbebebebe 0xbebe 0 cds 0 0 0 -| 0x0000001e 5a gas gas 0xbebe 0 cds 0 0 0 -| 0x0000001f f4 delegatecall suc 0 -| 0x00000020 3d returndatasize rds suc 0 -| 0x00000021 82 dup3 0 rds suc 0 -| 0x00000022 80 dup1 0 0 rds suc 0 -| 0x00000023 3e returndatacopy suc 0 -| 0x00000024 90 swap1 0 suc -| 0x00000025 3d returndatasize rds 0 suc -| 0x00000026 91 swap2 suc 0 rds -| 0x00000027 602b push1 0x2b 0x2b suc 0 rds -| ,=< 0x00000029 57 jumpi 0 rds -| | 0x0000002a fd revert -| `-> 0x0000002b 5b jumpdest 0 rds -\ 0x0000002c f3 return - -``` - -NOTE: as an effort to reduce gas costs as much as possible, the above bytecode depends on EIP-211 specification that `returndatasize` returns zero prior to any calls within the call-frame. `returndatasize` uses 1 less gas than `dup*`. - -### Vanity Address Optimization -Proxy deployment can be further optimized by installing the master contract at a vanity contract deployment address with leading zero-bytes. By generating a master contract vanity address that includes Z leading 0 bytes in its address, you can shorten the proxy bytecode by replacing the `push20` opcode with `pushN` (where N is 20 - Z) followed by the N non-zero address bytes. The revert jump address is decremented by Z in this case. Here is an example where Z = 4: -``` -| 0x00000000 36 calldatasize cds -| 0x00000001 3d returndatasize 0 cds -| 0x00000002 3d returndatasize 0 0 cds -| 0x00000003 37 calldatacopy -| 0x00000004 3d returndatasize 0 -| 0x00000005 3d returndatasize 0 0 -| 0x00000006 3d returndatasize 0 0 0 -| 0x00000007 36 calldatasize cds 0 0 0 -| 0x00000008 3d returndatasize 0 cds 0 0 0 -| 0x00000009 6fbebebebebe. push16 0xbebebebe 0xbebe 0 cds 0 0 0 -| 0x0000001a 5a gas gas 0xbebe 0 cds 0 0 0 -| 0x0000001b f4 delegatecall suc 0 -| 0x0000001c 3d returndatasize rds suc 0 -| 0x0000001d 82 dup3 0 rds suc 0 -| 0x0000001e 80 dup1 0 0 rds suc 0 -| 0x0000001f 3e returndatacopy suc 0 -| 0x00000020 90 swap1 0 suc -| 0x00000021 3d returndatasize rds 0 suc -| 0x00000022 91 swap2 suc 0 rds -| 0x00000023 6027 push1 0x27 0x27 suc 0 rds -| ,=< 0x00000025 57 jumpi 0 rds -| | 0x00000026 fd revert -| `-> 0x00000027 5b jumpdest 0 rds -\ 0x00000028 f3 return -``` -This saves 4 bytes of proxy contract size (savings on each deployment) and has zero impact on runtime gas costs. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1167.md diff --git a/EIPS/eip-1175.md b/EIPS/eip-1175.md index b56290ab1a1be6..6febb5f659e7d4 100644 --- a/EIPS/eip-1175.md +++ b/EIPS/eip-1175.md @@ -1,533 +1,7 @@ --- eip: 1175 -title: Wallet & shop standard for all tokens (erc20) -author: Jet Lim (@Nitro888) -discussions-to: https://github.com/ethereum/EIPs/issues/1182 -status: Stagnant -type: Standards Track category: ERC -created: 2018-06-21 -requires: 20 +status: Moved --- -# All tokens go to heaven -## Simple Summary -Make wallets and shops created from certified contracts make erc20 tokens easy to use for commerce. - -![wallet](/assets/eip-1175/wallet.png) - -## Abstract -The mutual trust between the wallet and the shop created by the authenticated contract allows you to pay for and purchase items at a simple process. - -## Motivation -New standards with improvements have been released, but the majority of tokens currently being developed are erc20 tokens. So I felt I needed a proposal to use old tokens in commerce. - To use various erc20 tokens for trading, you need a custom contract. However, a single wallet with a variety of tokens, and a mutually trusted store, can make transactions that are simple and efficient. The erc20 token is traded through two calls, `approve (address _spender, uint256 _value)` and `transferFrom (address _from, address _to, uint256 _value)`, but when using the wallet contract, `paySafe (address _shop, uint256 _item)`will be traded only in one call. -And if you only reuse the store interface, you can also trade using `payUnsafe (address _shop, uint256 _item)`. - -## Specification -![workflow](/assets/eip-1175/workflow.png) -## WalletCenter -### Methods -#### createWallet -Create wallet contract and add to list. Returns the address of new wallet. - -``` js -function createWallet() public returns (address _wallet) -``` - -#### isWallet -Returns true or false value for test this address is a created by createWallet. - -``` js -function isWallet(address _wallet) public constant returns (bool) -``` - -#### createShop -Create Shop contract and add to list. Returns the address of new Shop with erc20 token address. - -``` js -function createShop(address _erc20) public returns (address _shop) -``` - -#### isShop -Returns true or false value for test this address is a created by createWallet. - -``` js -function isShop(address _shop) public constant returns (bool) -``` - -### Events -#### Wallet -Search for my wallet. -``` js -event Wallet(address indexed _owner, address indexed _wallet) -``` - -#### Shop -Search for my shop. -``` js -event Shop(address indexed _owner, address indexed _shop, address indexed _erc20) -``` - -## Wallet -Wallet must be created by wallet center. -### Methods -#### balanceOf -Returns the account balance of Wallet. -``` js -function balanceOf(address _erc20) public constant returns (uint256 balance) -``` - -#### withdrawal -withdrawal `_value` amount of `_erc20` token to `_owner`. -``` js -function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) -``` - -#### paySafe -Pay for safe shop (created by contract) item with item index `_item`. -``` js -function paySafe(address _shop, uint256 _item) onlyOwner onlyShop(_shop) public payable returns (bool success) -``` - -#### payUnsafe -Pay for unsafe shop (did not created by contract) item with item index `_item`. -``` js -function payUnsafe(address _shop, uint256 _item) onlyOwner public payable returns (bool success) -``` - -#### payCancel -Cancel pay and refund. (only weekly model) -``` js -function payCancel(address _shop, uint256 _item) onlyOwner public returns (bool success) -``` - -#### refund -Refund from shop with item index `_item`. -``` js -function refund(uint256 _item, uint256 _value) public payable returns (bool success) -``` - -### Events -#### Pay -``` js -event Pay(address indexed _shop, uint256 indexed _item, uint256 indexed _value) -``` - -#### Refund -``` js -event Refund(address indexed _shop, uint256 indexed _item, uint256 indexed _value) -``` - -## Shop -Shop is created by wallet center or not. but Shop that created by wallet center is called safe shop. -### Methods -#### balanceOf -Returns the account balance of Shop. -``` js -function balanceOf(address _erc20) public constant returns (uint256 balance) -``` - -#### withdrawal -withdrawal `_value` amount of `_erc20` token to `_owner`. -``` js -function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) -``` - -#### pay -Pay from buyer with item index `_item`. -``` js -function pay(uint256 _item) onlyWallet(msg.sender) public payable returns (bool success) -``` - -#### refund -refund token to `_to`. -``` js -function refund(address _buyer, uint256 _item, uint256 _value) onlyWallet(_buyer) onlyOwner public payable returns (bool success) -``` - -#### resister -Listing item for sell. -``` js -function resister(uint8 _category, uint256 _price, uint256 _stock) onlyOwner public returns (uint256 _itemId) -``` - -#### update -Update item state for sell. (change item `_price` or add item `_stock`) -``` js -function update(uint256 _item, uint256 _price, uint256 _stock) onlyOwner public -``` - -#### price -Get token address and price from buyer with item index `_item`. -``` js -function price(uint256 _item) public constant returns (address _erc20, uint256 _value) -``` - -#### canBuy -`_who` can Buy `_item`. -``` js -function canBuy(address _who, uint256 _item) public constant returns (bool _canBuy) -``` - -#### isBuyer -`_who` is buyer of `_item`. -``` js -function isBuyer(address _who, uint256 _item) public constant returns (bool _buyer) -``` - -#### info -Set shop information bytes. -``` js -function info(bytes _msgPack) -``` - -#### upVote -Up vote for this shop. -``` js -function upVote() -``` - -#### dnVote -Down vote for this shop. -``` js -function dnVote() -``` - -#### about -Get shop token, up vote and down vote. -``` js -function about() view returns (address _erc20, uint256 _up, uint256 _down) -``` - -#### infoItem -Set item information bytes. -``` js -function infoItem(uint256 _item, bytes _msgPack) -``` - -#### upVoteItem -Up vote for this item. -``` js -function upVoteItem(uint256 _item) -``` - -#### dnVoteItem -Down vote for this item. -``` js -function dnVoteItem(uint256 _item) -``` - -#### aboutItem -Get Item price, up vote and down vote. -``` js -function aboutItem(uint256 _item) view returns (uint256 _price, uint256 _up, uint256 _down) -``` - -### Events -#### Pay -``` js -event Pay(address indexed _buyer, uint256 indexed _item, uint256 indexed _value) -``` - -#### Refund -``` js -event Refund(address indexed _to, uint256 indexed _item, uint256 indexed _value) -``` - -#### Item -``` js -event Item(uint256 indexed _item, uint256 _price) -``` - -#### Info -``` js -event Info(bytes _msgPack) -``` - -#### InfoItem -``` js -event InfoItem(uint256 indexed _item, bytes _msgPack) -``` - -## Implementation -Sample token contract address is [0x393dd70ce2ae7b30501aec94727968c517f90d52](https://ropsten.etherscan.io/address/0x393dd70ce2ae7b30501aec94727968c517f90d52) - -WalletCenter contract address is [0x1fe0862a4a8287d6c23904d61f02507b5044ea31](https://ropsten.etherscan.io/address/0x1fe0862a4a8287d6c23904d61f02507b5044ea31) - -WalletCenter create shop contract address is [0x59117730D02Ca3796121b7975796d479A5Fe54B0](https://ropsten.etherscan.io/address/0x59117730D02Ca3796121b7975796d479A5Fe54B0) - -WalletCenter create wallet contract address is [0x39da7111844df424e1d0a0226183533dd07bc5c6](https://ropsten.etherscan.io/address/0x39da7111844df424e1d0a0226183533dd07bc5c6) - - -## Appendix -``` js -pragma solidity ^0.4.24; - -contract ERC20Interface { - function totalSupply() public constant returns (uint); - function balanceOf(address tokenOwner) public constant returns (uint balance); - function allowance(address tokenOwner, address spender) public constant returns (uint remaining); - function transfer(address to, uint tokens) public returns (bool success); - function approve(address spender, uint tokens) public returns (bool success); - function transferFrom(address from, address to, uint tokens) public returns (bool success); - - event Transfer(address indexed from, address indexed to, uint tokens); - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); -} - -contract SafeMath { - function safeAdd(uint a, uint b) public pure returns (uint c) { - c = a + b; - require(c >= a); - } - function safeSub(uint a, uint b) public pure returns (uint c) { - require(b <= a); - c = a - b; - } - function safeMul(uint a, uint b) public pure returns (uint c) { - c = a * b; - require(a == 0 || c / a == b); - } - function safeDiv(uint a, uint b) public pure returns (uint c) { - require(b > 0); - c = a / b; - } -} - -contract _Base { - address internal owner; - address internal walletCenter; - - modifier onlyOwner { - require(owner == msg.sender); - _; - } - modifier onlyWallet(address _addr) { - require(WalletCenter(walletCenter).isWallet(_addr)); - _; - } - modifier onlyShop(address _addr) { - require(WalletCenter(walletCenter).isShop(_addr)); - _; - } - - function balanceOf(address _erc20) public constant returns (uint256 balance) { - if(_erc20==address(0)) - return address(this).balance; - return ERC20Interface(_erc20).balanceOf(this); - } - - function transfer(address _to, address _erc20, uint256 _value) internal returns (bool success) { - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - _to.transfer(_value); - else - ERC20Interface(_erc20).approve(_to,_value); - return true; - } - - function withdrawal(address _erc20, uint256 _value) public returns (bool success); - - event Pay(address indexed _who, uint256 indexed _item, uint256 indexed _value); - event Refund(address indexed _who, uint256 indexed _item, uint256 indexed _value); - event Prize(address indexed _who, uint256 indexed _item, uint256 indexed _value); -} - -contract _Wallet is _Base { - constructor(address _who) public { - owner = _who; - walletCenter = msg.sender; - } - - function pay(address _shop, uint256 _item) private { - require(_Shop(_shop).canBuy(this,_item)); - - address _erc20; - uint256 _value; - (_erc20,_value) = _Shop(_shop).price(_item); - - transfer(_shop,_erc20,_value); - _Shop(_shop).pay(_item); - emit Pay(_shop,_item,_value); - } - - function paySafe(address _shop, uint256 _item) onlyOwner onlyShop(_shop) public payable returns (bool success) { - pay(_shop,_item); - return true; - } - function payUnsafe(address _shop, uint256 _item) onlyOwner public payable returns (bool success) { - pay(_shop,_item); - return true; - } - function payCancel(address _shop, uint256 _item) onlyOwner public returns (bool success) { - _Shop(_shop).payCancel(_item); - return true; - } - - function refund(address _erc20, uint256 _item, uint256 _value) public payable returns (bool success) { - require((_erc20==address(0)?msg.value:ERC20Interface(_erc20).allowance(msg.sender,this))==_value); - if(_erc20!=address(0)) - ERC20Interface(_erc20).transferFrom(msg.sender,this,_value); - emit Refund(msg.sender,_item,_value); - return true; - } - function prize(address _erc20, uint256 _item, uint256 _value) public payable returns (bool success) { - require((_erc20==address(0)?msg.value:ERC20Interface(_erc20).allowance(msg.sender,this))==_value); - if(_erc20!=address(0)) - ERC20Interface(_erc20).transferFrom(msg.sender,this,_value); - emit Prize(msg.sender,_item,_value); - return true; - } - - function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) { - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - owner.transfer(_value); - else - ERC20Interface(_erc20).transfer(owner,_value); - return true; - } -} - -contract _Shop is _Base, SafeMath{ - address erc20; - constructor(address _who, address _erc20) public { - owner = _who; - walletCenter = msg.sender; - erc20 = _erc20; - } - - struct item { - uint8 category; // 0 = disable, 1 = non Stock, non Expire, 2 = can Expire (after 1 week), 3 = stackable - uint256 price; - uint256 stockCount; - - mapping(address=>uint256) customer; - } - - uint index; - mapping(uint256=>item) items; - - function pay(uint256 _item) onlyWallet(msg.sender) public payable returns (bool success) { - require(canBuy(msg.sender, _item)); - require((erc20==address(0)?msg.value:ERC20Interface(erc20).allowance(msg.sender,this))==items[_item].price); - - if(erc20!=address(0)) - ERC20Interface(erc20).transferFrom(msg.sender,this,items[_item].price); - - if(items[_item].category==1 || items[_item].category==2 && now > safeAdd(items[_item].customer[msg.sender], 1 weeks)) - items[_item].customer[msg.sender] = now; - else if(items[_item].category==2 && now < safeAdd(items[_item].customer[msg.sender], 1 weeks) ) - items[_item].customer[msg.sender] = safeAdd(items[_item].customer[msg.sender], 1 weeks); - else if(items[_item].category==3) { - items[_item].customer[msg.sender] = safeAdd(items[_item].customer[msg.sender],1); - items[_item].stockCount = safeSub(items[_item].stockCount,1); - } - - emit Pay(msg.sender,_item,items[_item].customer[msg.sender]); - return true; - } - - function payCancel(uint256 _item) onlyWallet(msg.sender) public returns (bool success) { - require (items[_item].category==2&&safeAdd(items[_item].customer[msg.sender],2 weeks)>now&&balanceOf(erc20)>=items[_item].price); - - items[_item].customer[msg.sender] = safeSub(items[_item].customer[msg.sender],1 weeks); - transfer(msg.sender, erc20, items[_item].price); - _Wallet(msg.sender).refund(erc20,_item,items[_item].price); - emit Refund(msg.sender,_item,items[_item].price); - - return true; - } - function refund(address _to, uint256 _item) onlyWallet(_to) onlyOwner public payable returns (bool success) { - require(isBuyer(_to,_item)&&items[_item].category>0&&(items[_item].customer[_to]>0||(items[_item].category==2&&safeAdd(items[_item].customer[_to],2 weeks)>now))); - require((erc20==address(0)?address(this).balance:ERC20Interface(erc20).balanceOf(this))>=items[_item].price); - - if(items[_item].category==1) - items[_item].customer[_to] = 0; - else if(items[_item].category==2) - items[_item].customer[_to] = safeSub(items[_item].customer[_to],1 weeks); - else - items[_item].customer[_to] = safeSub(items[_item].customer[_to],1); - - transfer(_to, erc20, items[_item].price); - _Wallet(_to).refund(erc20,_item,items[_item].price); - emit Refund(_to,_item,items[_item].price); - - return true; - } - - event Item(uint256 indexed _item, uint256 _price); - function resister(uint8 _category, uint256 _price, uint256 _stock) onlyOwner public returns (uint256 _itemId) { - require(_category>0&&_category<4); - require(_price>0); - items[index] = item(_category,_price,_stock); - index = safeAdd(index,1); - emit Item(index,_price); - return safeSub(index,1); - } - function update(uint256 _item, uint256 _price, uint256 _stock) onlyOwner public { - require(items[_item].category>0); - require(_price>0); - uint256 temp = items[_item].price; - items[_item].price = _price; - items[_item].stockCount = safeAdd(items[_item].stockCount,_stock); - - if(temp!=items[_item].price) - emit Item(index,items[_item].price); - } - - function price(uint256 _item) public constant returns (address _erc20, uint256 _value) { - return (erc20,items[_item].price); - } - - function canBuy(address _who, uint256 _item) public constant returns (bool _canBuy) { - return (items[_item].category>0) && - !(items[_item].category==1&&items[_item].customer[_who]>0) && - (items[_item].stockCount>0); - } - - function isBuyer(address _who, uint256 _item) public constant returns (bool _buyer) { - return (items[_item].category==1&&items[_item].customer[_who]>0)||(items[_item].category==2&&safeAdd(items[_item].customer[_who],1 weeks)>now)||(items[_item].category==3&&items[_item].customer[_who]>0); - } - - uint lastWithdrawal; - function withdrawal(address _erc20, uint256 _value) onlyOwner public returns (bool success) { - require(safeAdd(lastWithdrawal,1 weeks)<=now); - require((_erc20==address(0)?address(this).balance:ERC20Interface(_erc20).balanceOf(this))>=_value); - if(_erc20==address(0)) - owner.transfer(_value); - else - ERC20Interface(_erc20).transfer(owner,_value); - lastWithdrawal = now; - return true; - } -} - -contract WalletCenter { - mapping(address=>bool) public wallet; - event Wallet(address indexed _owner, address indexed _wallet); - function createWallet() public returns (address _wallet) { - _wallet = new _Wallet(msg.sender); - wallet[_wallet] = true; - emit Wallet(msg.sender,_wallet); - return _wallet; - } - function isWallet(address _wallet) public constant returns (bool) { - return wallet[_wallet]; - } - mapping(address=>bool) public shop; - event Shop(address indexed _owner, address indexed _shop, address indexed _erc20); - function createShop(address _erc20) public returns (address _shop) { - _shop = new _Shop(msg.sender,_erc20); - shop[_shop] = true; - emit Shop(msg.sender,_shop,_erc20); - return _shop; - } - function isShop(address _shop) public constant returns (bool) { - return shop[_shop]; - } -} -``` -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1175.md diff --git a/EIPS/eip-1178.md b/EIPS/eip-1178.md index 06a740ce42c3c7..ce8fc9b21156bc 100644 --- a/EIPS/eip-1178.md +++ b/EIPS/eip-1178.md @@ -1,156 +1,7 @@ --- eip: 1178 -title: Multi-class Token Standard -author: Albert Chon -discussions-to: https://github.com/ethereum/EIPs/issues/1179 -status: Stagnant -type: Standards Track category: ERC -created: 2018-06-22 +status: Moved --- - -## Simple Summary -A standard interface for multi-class fungible tokens. -## Abstract -This standard allows for the implementation of a standard API for multi-class fungible tokens (henceforth referred to as "MCFTs") within smart contracts. This standard provides basic functionality to track and transfer ownership of MCFTs. -## Motivation -Currently, there is no standard to support tokens that have multiple classes. In the real world, there are many situations in which defining distinct classes of the same token would be fitting (e.g. distinguishing between preferred/common/restricted shares of a company). Yet, such nuance cannot be supported in today's token standards. An ERC-20 token contract defines tokens that are all of one class while an ERC-721 token contract creates a class (defined by token_id) for each individual token. The ERC-1178 token standard proposes a new standard for creating multiple classes of tokens within one token contract. - -> Aside: In theory, while it is possible to implement tokens with classes using the properties of token structs in ERC-721 tokens, gas costs of implementing this in practice are prohibitive for any non-trivial application. - -## Specification -### ERC-20 Compatibility (partial) -**name** - -```solidity -function name() constant returns (string name) -``` - -*OPTIONAL - It is recommended that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns the name of the aggregate collection of MCFTs managed by this contract. - e.g. `"My Company Tokens"`. - -**class name** - -```solidity -function className(uint256 classId) constant returns (string name) -``` - -*OPTIONAL - It is recommended that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns the name of the class of MCFT managed by this contract. - e.g. `"My Company Preferred Shares Token"`. - -**symbol** -```solidity -function symbol() constant returns (string symbol) -``` - -*OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.* - -Returns a short string symbol referencing the entire collection of MCFT managed in this contract. e.g. "MUL". This symbol SHOULD be short (3-8 characters is recommended), with no whitespace characters or new-lines and SHOULD be limited to the uppercase latin alphabet (i.e. the 26 letters used in English). - -**totalSupply** -```solidity -function totalSupply() constant returns (uint256 totalSupply) -``` -Returns the total number of all MCFTs currently tracked by this contract. - -**individualSupply** -```solidity -function individualSupply(uint256 _classId) constant returns (uint256 individualSupply) -``` -Returns the total number of MCFTs of class `_classId` currently tracked by this contract. - -**balanceOf** -```solidity -function balanceOf(address _owner, uint256 _classId) constant returns (uint256 balance) -``` - -Returns the number of MCFTs of token class `_classId` assigned to address `_owner`. - -**classesOwned** -```solidity -function classesOwned(address _owner) constant returns (uint256[] classes) -``` - -Returns an array of `_classId`'s of MCFTs that address `_owner` owns in the contract. -> NOTE: returning an array is supported by `pragma experimental ABIEncoderV2` - -## Basic Ownership - -**approve** -```solidity -function approve(address _to, uint256 _classId, uint256 quantity) -``` -Grants approval for address `_to` to take possession `quantity` amount of the MCFT with ID `_classId`. This method MUST `throw` if `balanceOf(msg.sender, _classId) < quantity`, or if `_classId` does not represent an MCFT class currently tracked by this contract, or if `msg.sender == _to`. - -Only one address can "have approval" at any given time for a given address and `_classId`. Calling `approve` with a new address and `_classId` revokes approval for the previous address and `_classId`. Calling this method with 0 as the `_to` argument clears approval for any address and the specified `_classId`. - -Successful completion of this method MUST emit an `Approval` event (defined below) unless the caller is attempting to clear approval when there is no pending approval. In particular, an Approval event MUST be fired if the `_to` address is zero and there is some outstanding approval. Additionally, an Approval event MUST be fired if `_to` is already the currently approved address and this call otherwise has no effect. (i.e. An `approve()` call that "reaffirms" an existing approval MUST fire an event.) - - - -**transfer** -```solidity -function transfer(address _to, uint256 _classId, uint256 quantity) -``` -Assigns the ownership of `quantity` MCFT's with ID `_classId` to `_to` if and only if `quantity == balanceOf(msg.sender, _classId)`. A successful transfer MUST fire the `Transfer` event (defined below). - -This method MUST transfer ownership to `_to` or `throw`, no other outcomes can be possible. Reasons for failure include (but are not limited to): - -* `msg.sender` is not the owner of `quantity` amount of tokens of `_classId`'s. -* `_classId` does not represent an MCFT class currently tracked by this contract - -A conforming contract MUST allow the current owner to "transfer" a token to themselves, as a way of affirming ownership in the event stream. (i.e. it is valid for `_to == msg.sender` if `balanceOf(msg.sender, _classId) >= balance`.) This "no-op transfer" MUST be considered a successful transfer, and therefore MUST fire a `Transfer` event (with the same address for `_from` and `_to`). - -## Advanced Ownership and Exchange -```solidity -function approveForToken(uint256 classIdHeld, uint256 quantityHeld, uint256 classIdWanted, uint256 quantityWanted) -``` -Allows holder of one token to allow another individual (or the smart contract itself) to approve the exchange of their tokens of one class for tokens of another class at their specified exchange rate (see sample implementation for more details). This is equivalent to posting a bid in a marketplace. - -```solidity -function exchange(address to, uint256 classIdPosted, uint256 quantityPosted, uint256 classIdWanted, uint256 quantityWanted) -``` -Allows an individual to fill an existing bid (see above function) and complete the exchange of their tokens of one class for another. In the sample implementation, this function call should fail unless the callee has already approved the contract to transfer their tokens. Of course, it is possible to create an implementation where calling this function implicitly assumes approval and the transfer is completed in one step. - -```solidity -transferFrom(address from, address to, uint256 classId) -``` -Allows a third party to initiate a transfer of tokens from `from` to `to` assuming the approvals have been granted. - -## Events -**Transfer** - -This event MUST trigger when MCFT ownership is transferred via any mechanism. - -Additionally, the creation of new MCFTs MUST trigger a Transfer event for each newly created MCFTs, with a `_from` address of 0 and a `_to` address matching the owner of the new MCFT (possibly the smart contract itself). The deletion (or burn) of any MCFT MUST trigger a Transfer event with a `_to` address of 0 and a `_from` address of the owner of the MCFT (now former owner!). - -NOTE: A Transfer event with `_from == _to` is valid. See the `transfer()` documentation for details. - -```solidity -event Transfer(address indexed _from, address indexed _to, uint256 _classId) -``` - -**Approval** -This event MUST trigger on any successful call to `approve(_to, _classId, quantity)` (unless the caller is attempting to clear approval when there is no pending approval). - -```solidity -event Approval(address indexed _owner, address indexed _approved, uint256 _classId) -``` -## Rationale -### Current Limitations -The design of this project was motivated when I tried to create different classes of fungible ERC-721 tokens (an oxymoron) but ran into gas limits from having to create each tokens individually and maintain them in an efficient data structure for access. Using the maximum gas amount one can send with a transaction on Metamask (a popular web wallet), I was only able to create around 46 ERC-721 tokens before exhausting all gas. This experience motivated the creation of the multi-class fungible token standard. - - -## Backwards Compatibility -Adoption of the MCFT standard proposal would not pose backwards compatibility issues as it defines a new standard for token creation. This standard follows the semantics of ERC-721 as closely as possible, but can't be entirely compatible with it due to the fundamental differences between multi-class fungible and non-fungible tokens. For example, the `ownerOf`, `takeOwnership`, and `tokenOfOwnerByIndex` methods in the ERC-721 token standard cannot be implemented in this standard. Furthermore, the function arguments to `balanceOf`, `approve`, and `transfer` differ as well. - -## Implementation -A sample implementation can be found [here](https://github.com/achon22/ERC-1178/blob/master/erc1178-sample.sol) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1178.md diff --git a/EIPS/eip-1185.md b/EIPS/eip-1185.md index eab7b2bd54ff64..eecb70b6494360 100644 --- a/EIPS/eip-1185.md +++ b/EIPS/eip-1185.md @@ -1,80 +1,7 @@ --- eip: 1185 -title: Storage of DNS Records in ENS -author: Jim McDonald (@mcdee) -status: Stagnant -type: Standards Track category: ERC -created: 2018-06-26 -requires: 137 -discussions-to: https://ethereum-magicians.org/t/eip1185-dns-resolver-profile-for-ens/1589 +status: Moved --- - -## Abstract -This EIP defines a resolver profile for ENS that provides features for storage and lookup of DNS records. This allows ENS to be used as a store of authoritative DNS information. -## Motivation -ENS is a highly desirable store for DNS information. It provides the distributed authority of DNS without conflating ownership and authoritative serving of information. With ENS, the owner of a domain has full control over their own DNS records. Also, ENS has the ability (through smart contracts) for a domain's subdomains to be irrevocably assigned to another entity. - -## Specification - -The resolver profile to support DNS on ENS follows the resolver specification as defined in #137. - -Traditionally, DNS is a zone-based system in that all of the records for a zone are kept together in the same file. This has the benefit of simplicity and atomicity of zone updates, but when transposed to ENS can result in significant gas costs for simple changes. As a result, the resolver works on the basis of record sets. A record set is uniquely defined by the tuple (domain, name, resource record type), for example the tuple (example.com, www.example.com, A) defines the record set of A records for the name www.example.com in the domain example.com. A record set can contain 0 or more values, for example if www.example.com has A records 1.2.3.4 and 5.6.7.8 then the aforementioned tuple will have two values. - -The choice to work at the level of record sets rather than zones means that this specification cannot completely support some features of DNS, such as zone transfers and DNSSEC. It would be possible to build a different resolver profile that works at the zone level, however it would be very expensive to carry out updates and so is not considered further for this EIP. - -The DNS resolver interface consists of two functions to set DNS information and two functions to query DNS information. - -### setDNSRecords(bytes32 node, bytes data) - -`setDNSRecords()` sets, updates or clears 1 or more DNS records for a given node. It has function signature `0x0af179d7`. - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - data: 1 or more DNS records in DNS wire format. Any record that is supplied without a value will be cleared. Note that all records in the same RRset should be contiguous within the data; if not then the later RRsets will overwrite the earlier one(s) - -### clearDNSZone(bytes32 node) - -`clearDNSZone()` removes all DNS records for the domain. It has function signature `0xad5780af`. - -Although it is possible to clear records individually with `setDNSRecords()` as described above this requires the owner to know all of the records that have been set (as the resolver has no methods to iterate over the records for a given domain), and might require multiple transactions. `clearDNSZone()` removes all zone information in a single operation. - -The arguments for the function is as follows: - - node: the namehash of the fully-qualified domain in ENS for which to clear the records. Namehashes are defined in #137 - -### dnsRecords(bytes32 node, bytes32 name, uint16 resource) view returns (bytes) - -`dnsRecords()` obtains the DNS records for a given node, name and resource. It has function signature `0x2461e851`. - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - name: the `keccak256()` hash of the name of the record in DNS wire format. - - resource: the resource record ID. Resource record IDs are defined in https://en.wikipedia.org/wiki/List\_of\_DNS\_record\_types - -The function returns all matching records in DNS wire format. If there are no records present the function will return nothing. - -### hasDNSRecords(bytes32 node, bytes32 name) view returns (bool) - -`hasDNSRecords()` reports if there are any records for the provided name in the domain. It has function signature `0x4cbf6ba4`. - -This function is needed by DNS resolvers when working with wildcard resources as defined in https://tools.ietf.org/html/rfc4592 - -The arguments for the function are as follows: - - node: the namehash of the fully-qualified domain in ENS for which to set the records. Namehashes are defined in #137 - - name: the `keccak256()` hash of the name of the record in DNS wire format. - -The function returns `true` if there are any records for the provided node and name, otherwise `false`. - -## Backwards compatibility -Not applicable. - -## Implementation -The reference implementation of the DNS resolver is at https://github.com/wealdtech/wealdtech-solidity/blob/master/contracts/ens/DNSResolver.sol - -https://github.com/wealdtech/ethereal.git can be used to test the functionality of the resolver with the "dns set", "dns get" and "dns clear" commands. -## Test Cases -Test cases for the DNS resolver are at https://github.com/wealdtech/wealdtech-solidity/blob/master/test/ens/DNSResolver.js - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1185.md diff --git a/EIPS/eip-1191.md b/EIPS/eip-1191.md index 18208804ed19cb..9927c0a32159b5 100644 --- a/EIPS/eip-1191.md +++ b/EIPS/eip-1191.md @@ -1,123 +1,7 @@ --- eip: 1191 -title: Add chain id to mixed-case checksum address encoding -author: Juliano Rizzo (@juli) -status: Last Call -last-call-deadline: 2019-11-18 -type: Standards Track category: ERC -created: 2018-03-18 -requires: 55, 155 -discussions-to: https://github.com/ethereum/EIPs/issues/1121 +status: Moved --- -## Simple Summary -This EIP extends EIP-55 by optionally adding a chain id defined by EIP-155 to the checksum calculation. - -## Abstract -The EIP-55 was created to prevent users from losing funds by sending them to invalid addresses. This EIP extends EIP-55 to protect users from losing funds by sending them to addresses that are valid but that where obtained from a client of another network.For example, if this EIP is implemented, a wallet can alert the user that is trying to send funds to an Ethereum Testnet address from an Ethereum Mainnet wallet. - -## Motivation -The motivation of this proposal is to provide a mechanism to allow software to distinguish addresses from different Ethereum based networks. This proposal is necessary because Ethereum addresses are hashes of public keys and do not include any metadata. By extending the EIP-55 checksum algorithm it is possible to achieve this objective. - -## Specification -Convert the address using the same algorithm defined by EIP-55 but if a registered chain id is provided, add it to the input of the hash function. If the chain id passed to the function belongs to a network that opted for using this checksum variant, prefix the address with the chain id and the `0x` separator before calculating the hash. Then convert the address to hexadecimal, but if the ith digit is a letter (ie. it's one of `abcdef`) print it in uppercase if the 4*ith bit of the calculated hash is 1 otherwise print it in lowercase. - -## Rationale - Benefits: - - By means of a minimal code change on existing libraries, users are protected from losing funds by mixing addresses of different Ethereum based networks. - -## Implementation -```python -#!/usr/bin/python3 -from sha3 import keccak_256 -import random -""" - addr (str): Hexadecimal address, 40 characters long with 2 characters prefix - chainid (int): chain id from EIP-155 """ -def eth_checksum_encode(addr, chainid=1): - adopted_eip1191 = [30, 31] - hash_input = str(chainid) + addr.lower() if chainid in adopted_eip1191 else addr[2:].lower() - hash_output = keccak_256(hash_input.encode('utf8')).hexdigest() - aggregate = zip(addr[2:].lower(),hash_output) - out = addr[:2] + ''.join([c.upper() if int(a,16) >= 8 else c for c,a in aggregate]) - return out -``` - -## Test Cases -```python -eth_mainnet = [ -"0x27b1fdb04752bbc536007a920d24acb045561c26", -"0x3599689E6292b81B2d85451025146515070129Bb", -"0x42712D45473476b98452f434e72461577D686318", -"0x52908400098527886E0F7030069857D2E4169EE7", -"0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", -"0x6549f4939460DE12611948b3f82b88C3C8975323", -"0x66f9664f97F2b50F62D13eA064982f936dE76657", -"0x8617E340B3D01FA5F11F306F4090FD50E238070D", -"0x88021160C5C792225E4E5452585947470010289D", -"0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb", -"0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB", -"0xde709f2102306220921060314715629080e2fb77", -"0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359", -] -rsk_mainnet = [ -"0x27b1FdB04752BBc536007A920D24ACB045561c26", -"0x3599689E6292B81B2D85451025146515070129Bb", -"0x42712D45473476B98452f434E72461577d686318", -"0x52908400098527886E0F7030069857D2E4169ee7", -"0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD", -"0x6549F4939460DE12611948B3F82B88C3C8975323", -"0x66F9664f97f2B50F62d13EA064982F936de76657", -"0x8617E340b3D01Fa5f11f306f4090fd50E238070D", -"0x88021160c5C792225E4E5452585947470010289d", -"0xD1220A0Cf47c7B9BE7a2e6ba89F429762E7B9adB", -"0xDBF03B407c01E7CD3cBea99509D93F8Dddc8C6FB", -"0xDe709F2102306220921060314715629080e2FB77", -"0xFb6916095cA1Df60bb79ce92cE3EA74c37c5d359", -] -rsk_testnet = [ -"0x27B1FdB04752BbC536007a920D24acB045561C26", -"0x3599689e6292b81b2D85451025146515070129Bb", -"0x42712D45473476B98452F434E72461577D686318", -"0x52908400098527886E0F7030069857D2e4169EE7", -"0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd", -"0x6549f4939460dE12611948b3f82b88C3c8975323", -"0x66f9664F97F2b50f62d13eA064982F936DE76657", -"0x8617e340b3D01fa5F11f306F4090Fd50e238070d", -"0x88021160c5C792225E4E5452585947470010289d", -"0xd1220a0CF47c7B9Be7A2E6Ba89f429762E7b9adB", -"0xdbF03B407C01E7cd3cbEa99509D93f8dDDc8C6fB", -"0xDE709F2102306220921060314715629080e2Fb77", -"0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359", -] -test_cases = {30 : rsk_mainnet, 31 : rsk_testnet, 1 : eth_mainnet} - -for chainid, cases in test_cases.items(): - for addr in cases: - assert ( addr == eth_checksum_encode(addr,chainid) ) -``` -## Usage - -### Usage Table - -| Network | Chain id | Supports this EIP | -|-|-|-| -| RSK Mainnet | 30 | Yes | -| RSK Testnet | 31 | Yes | - -### Implementation Table -| Project | EIP Usage | Implementation | -|-|-|-| -| MyCrypto | Yes | [JavaScript](https://github.com/MyCryptoHQ/MyCrypto/blob/develop/common/utils/formatters.ts#L126) | -| MyEtherWallet | Yes | [JavaScript](https://github.com/MyEtherWallet/MyEtherWallet/blob/73c4a24f8f67c655749ac990c5b62efd92a2b11a/src/helpers/addressUtils.js#L22) | -| Ledger | Yes | [C](https://github.com/LedgerHQ/ledger-app-eth/blob/master/src_common/ethUtils.c#L203) | -| Trezor | Yes | [Python](https://github.com/trezor/trezor-core/blob/270bf732121d004a4cd1ab129adaccf7346ff1db/src/apps/ethereum/get_address.py#L32) and [C](https://github.com/trezor/trezor-crypto/blob/4153e662b60a0d83c1be15150f18483a37e9092c/address.c#L62) | -| Web3.js | Yes | [JavaScript](https://github.com/ethereum/web3.js/blob/aaf26c8806bc9fb60cf6dcb6658104963c6c7fc7/packages/web3-utils/src/Utils.js#L140) | -| EthereumJS-util | Yes | [JavaScript](https://github.com/ethereumjs/ethereumjs-util/pull/204/commits/cdf0b3c996b05ac5b1f758f17ea9f9ed1847c1eb) | -| ENS address-encoder | Yes | [TypeScript](https://github.com/ensdomains/address-encoder/commit/5bf53b13fa014646ea28c9e5f937361dc9b40590) | - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1191.md diff --git a/EIPS/eip-1193.md b/EIPS/eip-1193.md index 01cabe1365fb83..ea5377a8956e5d 100644 --- a/EIPS/eip-1193.md +++ b/EIPS/eip-1193.md @@ -1,7 +1,7 @@ --- eip: 1193 title: Ethereum Provider JavaScript API -author: Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Victor Maia (@MaiaVictor), Marc Garreau (@marcgarreau), Erik Marks (@rekmarks) +author: Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Victor Maia (@MaiaVictor), Marc Garreau (@wolovim), Erik Marks (@rekmarks) discussions-to: https://github.com/ethereum/EIPs/issues/2319 status: Final type: Standards Track diff --git a/EIPS/eip-1202.md b/EIPS/eip-1202.md index 9ab0f843a315da..2868fbb772b93b 100644 --- a/EIPS/eip-1202.md +++ b/EIPS/eip-1202.md @@ -1,160 +1,7 @@ --- eip: 1202 -title: Voting Interface -description: A general interface for voting on-chain -author: Zainan Victor Zhou (@xinbenlv), Evan (@evbots), Yin Xu (@yingogobot) -discussions-to: https://ethereum-magicians.org/t/eip-1202-voting-interface/11484 -status: Draft -type: Standards Track category: ERC -created: 2018-07-08 +status: Moved --- -## Abstract - -This EIP is an API for implementing voting with smart contract. This standard provides functionalities to voting as well as to view the vote result and set voting status. - -## Motivation - -Voting is one of the earliest example of EVM programming, and also a key to DAO/organizational governance process. We foresee many DAOs will ultimately need to leverage voting as one of the important part of their governance. By creating a voting standard for smart contract / token, we can have the following benefits - -### Benefits of having a standard - -1. Allow general UI and applications to be built on top of a standardized voting to allow more general user to participate, and encourage more DApp and DAO to think about their governance -2. Allow delegate voting / smart contract voting, automatic voting -3. Allow voting results to be recorded on-chain, in a standard way, and allow DAOs and DApps to honor the voting result programmatically. -4. Allow the compatibility with token standard such as [EIP-20](./eip-20.md) or other new standards([EIP-777](./eip-777.md)) and item standard such as [EIP-721](./eip-721.md) -5. Create massive potential for interoperability within Ethereum echo systems and other system. -6. Allow setting voting deadline, allow determine on single or multiple options. Allow requiring voting orders. (trade-off is interface complexity, we might need [EIP-20](./eip-20.md) approach and later a [EIP-777](./eip-777.md) for advanced voting) -7. Recording the voting with weights with token amount. -8. Possibly allow trust-worthy privacy-safe voting and anonymous voting (with either voter address being un-associated with the vote they cast, given a list of randomized/obfuscated voting options). - -9. Possibly allow result in reward by voting participation or voting result. - -### Non-Goal / Out of Scope - -1. **Delegation**: We intentionally leave delegation out of scope. A separate EIP could be proposed to address this particular use case. -2. **Eligibility or Weights**: Some of the implementing want to have weights or eligibility to vote to be configurable. Such as OpenZeppelin's implementation of GovernorBravo uses snapshot. Aslo weights calculation such as quadratic voting is not within the scope of this EIP. This EIP is intend to be flexible for -any current and new voting weights calculation. -3. **Proposal**: We intentionally leave Proposal out of scope. Proposals are going to be identified by `proposalId` but what information of the proposal includes, -whether they are on-chain or off-chain and whether they are exeutable, is leaved out from this proposal. A separate EIP could be proposed to address this particular use case. See one of such proposals [EIP-5247](./eip-5247.md) -4. **Signature Aggregations / Endorsement**: When implementing contracts want to allow user to submit their vote or approval of vote offline and have some other -account to generate the transaction, the signature aggregations or endorsements are not in scope of this EIP. A separate EIP could be proposed to address this particular use case. See one of such proposals here [EIP-5453](./eip-5453.md). - -### Use-cases - -1. Determine on issuing new token, issuing more token or issuing sub-token -2. Determine on creating new item under [EIP-721](./eip-721.md) -3. Determine on election on certain person or smart contract to be delegated leader for project or subproject -4. Determine on auditing result ownership allowing migration of smart contract proxy address - -## Specification - -1. Compliant contracts MUST implement the `IERC1202Core` below - -```solidity -interface IERC1202Core { - event VoteCast( - address indexed voter, - uint256 indexed proposalId, - uint8 support, - uint256 weight, - string reason, - bytes extraParams - ); - - function castVote( - uint256 proposalId, - uint8 support, - uint256 weight, - string calldata reasonUri, - bytes calldata extraParams - ) external payable returns; - - function castVoteFrom( - address from, - uint256 proposalId, - uint8 support, - uint256 weight, - string calldata reasonUri, - bytes calldata extraParams - ) external payable returns; - - function execute(uint256 proposalId, bytes memory extraParams) payable external; -} -``` - -2. Compliant contracts MAY implement the `IERC1202MultiVote` Interface. If the intention is for multi-options to be supported, e.g. for ranked-choices -or variant weights voting, Compliant contracts MUST implement `IERC1202MultiVote` Interface. - -```solidity -interface IERC1202MultiVote { - event MultiVoteCast( - address indexed voter, - uint256 indexed proposalId, - uint8[] support, - uint256[] weight, - string reason, - bytes extraParams - ); - - function castMultiVote( - uint256 proposalId, - uint8[] support, - uint256[] weight, - string calldata reasonUri, - bytes calldata extraParams - ) external payable; -} -``` - -### Getting Info: Voting Period, Eligibility, Weight - -```solidity -interface IERC1202Info { - function votingPeriodFor(uint256 proposalId) external view returns (uint256 startPointOfTime, uint256 endPointOfTime); - function eligibleVotingWeight(uint256 proposalId, address voter) external view returns (uint256); -} -``` - -## Rationale - -We made the following design decisions and here are the rationales. - -### Granularity and Anonymity - -We created a `view` function `ballotOf` primarily making it easier for people to check the vote from certain address. This has the following assumptions: - -- It's possible to check someone's vote directly given an address. If implementor don't want to make it so easily, they can simply reject all calls to this function. We want to make sure that we support both anonymous voting an non-anonymous voting. However since all calls to a smart contract is logged in block history, there is really no secrecy unless done with cryptography tricks. I am not cryptography-savvy enough to comment on the possibility. Please see "Second Feedback Questions 2018" for related topic. - -- It's assumes for each individual address, they can only vote for one decision. They can distribute their available voting power into more granular level. If implementor wants allow this, they ask the user to create another wallet address and grant the new address certain power. For example, a token based voting where voting weight is determined by the amount of token held by a voter, a voter who wants to distribute its voting power in two different option(option set) can transfer some of the tokens to the new account and cast the votes from both accounts. - -### Weights - -We assume there are `weight` of votes and can be checked by calling `eligibleVotingWeight(proposalId, address voter)`, and the weight distribution is either internally determined or determined by constructor. - -## Backwards Compatibility - -1. The `support` options are chosen to be `uint8` for the purpose to be backward compatible for GovernorBravo. It can be increased in the future - -## Security Considerations - -We expect the voting standard to be used in connection with other contracts such as token distributions, conducting actions in consensus or on behalf of an entity, multi-signature wallets, etc. - -The major security consideration is to ensure only using the standard interface for performing downstream actions or receiving upstream input (vote casting). We expect future audit tool to be based on standard interfaces. - -It's also important to note as discussed in this standard that for the sake of simplicity, this EIP is kept in the very basic form. It can be extended to support many different implementation variations. Such variations might contain different assumptions of the behavior and interpretation of actions. One example would be: What does it mean if someone votes multiple times through `vote`? - -- Would that mean the voter is increasing their weight, or -- vote multiple options in the meanwhile, or -- Does the latter vote override the previous vote? - -Because of the flexible nature of voting, we expect many subsequent standards need to be created as an extension of this EIP. We suggest any extension or implementations of this standard be thoroughly audited before included in large scale or high asset volume applications. - -The third consideration is non-triviality. Some voting applications assume **_anonymity_**, **_randomness_**, **_time-based deadline_**, **_ordering_**, etc, these requirements in Ethereum are known to be non-trivial to achieve. We suggest any applications or organizations rely on audited and time-proven shared libraries when these requirements need to be enforced in their applications. - -The fourth consideration is potential abuse. When voting is standardized and put on contract, it is possible to write another contract that rewards a voter to vote in a certain way. It creates potential issues of bribery and conflict of interest abuse that is previously hard to implement. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1202.md diff --git a/EIPS/eip-1203.md b/EIPS/eip-1203.md index dc971789dd83a7..5d4e6d6f3a9d51 100644 --- a/EIPS/eip-1203.md +++ b/EIPS/eip-1203.md @@ -1,230 +1,7 @@ --- eip: 1203 -title: ERC-1203 Multi-Class Token Standard (ERC-20 Extension) -author: Jeff Huang , Min Zu -discussions-to: https://github.com/ethereum/EIPs/issues/1203 -status: Stagnant -type: Standards Track category: ERC -created: 2018-07-01 +status: Moved --- -## Simple Summary - -A standard interface for multi-class tokens (MCTs). - -## Abstract - -The following standard allows for the implementation of a standard API for MCTs within smart contracts. This standard provides basic functionality to track, transfer, and convert MCTs. - -## Motivation - -This standard is heavily inspired by ERC-20 Token Standard and ERC-721 Non-Fungible Token Standard. However, whereas these standards are chiefly concerned with representation of items/value in a single class, fungible or note, this proposed standard focus on that of a more complexed, multi-class system. It is fair to think of MCTs as a hybrid of fungible tokens (FT) and non-fungible tokens (NFTs), that is tokens are fungible within the same class but non-fungible with that from a different class. And conversions between classes may be optionally supported. - -MCTs are useful in representing various structures with heterogeneous components, such as: - -- **Abstract Concepts:** A company may have different classes of stocks (e.g. senior preferred, junior preferred, class A common, class B common) that together make up its outstanding equities. A shareholder's position of such company composites of zero or more shares in each class. - -- **Virtual Items:** A sandbox computer game may have many types of resources (e.g. rock, wood, berries, cows, meat, knife, etc.) that together make up that virtual world. A player's inventory has any combination and quantity of these resources - -- **Physical Items:** A supermarket may have many SKUs it has available for purchase (e.g. eggs, milk, beef jerky, beer, etc.). Things get added or removed from a shopper's cart as it moves down the aisle. - -It's sometimes possible, especially with regard to abstract concepts or virtual items, to convert from one class to another, at a specified conversion ratio. When it comes to physical items, such conversion essentially is the implementation of bartering. Though it might generally be easier to introduce a common intermediary class, i.e. money. - -## Specification - -```solidity -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address _owner) public view returns (uint256); - function transfer(address _to, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} - -contract ERC1203 is ERC20 { - function totalSupply(uint256 _class) public view returns (uint256); - function balanceOf(address _owner, uint256 _class) public view returns (uint256); - function transfer(address _to, uint256 _class, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _class, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender, uint256 _class) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _class, uint256 _value) public returns (bool); - - function fullyDilutedTotalSupply() public view returns (uint256); - function fullyDilutedBalanceOf(address _owner) public view returns (uint256); - function fullyDilutedAllowance(address _owner, address _spender) public view returns (uint256); - function convert(uint256 _fromClass, uint256 _toClass, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _class, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _class, uint256 _value); - event Convert(uint256 indexed _fromClass, uint256 indexed _toClass, uint256 _value); -} -``` - -### ERC-20 Methods and Events (fully compatible) - -Please see [ERC-20 Token Standard](./eip-20.md) for detailed specifications. Do note that these methods and events only work on the "default" class of an MCT. - -```solidity - function totalSupply() public view returns (uint256); - function balanceOf(address _owner) public view returns (uint256); - function transfer(address _to, uint256 _value) public returns (bool); - function approve(address _spender, uint256 _value) public returns (bool); - function allowance(address _owner, address _spender) public view returns (uint256); - function transferFrom(address _from, address _to, uint256 _value) public returns (bool); - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -``` - -### Tracking and Transferring - -**totalSupply** - -Returns the total number of tokens in the specified `_class` - -```solidity - function totalSupply(uint256 _class) public view returns (uint256); -``` - -**balanceOf** - -Returns the number of tokens of a specified `_class` that the `_owner` has - -```solidity - function balanceOf(address _owner, uint256 _class) public view returns (uint256); -``` - -**transfer** - -Transfer `_value` tokens of `_class` to address specified by `_to`, return `true` if successful - -```solidity - function transfer(address _to, uint256 _class, uint256 _value) public returns (bool); -``` - -**approve** - -Grant `_spender` the right to transfer `_value` tokens of `_class`, return `true` if successful - -```solidity - function approve(address _spender, uint256 _class, uint256 _value) public returns (bool); -``` - -**allowance** - -Return the number of tokens of `_class` that `_spender` is authorized to transfer on the behalf of `_owner` - -```solidity - function allowance(address _owner, address _spender, uint256 _class) public view returns (uint256); -``` - -**transferFrom** - -Transfer `_value` tokens of `_class` from address specified by `_from` to address specified by `_to` as previously approved, return `true` if successful - -```solidity - function transferFrom(address _from, address _to, uint256 _class, uint256 _value) public returns (bool); -``` - -**Transfer** - -Triggered when tokens are transferred or created, including zero value transfers - -```solidity - event Transfer(address indexed _from, address indexed _to, uint256 _class, uint256 _value); -``` - -**Approval** - -Triggered on successful `approve` - -```solidity - event Approval(address indexed _owner, address indexed _spender, uint256 _class, uint256 _value); -``` - -### Conversion and Dilution - -**fullyDilutedTotalSupply** - -Return the total token supply as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedTotalSupply() public view returns (uint256); -``` - -**fullyDilutedBalanceOf** - -Return the total token owned by `_owner` as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedBalanceOf(address _owner) public view returns (uint256); -``` - -**fullyDilutedAllowance** - -Return the total token `_spender` is authorized to transfer on behalf of `_owner` as if all converted to the lowest common denominator class - -```solidity - function fullyDilutedAllowance(address _owner, address _spender) public view returns (uint256); -``` - -**convert** - -Convert `_value` of `_fromClass` to `_toClass`, return `true` if successful - -```solidity - function convert(uint256 _fromClass, uint256 _toClass, uint256 _value) public returns (bool); -``` - -**Conversion** - -Triggered on successful `convert` - -```solidity - event Conversion(uint256 indexed _fromClass, uint256 indexed _toClass, uint256 _value); -``` - -## Rationale -This standard purposely extends ERC-20 Token Standard so that new MCTs following or existing ERC-20 tokens extending this standard are fully compatible with current wallets and exchanges. In addition, new methods and events are kept as closely to ERC-20 conventions as possible for ease of adoption. - -We have considered alternative implementations to support the multi-class structure, as discussed below, and we found current token standards incapable or inefficient in deal with such structures. - -**Using multiple ERC-20 tokens** - -It is certainly possible to create an ERC-20 token for each class, and a separate contract to coordinate potential conversions, but the short coming in this approach is clearly evident. The rationale behind this standard is to have a single contract to manage multiple classes of tokens. - -**Shoehorning ERC-721 token** - -Treating each token as unique, the non-fungible token standard offers maximum representational flexibility arguably at the expense of convenience. The main challenge of using ERC-721 to represent multi-class token is that separate logic is required to keep track of which tokens belongs to which class, a hacky and unnecessary endeavor. - -**Using ERC-1178 token** - -We came across ERC-1178 as we were putting final touches on our own proposal. The two ERCs look very similar on the surface but we believe there're a few key advantages this one has over ERC-1178. - -- ERC-1178 offers no backward compatibility whereas this proposal is an extension of ERC-20 and therefore fully compatible with all existing wallets and exchanges -- By the same token, existing ERC-20 contracts can extend themselves to adopt this standard and support additional classes without affecting their current behaviors -- This proposal introduces the concept of cross class conversion and dilution, making each token class integral part of a whole system rather than many silos - -## Backwards Compatibility -This EIP is fully compatible with the mandatory methods of ERC20 Token Standard so long as the implementation includes a "lowest common denominator" class, which may be class B common/gold coin/money in the abstract/virtual/physical examples above respectively. Where it is not possible to implement such class, then the implementation should specify a default class for tracking or transferring unless otherwise specified, e.g. US dollar is transferred unless other currency is explicitly specified. - -We find it contrived to require the optional methods of ERC20 Token Standard, `name()`, `symbol()`, and `decimals()`, but developers are certainly free to implement these as they wish. - -## Test Cases -The repository at [jeffishjeff/ERC-1203](https://github.com/jeffishjeff/ERC-1203) contains the [sample test cases](https://github.com/jeffishjeff/ERC-1203/blob/master/token.test.js). - -## Implementation -The repository at [jeffishjeff/ERC-1203](https://github.com/jeffishjeff/ERC-1203) contains the [sample implementation](https://github.com/jeffishjeff/ERC-1203/blob/master/token.sol). - -## References -- ERC-20 Token Standard. ./eip-20.md -- ERC-721 Non-Fungible Token Standard. ./eip-721.md -- ERC-1178 Multi-class Token Standard. ./eip-1178.md - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1203.md diff --git a/EIPS/eip-1207.md b/EIPS/eip-1207.md index 9b9fb0ca34b92c..867e74672a09f4 100644 --- a/EIPS/eip-1207.md +++ b/EIPS/eip-1207.md @@ -1,169 +1,7 @@ --- eip: 1207 -title: DAuth Access Delegation Standard -author: Xiaoyu Wang (@wxygeek), Bicong Wang (@Wangbicong) -discussions-to: https://github.com/ethereum/EIPs/issues/1207 -status: Stagnant -type: Standards Track category: ERC -created: 2018-07-10 +status: Moved --- -DAuth Access Delegation Standard -===== - -## Simple Summary -DAuth is a standard interface for accessing authorization delegation between smart contracts and users. - -## Abstract -The DAuth protocol defines a set of standard API allowing identity delegations between smart contracts without the user's private key. Identity delegations include accessing and operating a user's data and assets contained in the delegated contracts. - -## Motivation -The inspiration for designing DAuth comes from OAuth protocol that is extensively used in web applications. But unlike the centralized authorization of OAuth, DAuth works in a distributed manner, thus providing much more reliability and generality. - -## Specification -![Rationale](../assets/eip-1207/rationale.png) - -**Resource owner**: the authorizer - -**Resource contract**: the contract providing data and operators - -**API**: the resource contract APIs that the grantee contract can invoke - -**Client contract**: the grantee contract using authorization to access and operate the data - -**Grantee request**: the client contract calls the resource contract with the authorizer authorization - - -**AuthInfo** -``` js -struct AuthInfo { - string[] funcNames; - uint expireAt; -} -``` -Required - The struct contains user authorization information -* `funcNames`: a list of function names callable by the granted contract -* `expireAt`: the authorization expire timestamp in seconds - -**userAuth** -``` js -mapping(address => mapping(address => AuthInfo)) userAuth; -``` -Required - userAuth maps (authorizer address, grantee contract address) pair to the user’s authorization AuthInfo object - -**callableFuncNames** -``` js -string[] callableFuncNames; -``` -Required - All methods that are allowed other contracts to call -* The callable function MUST verify the grantee’s authorization - -**updateCallableFuncNames** -``` js -function updateCallableFuncNames(string _invokes) public returns (bool success); -``` -Optional - Update the callable function list for the client contract by the resource contract's administrator -* `_invokes`: the invoke methods that the client contract can call -* return: Whether the callableFuncNames is updated or not -* This method MUST return success or throw, no other outcomes can be possible - -**verify** -``` js -function verify(address _authorizer, string _invoke) internal returns (bool success); -``` -Required - check the invoke method authority for the client contract -* `_authorizer`: the user address that the client contract agents -* `_invoke`: the invoke method that the client contract wants to call -* return: Whether the grantee request is authorized or not -* This method MUST return success or throw, no other outcomes can be possible - -**grant** -``` js -function grant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); -``` -Required - delegate a client contract to access the user's resource -* `_grantee`: the client contract address -* `_invokes`: the callable methods that the client contract can access. It is a string which contains all function names split by spaces -* `_expireAt`: the authorization expire timestamp in seconds -* return: Whether the grant is successful or not -* This method MUST return success or throw, no other outcomes can be possible -* A successful grant MUST fire the Grant event(defined below) - -**regrant** -``` js -function regrant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); -``` -Optional - alter a client contract's delegation - -**revoke** -``` js -function revoke(address _grantee) public returns (bool success); -``` -Required - delete a client contract's delegation -* `_grantee`: the client contract address -* return: Whether the revoke is successful or not -* A successful revoke MUST fire the Revoke event(defined below). - -**Grant** -``` js -event Grant(address _authorizer, address _grantee, string _invokes, uint _expireAt); -``` -* This event MUST trigger when the authorizer grant a new authorization when `grant` or `regrant` processes successfully - -**Revoke** -``` js -event Revoke(address _authorizer, address _grantee); -``` -* This event MUST trigger when the authorizer revoke a specific authorization successfully - -**Callable Resource Contract Functions** - -All public or external functions that are allowed the grantee to call MUST use overload to implement two functions: The First one is the standard method that the user invokes directly, the second one is the grantee methods of the same function name with one more authorizer address parameter. - -Example: -``` js -function approve(address _spender, uint256 _value) public returns (bool success) { - return _approve(msg.sender, _spender, _value); -} - -function approve(address _spender, uint256 _value, address _authorizer) public returns (bool success) { - verify(_authorizer, "approve"); - - return _approve(_authorizer, _spender, _value); -} - -function _approve(address sender, address _spender, uint256 _value) internal returns (bool success) { - allowed[sender][_spender] = _value; - emit Approval(sender, _spender, _value); - return true; -} -``` - -## Rationale - -**Current Limitations** - -The current design of many smart contracts only considers the user invokes the smart contract functions by themselves using the private key. However, in some case, the user wants to delegate other client smart contracts to access and operate their data or assets in the resource smart contract. There isn’t a common protocol to provide a standard delegation approach. - -**Rationale** - -On the Ethereum platform, all storage is transparent and the `msg.sender` is reliable. Therefore, the DAuth don't need an `access_token` like OAuth. DAuth just recodes the users' authorization for the specific client smart contract's address. It is simple and reliable on the Ethereum platform. - -## Backwards Compatibility -This EIP introduces no backward compatibility issues. In the future, the new version protocol has to keep these interfaces. - -## Implementation -Following is the DAuth Interface implementation. Furthermore, the example implementations of EIP20 Interface and ERC-DAuth Interface are also provided. Developers can easily implement their own contracts with ERC-DAuth Interface and other EIP. - -* ERC-DAuth Interface implementation is available at: - - https://github.com/DIA-Network/ERC-DAuth/blob/master/ERC-DAuth-Interface.sol - -* Example implementation with EIP20 Interface and ERC-DAuth Interface is available at: - - https://github.com/DIA-Network/ERC-DAuth/blob/master/eip20-dauth-example/EIP20DAuth.sol - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1207.md diff --git a/EIPS/eip-1261.md b/EIPS/eip-1261.md index e2bf12a7cd9cbe..ba3f868fa31714 100644 --- a/EIPS/eip-1261.md +++ b/EIPS/eip-1261.md @@ -1,390 +1,7 @@ --- eip: 1261 -title: Membership Verification Token (MVT) -author: Chaitanya Potti (@chaitanyapotti), Partha Bhattacharya (@pb25193) -type: Standards Track category: ERC -status: Stagnant -created: 2018-07-14 -requires: 165, 173 -discussions-to: https://github.com/ethereum/EIPs/issues/1261 +status: Moved --- -## Simple Summary - -A standard interface for Membership Verification Token(MVT). - -## Abstract - -The following standard allows for the implementation of a standard API for Membership Verification Token within smart contracts(called entities). This standard provides basic functionality to track membership of individuals in certain on-chain ‘organizations’. This allows for several use cases like automated compliance, and several forms of governance and membership structures. - -We considered use cases of MVTs being assigned to individuals which are non-transferable and revocable by the owner. MVTs can represent proof of recognition, proof of membership, proof of right-to-vote and several such otherwise abstract concepts on the blockchain. The following are some examples of those use cases, and it is possible to come up with several others: - -- Voting: Voting is inherently supposed to be a permissioned activity. So far, onchain voting systems are only able to carry out voting with coin balance based polls. This can now change and take various shapes and forms. -- Passport issuance, social benefit distribution, Travel permit issuance, Drivers licence issuance are all applications which can be abstracted into membership, that is belonging of an individual to a small set, recognized by some authority as having certain entitlements, without needing any individual specific information(right to welfare, freedom of movement, authorization to operate vehicles, immigration) -- Investor permissioning: Making regulatory compliance a simple on chain process. Tokenization of securities, that are streamlined to flow only to accredited addresses, tracing and certifying on chain addresses for AML purposes. -- Software licencing: Software companies like game developers can use the protocol to authorize certain hardware units(consoles) to download and use specific software(games) - -In general, an individual can have different memberships in their day to day life. The protocol allows for the creation of software that puts everything all at one place. Their identity can be verified instantly. Imagine a world where you don't need to carry a wallet full of identity cards (Passport, gym membership, SSN, Company ID etc) and organizations can easily keep track of all its members. Organizations can easily identify and disallow fake identities. - -Attributes are a huge part of ERC-1261 which help to store identifiable information regarding its members. Polls can make use of attributes to calculate the voterbase. -E.g: Users should belong to USA entity and not belong to Washington state attribute to be a part of a poll. - -There will exist a mapping table that maps attribute headers to an array of all possible attributes. This is done in order to subdivide entities into subgroups which are exclusive and exhaustive. For example, -header: blood group alphabet -Array: [ o, a, b, ab ] -header: blood group sign -Array: [ +, - ] - -NOT an example of exclusive exhaustive: -Header: video subscription -Array: [ Netflix, HBO, Amazon ] -Because a person is not necessitated to have EXACTLY one of the elements. He or she may have none or more than one. - -## Motivation - -A standard interface allows any user, applications to work with any MVT on Ethereum. We provide for simple ERC-1261 smart contracts. Additional applications are discussed below. - -This standard is inspired from the fact that voting on the blockchain is done with token balance weights. This has been greatly detrimental to the formation of flexible governance systems on the blockchain, despite the tremendous governance potential that blockchains offer. The idea was to create a permissioning system that allows organizations to vet people once into the organization on the blockchain, and then gain immense flexibility in the kind of governance that can be carried out. - -We have also reviewed other Membership EIPs including EIP-725/735 Claim Registry. A significant difference between #735 claims and #1261 MVTs is information ownership. In #735 the Claim Holder owns any claims made about themselves. The problem with this is that there is no way for a Claim Issuer to revoke or alter a claim once it has been issued. While #735 does specify a removeClaim method, a malicious implementation could simply ignore that method call, because they own the claim. - -Imagine that SafeEmploy™, a background checking company, issues a claim about Timmy. The claim states that Timmy has never been convicted of any felonies. Timmy makes some bad decisions, and now that claim is no longer true. SafeEmploy™ executes removeClaim, but Timmy's #735 contract just ignores it, because Timmy wants to stay employed (and is crypto-clever). #1261 MVTs do not have this problem. Ownership of a badge/claim is entirely determined by the contract issuing the badges, not the one receiving them. The issuer is free to remove or change those badges as they see fit. - -**Trade-off between trustlessness and usability:** -To truly understand the value of the protocol, it is important to understand the trade-off we are treading on. The MVT contract allows the creator to revoke the token, and essentially confiscate the membership of the member in question. To some, this might seem like an unacceptable flaw, however this is a design choice, and not a flaw. -The choice may seem to place a great amount of trust in the individuals who are managing the entity contract(entity owners). If the interests of the entity owner conflict with the interests of the members, the owner may resort to addition of fake addresses(to dominate consensus) or evicting members(to censor unfavourable decisions). At first glance this appears to be a major shortcomings, because the blockchain space is used to absolute removal of authority in most cases. Even the official definition of a dapp requires the absence of any party that manages the services provided by the application. However, the trust in entity owners is not misplaced, if it can be ensured that the interests of entity owners are aligned with the interests of members. -Another criticism of such a system would be that the standard edge of blockchain intermediation - “you cannot bribe the system if you don’t know who to bribe” - no longer holds. It is possible to bribe an entity owner into submission, and get them to censor or fake votes. There are several ways to respond to this argument. First of all, all activities, such as addition of members, and removal of members can be tracked on the blockchain and traces of such activity cannot be removed. It is not difficult to build analytics tools to detect malicious activity(adding 100 fake members suddenly who vote in the direction/sudden removal of a number of members voting in a certain direction). Secondly, the entity owners’ power is limited to the addition and removal of members. This means that they cannot tamper any votes. They can only alter the counting system to include fake voters or remove real voters. Any sensible auditor can identify the malicious/victim addresses and create an open source audit tool to find out the correct results. The biggest loser in this attack will be the entity owner, who has a reputation to lose. -Finally, one must understand why we are taking a step away from trustlessness in this trade-off. The answer is usability. Introducing a permissioning system expands the scope of products and services that can be delivered through the blockchain, while leveraging other aspects of the blockchain(cheap, immutable, no red-tape, secure). Consider the example of the driver licence issuing agency using the ERC-1300 standard. This is a service that simply cannot be deployed in a completely trustless environment. The introduction of permissioned systems expanded the scope of services on the blockchain to cover this particular service. Sure, they have the power to revoke a person’s licence for no reason. But will they? Who stands to lose the most, if the agency acts erratically? The agency itself. Now consider the alternative, the way licences(not necessarily only drivers licence, but say shareholder certificates and so on) are issued, the amount of time consumed, the complete lack of transparency. One could argue that if the legacy systems providing these services really wanted to carry out corruption and nepotism in the execution of these services, the present systems make it much easier to do so. Also, they are not transparent, meaning that there is no way to even detect if they act maliciously. -All that being said, we are very excited to share our proposal with the community and open up to suggestions in this space. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every ERC-1261 compliant contract must implement the `ERC1261`, `ERC173` and `ERC165` interfaces** (subject to "caveats" below): - -```solidity -/// @title ERC-1261 MVT Standard -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1261.md -/// The constructor should define the attribute set for this MVT. -/// Note: the ERC-165 identifier for this interface is 0x1d8362cf. -interface IERC1261 {/* is ERC173, ERC165 */ - /// @dev This emits when a token is assigned to a member. - event Assigned(address indexed _to, uint[] attributeIndexes); - - /// @dev This emits when a membership is revoked. - event Revoked(address indexed _to); - - /// @dev This emits when a user forfeits his membership - event Forfeited(address indexed _to); - - /// @dev This emits when a membership request is accepted - event ApprovedMembership(address indexed _to, uint[] attributeIndexes); - - /// @dev This emits when a membership is requested by an user - event RequestedMembership(address indexed _to); - - /// @dev This emits when data of a member is modified. - /// Doesn't emit when a new membership is created and data is assigned. - event ModifiedAttributes(address indexed _to, uint attributeIndex, uint attributeValueIndex); - - /// @notice Adds a new attribute (key, value) pair to the set of pre-existing attributes. - /// @dev Adds a new attribute at the end of the array of attributes and maps it to `values`. - /// Contract can set a max number of attributes and throw if limit is reached. - /// @param _name Name of the attribute which is to be added. - /// @param values List of values of the specified attribute. - function addAttributeSet(bytes32 _name, bytes32[] calldata values) external; - - /// @notice Modifies the attribute value of a specific attribute for a given `_to` address. - /// @dev Use appropriate checks for whether a user/admin can modify the data. - /// Best practice is to use onlyOwner modifier from ERC173. - /// @param _to The address whose attribute is being modified. - /// @param _attributeIndex The index of attribute which is being modified. - /// @param _modifiedValueIndex The index of the new value which is being assigned to the user attribute. - function modifyAttributeByIndex(address _to, uint _attributeIndex, uint _modifiedValueIndex) external; - - /// @notice Requests membership from any address. - /// @dev Throws if the `msg.sender` already has the token. - /// The individual `msg.sender` can request for a membership if some existing criteria are satisfied. - /// When a membership is requested, this function emits the RequestedMembership event. - /// dev can store the membership request and use `approveRequest` to assign membership later - /// dev can also oraclize the request to assign membership later - /// @param _attributeIndexes the attribute data associated with the member. - /// This is an array which contains indexes of attributes. - function requestMembership(uint[] calldata _attributeIndexes) external payable; - - /// @notice User can forfeit his membership. - /// @dev Throws if the `msg.sender` already doesn't have the token. - /// The individual `msg.sender` can revoke his/her membership. - /// When the token is revoked, this function emits the Revoked event. - function forfeitMembership() external payable; - - /// @notice Owner approves membership from any address. - /// @dev Throws if the `_user` doesn't have a pending request. - /// Throws if the `msg.sender` is not an owner. - /// Approves the pending request - /// Make oraclize callback call this function - /// When the token is assigned, this function emits the `ApprovedMembership` and `Assigned` events. - /// @param _user the user whose membership request will be approved. - function approveRequest(address _user) external; - - /// @notice Owner discards membership from any address. - /// @dev Throws if the `_user` doesn't have a pending request. - /// Throws if the `msg.sender` is not an owner. - /// Discards the pending request - /// Make oraclize callback call this function if criteria are not satisfied - /// @param _user the user whose membership request will be discarded. - function discardRequest(address _user) external; - - /// @notice Assigns membership of an MVT from owner address to another address. - /// @dev Throws if the member already has the token. - /// Throws if `_to` is the zero address. - /// Throws if the `msg.sender` is not an owner. - /// The entity assigns the membership to each individual. - /// When the token is assigned, this function emits the Assigned event. - /// @param _to The address to which the token is assigned. - /// @param _attributeIndexes The attribute data associated with the member. - /// This is an array which contains indexes of attributes. - function assignTo(address _to, uint[] calldata _attributeIndexes) external; - - /// @notice Only Owner can revoke the membership. - /// @dev This removes the membership of the user. - /// Throws if the `_from` is not an owner of the token. - /// Throws if the `msg.sender` is not an owner. - /// Throws if `_from` is the zero address. - /// When transaction is complete, this function emits the Revoked event. - /// @param _from The current owner of the MVT. - function revokeFrom(address _from) external; - - /// @notice Queries whether a member is a current member of the organization. - /// @dev MVT's assigned to the zero address are considered invalid, and this - /// function throws for queries about the zero address. - /// @param _to An address for whom to query the membership. - /// @return Whether the member owns the token. - function isCurrentMember(address _to) external view returns (bool); - - /// @notice Gets the value collection of an attribute. - /// @dev Returns the values of attributes as a bytes32 array. - /// @param _name Name of the attribute whose values are to be fetched - /// @return The values of attributes. - function getAttributeExhaustiveCollection(bytes32 _name) external view returns (bytes32[] memory); - - /// @notice Returns the list of all past and present members. - /// @dev Use this function along with isCurrentMember to find wasMemberOf() in Js. - /// It can be calculated as present in getAllMembers() and !isCurrentMember(). - /// @return List of addresses who have owned the token and currently own the token. - function getAllMembers() external view returns (address[]); - - /// @notice Returns the count of all current members. - /// @dev Use this function in polls as denominator to get percentage of members voted. - /// @return Count of current Members. - function getCurrentMemberCount() external view returns (uint); - - /// @notice Returns the list of all attribute names. - /// @dev Returns the names of attributes as a bytes32 array. - /// AttributeNames are stored in a bytes32 Array. - /// Possible values for each attributeName are stored in a mapping(attributeName => attributeValues). - /// AttributeName is bytes32 and attributeValues is bytes32[]. - /// Attributes of a particular user are stored in bytes32[]. - /// Which has a single attributeValue for each attributeName in an array. - /// Use web3.toAscii(data[0]).replace(/\u0000/g, "") to convert to string in JS. - /// @return The names of attributes. - function getAttributeNames() external view returns (bytes32[] memory); - - /// @notice Returns the attributes of `_to` address. - /// @dev Throws if `_to` is the zero address. - /// Use web3.toAscii(data[0]).replace(/\u0000/g, "") to convert to string in JS. - /// @param _to The address whose current attributes are to be returned. - /// @return The attributes associated with `_to` address. - function getAttributes(address _to) external view returns (bytes32[]); - - /// @notice Returns the `attribute` stored against `_to` address. - /// @dev Finds the index of the `attribute`. - /// Throws if the attribute is not present in the predefined attributes. - /// Returns the attributeValue for the specified `attribute`. - /// @param _to The address whose attribute is requested. - /// @param _attributeIndex The attribute Index which is required. - /// @return The attribute value at the specified name. - function getAttributeByIndex(address _to, uint _attributeIndex) external view returns (bytes32); -} - -interface ERC173 /* is ERC165 */ { - /// @dev This emits when ownership of a contract changes. - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /// @notice Get the address of the owner - /// @return The address of the owner. - function owner() external view; - - /// @notice Set the address of the new owner of the contract - /// @param _newOwner The address of the new owner of the contract - function transferOwnership(address _newOwner) external; -} - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The **metadata extension** is OPTIONAL for ERC-1261 smart contracts (see "caveats", below). This allows your smart contract to be interrogated for its name and for details about the organization which your MV tokens represent. - -```solidity -/// @title ERC-1261 MVT Standard, optional metadata extension -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1261.md -interface ERC1261Metadata /* is ERC1261 */ { - /// @notice A descriptive name for a collection of MVTs in this contract - function name() external view returns (string _name); - - /// @notice An abbreviated name for MVTs in this contract - function symbol() external view returns (string _symbol); -} -``` - -This is the "ERC1261 Metadata JSON Schema" referenced above. - -```json -{ - "title": "Organization Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the organization to which this MVT represents" - }, - "description": { - "type": "string", - "description": "Describes the organization to which this MVT represents" - } - } -} -``` - -### Caveats - -The 0.4.24 Solidity interface grammar is not expressive enough to document the ERC-1261 standard. A contract which complies with ERC-1261 MUST also abide by the following: - -- Solidity issue #3412: The above interfaces include explicit mutability guarantees for each function. Mutability guarantees are, in order weak to strong: `payable`, implicit nonpayable, `view`, and `pure`. Your implementation MUST meet the mutability guarantee in this interface and you MAY meet a stronger guarantee. For example, a `payable` function in this interface may be implemented as nonpayble (no state mutability specified) in your contract. We expect a later Solidity release will allow your stricter contract to inherit from this interface, but a workaround for version 0.4.24 is that you can edit this interface to add stricter mutability before inheriting from your contract. -- Solidity issue #3419: A contract that implements `ERC1261Metadata` SHALL also implement `ERC1261`. -- Solidity issue #2330: If a function is shown in this specification as `external` then a contract will be compliant if it uses `public` visibility. As a workaround for version 0.4.24, you can edit this interface to switch to `public` before inheriting from your contract. -- Solidity issues #3494, #3544: Use of `this.*.selector` is marked as a warning by Solidity, a future version of Solidity will not mark this as an error. - -_If a newer version of Solidity allows the caveats to be expressed in code, then this EIP MAY be updated and the caveats removed, such will be equivalent to the original specification._ - -## Rationale - -There are many potential uses of Ethereum smart contracts that depend on tracking membership. Examples of existing or planned MVT systems are Vault, a DAICO platform, and Stream, a security token framework. Future uses include the implementation of direct democracy, in-game memberships and badges, licence and travel document issuance, electronic voting machine trails, software licencing and many more. - -**MVT Word Choice:** - -Since the tokens are non transferable and revocable, they function like membership cards. Hence the word membership verification token. - -**Transfer Mechanism** - -MVTs can't be transferred. This is a design choice, and one of the features that distinguishes this protocol. -Any member can always ask the issuer to revoke the token from an existing address and assign to a new address. -One can think of the set of MVTs as identifying a user, and you cannot split the user into parts and have it be the same user, but you can transfer a user to a new private key. - -**Assign and Revoke mechanism** - -The assign and revoke functions' documentation only specify conditions when the transaction MUST throw. Your implementation MAY also throw in other situations. This allows implementations to achieve interesting results: - -- **Disallow additional memberships after a condition is met** — Sample contract available on GitHub -- **Blacklist certain address from receiving MV tokens** — Sample contract available on GitHub -- **Disallow additional memberships after a certain time is reached** — Sample contract available on GitHub -- **Charge a fee to user of a transaction** — require payment when calling `assign` and `revoke` so that condition checks from external sources can be made - -**ERC-173 Interface** - -We chose Standard Interface for Ownership (ERC-173) to manage the ownership of a ERC-1261 contract. - -A future EIP/ Zeppelin may create a multi-ownable implementation for ownership. We strongly support such an EIP and it would allow your ERC-1261 implementation to implement `ERC1261Metadata`, or other interfaces by delegating to a separate contract. - -**ERC-165 Interface** - -We chose Standard Interface Detection (ERC-165) to expose the interfaces that a ERC-1261 smart contract supports. - -A future EIP may create a global registry of interfaces for contracts. We strongly support such an EIP and it would allow your ERC-1261 implementation to implement `ERC1261Metadata`, or other interfaces by delegating to a separate contract. - -**Gas and Complexity** (regarding the enumeration extension) - -This specification contemplates implementations that manage a few and _arbitrarily large_ numbers of MVTs. If your application is able to grow then avoid using for/while loops in your code. These indicate your contract may be unable to scale and gas costs will rise over time without bound - -**Privacy** - -Personal information: The protocol does not put any personal information on to the blockchain, so there is no compromise of privacy in that respect. -Membership privacy: The protocol by design, makes it public which addresses are/aren’t members. Without making that information public, it would not be possible to independently audit governance activity or track admin(entity owner) activity. - -**Metadata Choices** (metadata extension) - -We have required `name` and `symbol` functions in the metadata extension. Every token EIP and draft we reviewed (ERC-20, ERC-223, ERC-677, ERC-777, ERC-827) included these functions. - -We remind implementation authors that the empty string is a valid response to `name` and `symbol` if you protest to the usage of this mechanism. We also remind everyone that any smart contract can use the same name and symbol as _your_ contract. How a client may determine which ERC-1261 smart contracts are well-known (canonical) is outside the scope of this standard. - -A mechanism is provided to associate MVTs with URIs. We expect that many implementations will take advantage of this to provide metadata for each MVT system. The URI MAY be mutable (i.e. it changes from time to time). We considered an MVT representing membership of a place, in this case metadata about the organization can naturally change. - -Metadata is returned as a string value. Currently this is only usable as calling from `web3`, not from other contracts. This is acceptable because we have not considered a use case where an on-blockchain application would query such information. - -_Alternatives considered: put all metadata for each asset on the blockchain (too expensive), use URL templates to query metadata parts (URL templates do not work with all URL schemes, especially P2P URLs), multiaddr network address (not mature enough)_ - -**Community Consensus** - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Backwards Compatibility - -We have adopted `name` and `symbol` semantics from the ERC-20 specification. - -Example MVT implementations as of July 2018: - -- Membership Verification Token(https://github.com/chaitanyapotti/MembershipVerificationToken) - -## Test Cases - -Membership Verification Token ERC-1261 Token includes test cases written using Truffle. - -## Implementations - -Membership Verification Token ERC1261 -- a reference implementation - -- MIT licensed, so you can freely use it for your projects -- Includes test cases -- Also available as a npm package - npm i membershipverificationtoken - -## References - -**Standards** - -1. ERC-20 Token Standard. ./eip-20.md -1. ERC-165 Standard Interface Detection. ./eip-165.md -1. ERC-725/735 Claim Registry ./eip-725.md -1. ERC-173 Owned Standard. ./eip-173.md -1. JSON Schema. https://json-schema.org/ -1. Multiaddr. https://github.com/multiformats/multiaddr -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -**Issues** - -1. The Original ERC-1261 Issue. https://github.com/ethereum/eips/issues/1261 -1. Solidity Issue \#2330 -- Interface Functions are Axternal. https://github.com/ethereum/solidity/issues/2330 -1. Solidity Issue \#3412 -- Implement Interface: Allow Stricter Mutability. https://github.com/ethereum/solidity/issues/3412 -1. Solidity Issue \#3419 -- Interfaces Can't Inherit. https://github.com/ethereum/solidity/issues/3419 - -**Discussions** - -1. Gitter #EIPs (announcement of first live discussion). https://gitter.im/ethereum/EIPs?at=5b5a1733d2f0934551d37642 -1. ERC-1261 (announcement of first live discussion). https://github.com/ethereum/eips/issues/1261 - -**MVT Implementations and Other Projects** - -1. Membership Verification Token ERC-1261 Token. https://github.com/chaitanyapotti/MembershipVerificationToken - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1261.md diff --git a/EIPS/eip-1271.md b/EIPS/eip-1271.md index 55da665aef721e..2a1649d5b0f11f 100644 --- a/EIPS/eip-1271.md +++ b/EIPS/eip-1271.md @@ -1,162 +1,7 @@ --- eip: 1271 -title: Standard Signature Validation Method for Contracts -description: Standard way to verify a signature when the account is a smart contract -author: Francisco Giordano (@frangio), Matt Condon (@shrugs), Philippe Castonguay (@PhABC), Amir Bandeali (@abandeali1), Jorge Izquierdo (@izqui), Bertrand Masius (@catageek) -discussions-to: https://github.com/ethereum/EIPs/issues/1271 -status: Final -type: Standards Track category: ERC -created: 2018-07-25 +status: Moved --- -## Abstract -Externally Owned Accounts (EOA) can sign messages with their associated private keys, but currently contracts cannot. We propose a standard way for any contracts to verify whether a signature on a behalf of a given contract is valid. This is possible via the implementation of a `isValidSignature(hash, signature)` function on the signing contract, which can be called to validate a signature. - -## Motivation - -There are and will be many contracts that want to utilize signed messages for validation of rights-to-move assets or other purposes. In order for these contracts to be able to support non Externally Owned Accounts (i.e., contract owners), we need a standard mechanism by which a contract can indicate whether a given signature is valid or not on its behalf. - -One example of an application that requires signatures to be provided would be decentralized exchanges with off-chain orderbook, where buy/sell orders are signed messages. In these applications, EOAs sign orders, signaling their desire to buy/sell a given asset and giving explicit permissions to the exchange smart contracts to conclude a trade via a signature. When it comes to contracts however, regular signatures are not possible since contracts do not possess a private key, hence this proposal. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt). - -```javascript -pragma solidity ^0.5.0; - -contract ERC1271 { - - // bytes4(keccak256("isValidSignature(bytes32,bytes)") - bytes4 constant internal MAGICVALUE = 0x1626ba7e; - - /** - * @dev Should return whether the signature provided is valid for the provided hash - * @param _hash Hash of the data to be signed - * @param _signature Signature byte array associated with _hash - * - * MUST return the bytes4 magic value 0x1626ba7e when function passes. - * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) - * MUST allow external calls - */ - function isValidSignature( - bytes32 _hash, - bytes memory _signature) - public - view - returns (bytes4 magicValue); -} -``` - -`isValidSignature` can call arbitrary methods to validate a given signature, which could be context dependent (e.g. time based or state based), EOA dependent (e.g. signers authorization level within smart wallet), signature scheme Dependent (e.g. ECDSA, multisig, BLS), etc. - -This function should be implemented by contracts which desire to sign messages (e.g. smart contract wallets, DAOs, multisignature wallets, etc.) Applications wanting to support contract signatures should call this method if the signer is a contract. - - -## Rationale -We believe the name of the proposed function to be appropriate considering that an *authorized* signers providing proper signatures for a given data would see their signature as "valid" by the signing contract. Hence, an signed action message is only valid when the signer is authorized to perform a given action on the behalf of a smart wallet. - -Two arguments are provided for simplicity of separating the hash signed from the signature. A bytes32 hash is used instead of the unhashed message for simplicy, since contracts could expect a certain hashing function that is not standard, such as with [EIP-712](./eip-712.md). - -`isValidSignature()` should not be able to modify states in order to prevent `GasToken` minting or similar attack vectors. Again, this is to simplify the implementation surface of the function for better standardization and to allow off-chain contract queries. - -The specific return value is expected to be returned instead of a boolean in order to have stricter and simpler verification of a signature. - -## Backwards Compatibility - -This EIP is backward compatible with previous work on signature validation since this method is specific to contract based signatures and not EOA signatures. - -## Reference Implementation - -Example implementation of a signing contract: - -```solidity - - /** - * @notice Verifies that the signer is the owner of the signing contract. - */ - function isValidSignature( - bytes32 _hash, - bytes calldata _signature - ) external override view returns (bytes4) { - // Validate signatures - if (recoverSigner(_hash, _signature) == owner) { - return 0x1626ba7e; - } else { - return 0xffffffff; - } - } - - /** - * @notice Recover the signer of hash, assuming it's an EOA account - * @dev Only for EthSign signatures - * @param _hash Hash of message that was signed - * @param _signature Signature encoded as (bytes32 r, bytes32 s, uint8 v) - */ - function recoverSigner( - bytes32 _hash, - bytes memory _signature - ) internal pure returns (address signer) { - require(_signature.length == 65, "SignatureValidator#recoverSigner: invalid signature length"); - - // Variables are not scoped in Solidity. - uint8 v = uint8(_signature[64]); - bytes32 r = _signature.readBytes32(0); - bytes32 s = _signature.readBytes32(32); - - // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature - // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines - // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most - // signatures from current libraries generate a unique signature with an s-value in the lower half order. - // - // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value - // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or - // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept - // these malleable signatures as well. - // - // Source OpenZeppelin - // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol - - if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { - revert("SignatureValidator#recoverSigner: invalid signature 's' value"); - } - - if (v != 27 && v != 28) { - revert("SignatureValidator#recoverSigner: invalid signature 'v' value"); - } - - // Recover ECDSA signer - signer = ecrecover(_hash, v, r, s); - - // Prevent signer from being 0x0 - require( - signer != address(0x0), - "SignatureValidator#recoverSigner: INVALID_SIGNER" - ); - - return signer; - } -``` - -Example implementation of a contract calling the isValidSignature() function on an external signing contract ; - -```solidity - function callERC1271isValidSignature( - address _addr, - bytes32 _hash, - bytes calldata _signature - ) external view { - bytes4 result = IERC1271Wallet(_addr).isValidSignature(_hash, _signature); - require(result == 0x1626ba7e, "INVALID_SIGNATURE"); - } -``` - -## Security Considerations -Since there are no gas-limit expected for calling the isValidSignature() function, it is possible that some implementation will consume a large amount of gas. It is therefore important to not hardcode an amount of gas sent when calling this method on an external contract as it could prevent the validation of certain signatures. - -Note also that each contract implementing this method is responsible to ensure that the signature passed is indeed valid, otherwise catastrophic outcomes are to be expected. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1271.md diff --git a/EIPS/eip-1319.md b/EIPS/eip-1319.md index 92ab5560e002b7..f2692ae66c1298 100644 --- a/EIPS/eip-1319.md +++ b/EIPS/eip-1319.md @@ -1,176 +1,7 @@ --- eip: 1319 -title: Smart Contract Package Registry Interface -author: Piper Merriam , Christopher Gewecke , g. nicholas d'andrea , Nick Gheorghita (@njgheorghita) -type: Standards Track category: ERC -status: Stagnant -created: 2018-08-13 -discussions-to: https://github.com/ethereum/EIPs/issues/1319 +status: Moved --- -## Simple Summary -A standard interface for smart contract package registries. - -## Abstract -This EIP specifies an interface for publishing to and retrieving assets from smart contract package registries. It is a companion EIP to [1123](./eip-1123.md) which defines a standard for smart contract package manifests. - -## Motivation -The goal is to establish a framework that allows smart contract publishers to design and deploy code registries with arbitrary business logic while exposing a set of common endpoints that tooling can use to retrieve assets for contract consumers. - -A clear standard would help the existing EthPM Package Registry evolve from a centralized, single-project community resource into a decentralized multi-registry system whose constituents are bound together by the proposed interface. In turn, these registries could be ENS name-spaced, enabling installation conventions familiar to users of `npm` and other package managers. - -**Examples** -```shell -$ ethpm install packages.zeppelin.eth/Ownership -``` - -```javascript -const SimpleToken = await web3.packaging - .registry('packages.ethpm.eth') - .getPackage('simple-token') - .getVersion('^1.1.5'); -``` - -## Specification -The specification describes a small read/write API whose components are mandatory. It allows registries to manage versioned releases using the conventions of [semver](https://semver.org/) without imposing this as a requirement. It assumes registries will share the following structure and conventions: - -+ a **registry** is a deployed contract which manages a collection of **packages**. -+ a **package** is a collection of **releases** -+ a **package** is identified by a unique string name and unique bytes32 **packageId** within a given **registry** -+ a **release** is identified by a `bytes32` **releaseId** which must be unique for a given package name and release version string pair. -+ a **releaseId** maps to a set of data that includes a **manifestURI** string which describes the location of an [EIP 1123 package manifest](./eip-1123.md). This manifest contains data about the release including the location of its component code assets. -+ a **manifestURI** is a URI as defined by [RFC3986](https://tools.ietf.org/html/rfc3986) which can be used to retrieve the contents of the package manifest. In addition to validation against RFC3986, each **manifestURI** must also contain a hash of the content as specified in the [EIP-1123](./eip-1123.md). - -### Examples - -**Package Names / Release Versions** - -```shell -"simple-token" # package name -"1.0.1" # version string -``` - -**Release IDs** - -Implementations are free to choose any scheme for generating a **releaseId**. A common approach would be to hash the strings together as below: - -```solidity -// Hashes package name and a release version string -function generateReleaseId(string packageName, string version) - public - view - returns (bytes32 releaseId) - { - return keccak256(abi.encodePacked(packageName, version)); - } -``` -Implementations **must** expose this id generation logic as part of their public `read` API so -tooling can easily map a string based release query to the registry's unique identifier for that release. - -**Manifest URIs** - -Any IPFS or Swarm URI meets the definition of **manifestURI**. - -Another example is content on GitHub addressed by its SHA-1 hash. The Base64 encoded content at this hash can be obtained by running: -```shell -$ curl https://api.github.com/repos/:owner/:repo/git/blobs/:file_sha - -# Example -$ curl https://api.github.com/repos/rstallman/hello/git/blobs/ce013625030ba8dba906f756967f9e9ca394464a -``` - -The string "hello" can have its GitHub SHA-1 hash independently verified by comparing it to the output of: -```shell -$ printf "blob 6\000hello\n" | sha1sum -> ce013625030ba8dba906f756967f9e9ca394464a -``` - -### Write API Specification -The write API consists of a single method, `release`. It passes the registry the package name, a -version identifier for the release, and a URI specifying the location of a manifest which -details the contents of the release. -```solidity -function release(string packageName, string version, string manifestURI) public - returns (bytes32 releaseId); -``` - -### Events - -#### VersionRelease -MUST be triggered when `release` is successfully called. - -```solidity -event VersionRelease(string packageName, string version, string manifestURI) -``` - -### Read API Specification - -The read API consists of a set of methods that allows tooling to extract all consumable data from a registry. - -```solidity -// Retrieves a slice of the list of all unique package identifiers in a registry. -// `offset` and `limit` enable paginated responses / retrieval of the complete set. (See note below) -function getAllPackageIds(uint offset, uint limit) public view - returns ( - bytes32[] packageIds, - uint pointer - ); - -// Retrieves the unique string `name` associated with a package's id. -function getPackageName(bytes32 packageId) public view returns (string packageName); - -// Retrieves the registry's unique identifier for an existing release of a package. -function getReleaseId(string packageName, string version) public view returns (bytes32 releaseId); - -// Retrieves a slice of the list of all release ids for a package. -// `offset` and `limit` enable paginated responses / retrieval of the complete set. (See note below) -function getAllReleaseIds(string packageName, uint offset, uint limit) public view - returns ( - bytes32[] releaseIds, - uint pointer - ); - -// Retrieves package name, release version and URI location data for a release id. -function getReleaseData(bytes32 releaseId) public view - returns ( - string packageName, - string version, - string manifestURI - ); - -// Retrieves the release id a registry *would* generate for a package name and version pair -// when executing a release. -function generateReleaseId(string packageName, string version) - public - view - returns (bytes32 releaseId); - -// Returns the total number of unique packages in a registry. -function numPackageIds() public view returns (uint totalCount); - -// Returns the total number of unique releases belonging to the given packageName in a registry. -function numReleaseIds(string packageName) public view returns (uint totalCount); -``` -**Pagination** - -`getAllPackageIds` and `getAllReleaseIds` support paginated requests because it's possible that the return values for these methods could become quite large. The methods should return a `pointer` that points to the next available item in a list of all items such that a caller can use it to pick up from where the previous request left off. (See [here](https://mixmax.com/blog/api-paging-built-the-right-way) for a discussion of the merits and demerits of various pagination strategies.) The `limit` parameter defines the maximum number of items a registry should return per request. - -## Rationale -The proposal hopes to accomplish the following: - -+ Define the smallest set of inputs necessary to allow registries to map package names to a set of -release versions while allowing them to use any versioning schema they choose. -+ Provide the minimum set of getter methods needed to retrieve package data from a registry so that registry aggregators can read all of their data. -+ Define a standard query that synthesizes a release identifier from a package name and version pair so that tooling can resolve specific package version requests without needing to query a registry about all of a package's releases. - -Registries may offer more complex `read` APIs that manage requests for packages within a semver range or at `latest` etc. This EIP is agnostic about how tooling or registries might implement these. It recommends that registries implement [EIP-165](./eip-165.md) and avail themselves of resources to publish more complex interfaces such as [EIP-926](./eip-926.md). - -## Backwards Compatibility -No existing standard exists for package registries. The package registry currently deployed by EthPM would not comply with the standard since it implements only one of the method signatures described in the specification. - -## Implementation -A reference implementation of this proposal is in active development at the EthPM organization on GitHub [here](https://github.com/ethpm/escape-truffle). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1319.md diff --git a/EIPS/eip-1328.md b/EIPS/eip-1328.md index ddc15279daa58c..6038084aa2162c 100644 --- a/EIPS/eip-1328.md +++ b/EIPS/eip-1328.md @@ -1,72 +1,7 @@ --- eip: 1328 -title: WalletConnect URI Format -description: Define URI format for initiating connections between applications and wallets -author: ligi (@ligi), Pedro Gomes (@pedrouid) -discussions-to: https://ethereum-magicians.org/t/wallet-connect-eip/850 -status: Review -type: Standards Track category: ERC -created: 2018-08-15 +status: Moved --- -## Abstract - -This standard defines how the data to connect some application and a wallet can be encoded with a URI. This URI can then be shown either as a QR code or as a link. - -## Specification - -### Syntax - -WalletConnect request URI with the following parameters: - - request = "wc" ":" topic [ "@" version ][ "?" parameters ] - topic = STRING - version = 1*DIGIT - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = STRING - value = STRING - -### Semantics - -Required parameters are dependent on the WalletConnect protocol version: - -For WalletConnect v1.0 protocol (`version`=`1`) the parameters are: - -- `key` - symmetric key used for encryption -- `bridge` - url of the bridge server for relaying messages - -For WalletConnect v2.0 protocol (`version`=`2`) the parameters are: - -- `symKey` - symmetric key used for encrypting messages over relay -- `methods` - jsonrpc methods supported for pairing topic -- `relay-protocol` - transport protocol for relaying messages -- `relay-data` - (optional) transport data for relaying messages - - -### Example - -``` -# 1.0 -wc:8a5e5bdc-a0e4-4702-ba63-8f1a5655744f@1?bridge=https%3A%2F%2Fbridge.walletconnect.org&key=41791102999c339c844880b23950704cc43aa840f3739e365323cda4dfa89e7a - -# 2.0 -wc:7f6e504bfad60b485450578e05678ed3e8e8c4751d3c6160be17160d63ec90f9@2?relay-protocol=irn&symKey=587d5484ce2a2a6ee3ba1962fdd7e8588e06200c46823bd18fbd67def96ad303&methods=[wc_sessionPropose],[wc_authRequest,wc_authBatchRequest]" -``` - -## Rationale - -This proposal moves away from the JSON format used in the alpha version of the WalletConnect protocol because it suffered from very inefficient parsing of the intent of the QR code, thereby making it easier to create better QR code parsers APIs for wallets to implement. Also by using a URI instead of JSON inside the QR-Code the Android Intent system can be leveraged. - -## Backwards Compatibility - -Versioning is required as part of the syntax for this URI specification to allow the WalletConnect protocol to evolve and allow backwards-compatibility whenever a new version is introduced. - -## Security Considerations - -URIs should be shared between user devices or applications and no sensitive data is shared within the URI that could compromise the communication or would allow control of the user's private keys. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1328.md diff --git a/EIPS/eip-1337.md b/EIPS/eip-1337.md index 665756b47070da..8d201b25cb9b2f 100644 --- a/EIPS/eip-1337.md +++ b/EIPS/eip-1337.md @@ -1,247 +1,7 @@ --- eip: 1337 -title: Subscriptions on the blockchain -author: Kevin Owocki , Andrew Redden , Scott Burke , Kevin Seagraves , Luka Kacil , Štefan Šimec , Piotr Kosiński (@kosecki123), ankit raj , John Griffin , Nathan Creswell -discussions-to: https://ethereum-magicians.org/t/eip-1337-subscriptions-on-the-blockchain/4422 -type: Standards Track -status: Stagnant category: ERC -created: 2018-08-01 -requires: 20, 165 +status: Moved --- -## Simple Summary -Monthly subscriptions are a key monetization channel for legacy web, and arguably they are the most healthy monetization channel for businesses on the legacy web (especially when compared to ad/surveillance) based models. They are arguably more healthy than a token based economic system (depending upon the vesting model of the ICO) because - -##### For a user: - * you don't have to read a complex whitepaper to use a dapps utility (as opposed to utility tokens) -* you don't have to understand the founder's vesting schedules -* you can cancel anytime - -##### For a Service Provider: -* since you know your subscriber numbers, churn numbers, conversion rate, you get consistent cash flow, and accurate projections -* you get to focus on making your customers happy -* enables you to remove speculators from your ecosystem - -For these reasons, we think it's imperative to create a standard way to do 'subscriptions' on Ethereum. - -## Abstract -To enable replay-able transactions users sign a concatenated bytes hash that is composed of the input data needed to execute the transaction. This data is stored off chain by the recipient of the payment and is transmitted to the customers smart contract for execution alongside a provided signature. - -## Motivation -Recurring payments are the bedrock of SaSS and countless other businesses, a robust specification for defining this interaction will enable a broad spectrum of revenue generation and business models. - -## Specification -#### Enum Contract - -EIP-1337 Contracts should be compiled with a contract that references all the enumerations that are required for operation - -```SOLIDITY -/// @title Enum - Collection of enums -/// Original concept from Richard Meissner - Gnosis safe contracts -contract Enum { - enum Operation { - Call, - DelegateCall, - Create, - ERC20, - ERC20Approve - } - enum SubscriptionStatus { - ACTIVE, - PAUSED, - CANCELLED, - EXPIRED - } - - enum Period { - INIT, - DAY, - WEEK, - MONTH - } -} -``` - -#### EIP-165 - -EIP-1337 compliant contracts support EIP-165 announcing what interfaces they support - -```SOLIDITY -interface ERC165 { - /** - * @notice Query if a contract implements an interface - * @param interfaceID The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - * @return `true` if the contract implements `interfaceID` and - * `interfaceID` is not 0xffffffff, `false` otherwise - **/ - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -#### Public View Functions - -###### isValidSubscription -```SOLIDITY - -/** @dev Checks if the subscription is valid. - * @param bytes subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @return success is the result of whether the subscription is valid or not. - **/ - -function isValidSubscription( - uint256 subscriptionHash - ) - public - view - returns ( - bool success - ) -``` -###### getSubscriptionStatus -```SOLIDITY - -/** @dev returns the value of the subscription - * @param bytes subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @return status is the enumerated status of the current subscription, 0 expired, 1 active, 2 paused, 3 cancelled - **/ -function getSubscriptionStatus( - uint256 subscriptionHash - ) - public - view - returns ( - uint256 status, - uint256 nextWithdraw - ) -``` - -###### getSubscriptionHash - -```SOLIDITY -/** @dev returns the hash of cocatenated inputs to the address of the contract holding the logic., - * the owner would sign this hash and then provide it to the party for execution at a later date, - * this could be viewed like a cheque, with the exception that unless you specifically - * capture the hash on chain a valid signature will be executable at a later date, capturing the hash lets you modify the status to cancel or expire it. - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @param bytes data the data the user is agreeing to - * @param uint256 txGas the cost of executing one of these transactions in gas(probably safe to pad this) - * @param uint256 dataGas the cost of executing the data portion of the transaction(delegate calls etc) - * @param uint 256 gasPrice the agreed upon gas cost of Execution of this subscription(cost incurment is up to implementation, ie, sender or receiver) - * @param address gasToken address of the token in which gas will be compensated by, address(0) is ETH, only works in the case of an enscrow implementation) - * @param bytes meta dynamic bytes array with 4 slots, 2 required, 2 optional // address refundAddress / uint256 period / uint256 offChainID / uint256 expiration (uinx timestamp) - * @return bytes32, return the hash input arguments concatenated to the address of the contract that holds the logic. - **/ -function getSubscriptionHash( - address recipient, - uint256 value, - bytes data, - Enum.Operation operation, - uint256 txGas, - uint256 dataGas, - uint256 gasPrice, - address gasToken, - bytes meta - ) - public - view - returns ( - bytes32 subscriptionHash - ) -``` - - -###### getModifyStatusHash - -```SOLIDITY -/** @dev returns the hash of concatenated inputs that the owners user would sign with their public keys - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @return bytes32 returns the hash of concatenated inputs with the address of the contract holding the subscription hash - **/ -function getModifyStatusHash( - bytes32 subscriptionHash - Enum.SubscriptionStatus status - ) - public - view - returns ( - bytes32 modifyStatusHash - ) -``` -#### Public Functions - -###### modifyStatus -```SOLIDITY - -/** @dev modifys the current subscription status - * @param uint256 subscriptionHash is the identifier of the customer's subscription with its relevant details. - * @param Enum.SubscriptionStatus status the new status of the subscription - * @param bytes signatures of the requested method being called - * @return success is the result of the subscription being paused - **/ -function modifyStatus( - uint256 subscriptionHash, - Enum.SubscriptionStatus status, - bytes signatures - ) - public - returns ( - bool success - ) -``` - -###### executeSubscription -```SOLIDITY - -/** @dev returns the hash of cocatenated inputs to the address of the contract holding the logic., - * the owner would sign this hash and then provide it to the party for execution at a later date, - * this could be viewed like a cheque, with the exception that unless you specifically - * capture the hash on chain a valid signature will be executable at a later date, capturing the hash lets you modify the status to cancel or expire it. - * @param address recipient the address of the person who is getting the funds. - * @param uint256 value the value of the transaction - * @param bytes data the data the user is agreeing to - * @param uint256 txGas the cost of executing one of these transactions in gas(probably safe to pad this) - * @param uint256 dataGas the cost of executing the data portion of the transaction(delegate calls etc) - * @param uint 256 gasPrice the agreed upon gas cost of Execution of this subscription(cost incurment is up to implementation, ie, sender or receiver) - * @param address gasToken address of the token in which gas will be compensated by, address(0) is ETH, only works in the case of an enscrow implementation) - * @param bytes meta dynamic bytes array with 4 slots, 2 required, 2 optional // address refundAddress / uint256 period / uint256 offChainID / uint256 expiration (uinx timestamp) - * @param bytes signatures signatures concatenated that have signed the inputs as proof of valid execution - * @return bool success something to note that a failed execution will still pay the issuer of the transaction for their gas costs. - **/ -function executeSubscription( - address to, - uint256 value, - bytes data, - Enum.Operation operation, - uint256 txGas, - uint256 dataGas, - uint256 gasPrice, - address gasToken, - bytes meta, - bytes signatures - ) - public - returns ( - bool success - ) -``` - -## Rationale -Merchants who accept credit-cards do so by storing a token that is retrieved from a third party processor(stripe, paypal, etc), this token is used to grant access to pull payment from the cx's credit card provider and move funds to the merchant account. -Having users sign input data acts in a similliar fashion and enables that merchant to store the signature of the concatenated bytes hash and input data used to generate the hash and pass them off to the contract holding the subscription logic, thus enabling a workflow that is similliar to what exists in the present day legacy web. - -## Backwards Compatibility -N/A - -## Test Cases -TBD - -## Implementation -TBD - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1337.md diff --git a/EIPS/eip-1363.md b/EIPS/eip-1363.md index d4984c37998c9f..8c0100cab26161 100644 --- a/EIPS/eip-1363.md +++ b/EIPS/eip-1363.md @@ -1,208 +1,7 @@ --- eip: 1363 -title: Payable Token -author: Vittorio Minacori (@vittominacori) -discussions-to: https://github.com/ethereum/eips/issues/1363 -status: Final -type: Standards Track category: ERC -created: 2020-01-31 -requires: 20, 165 +status: Moved --- -## Simple Summary -Defines a token interface for [ERC-20](./eip-20.md) tokens that supports executing recipient code after `transfer` or `transferFrom`, or spender code after `approve`. - -## Abstract -Standard functions a token contract and contracts working with tokens can implement to make a token Payable. - -`transferAndCall` and `transferFromAndCall` will call an `onTransferReceived` on a `ERC1363Receiver` contract. - -`approveAndCall` will call an `onApprovalReceived` on a `ERC1363Spender` contract. - -## Motivation -There is no way to execute code after a [ERC-20](./eip-20.md) transfer or approval (i.e. making a payment), so to make an action it is required to send another transaction and pay GAS twice. - -This proposal wants to make token payments easier and working without the use of any other listener. It allows to make a callback after a transfer or approval in a single transaction. - -There are many proposed uses of Ethereum smart contracts that can accept [ERC-20](./eip-20.md) payments. - -Examples could be -* to create a token payable crowdsale -* selling services for tokens -* paying invoices -* making subscriptions - -For these reasons it was named as **"Payable Token"**. - -Anyway you can use it for specific utilities or for any other purposes who require the execution of a callback after a transfer or approval received. - -This proposal has been inspired by the [ERC-721](./eip-721.md) `onERC721Received` and `ERC721TokenReceiver` behaviours. - -## Specification -Implementing contracts **MUST** implement the [ERC-1363](./eip-1363.md) interface as well as the [ERC-20](./eip-20.md) and [ERC-165](./eip-165.md) interfaces. - -```solidity -pragma solidity ^0.8.0; - -interface ERC1363 /* is ERC20, ERC165 */ { - /* - * Note: the ERC-165 identifier for this interface is 0xb0202a11. - * 0xb0202a11 === - * bytes4(keccak256('transferAndCall(address,uint256)')) ^ - * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ - * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ - * bytes4(keccak256('approveAndCall(address,uint256)')) ^ - * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) - */ - - /** - * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferAndCall(address to, uint256 value) external returns (bool); - - /** - * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool); - - /** - * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 value) external returns (bool); - - - /** - * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver - * @param from address The address which you want to send tokens from - * @param to address The address which you want to transfer to - * @param value uint256 The amount of tokens to be transferred - * @param data bytes Additional data with no specified format, sent in call to `to` - * @return true unless throwing - */ - function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool); - - /** - * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - */ - function approveAndCall(address spender, uint256 value) external returns (bool); - - /** - * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender - * and then call `onApprovalReceived` on spender. - * @param spender address The address which will spend the funds - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format, sent in call to `spender` - */ - function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool); -} - -interface ERC20 { - function totalSupply() external view returns (uint256); - function balanceOf(address account) external view returns (uint256); - function transfer(address recipient, uint256 amount) external returns (bool); - function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); - function allowance(address owner, address spender) external view returns (uint256); - function approve(address spender, uint256 amount) external returns (bool); - event Transfer(address indexed from, address indexed to, uint256 value); - event Approval(address indexed owner, address indexed spender, uint256 value); -} - -interface ERC165 { - function supportsInterface(bytes4 interfaceId) external view returns (bool); -} -``` - -A contract that wants to accept token payments via `transferAndCall` or `transferFromAndCall` **MUST** implement the following interface: - -```solidity -/** - * @title ERC1363Receiver interface - * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall` - * from ERC1363 token contracts. - */ -interface ERC1363Receiver { - /* - * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. - * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) - */ - - /** - * @notice Handle the receipt of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function - * @param from address The address which are token transferred from - * @param value uint256 The amount of tokens transferred - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` - * unless throwing - */ - function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4); -} -``` - -A contract that wants to accept token payments via `approveAndCall` **MUST** implement the following interface: - -```solidity -/** - * @title ERC1363Spender interface - * @dev Interface for any contract that wants to support `approveAndCall` - * from ERC1363 token contracts. - */ -interface ERC1363Spender { - /* - * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. - * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) - */ - - /** - * @notice Handle the approval of ERC1363 tokens - * @dev Any ERC1363 smart contract calls this function on the recipient - * after an `approve`. This function MAY throw to revert and reject the - * approval. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the token contract address is always the message sender. - * @param owner address The address which called `approveAndCall` function - * @param value uint256 The amount of tokens to be spent - * @param data bytes Additional data with no specified format - * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` - * unless throwing - */ - function onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4); -} -``` - -## Rationale -The choice to use `transferAndCall`, `transferFromAndCall` and `approveAndCall` derives from the [ERC-20](./eip-20.md) naming. They want to highlight that they have the same behaviours of `transfer`, `transferFrom` and `approve` with the addition of a callback on receiver or spender. - -## Backwards Compatibility -This proposal has been inspired also by [ERC-223](https://github.com/ethereum/EIPs/issues/223) and [ERC-677](https://github.com/ethereum/EIPs/issues/677) but it uses the [ERC-721](./eip-721.md) approach, so it doesn't override the [ERC-20](./eip-20.md) `transfer` and `transferFrom` methods and defines the interfaces IDs to be implemented maintaining the [ERC-20](./eip-20.md) backwards compatibility. - -## Security Considerations -The `approveAndCall` and `transferFromAndCall` methods can be affected by the same issue of the standard [ERC-20](./eip-20.md) `approve` and `transferFrom` method. - -Changing an allowance with the `approveAndCall` methods brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. - -One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards ([EIP-20#issuecomment-263524729](https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1363.md diff --git a/EIPS/eip-137.md b/EIPS/eip-137.md index b35e9ef62c2649..71ad10879546df 100644 --- a/EIPS/eip-137.md +++ b/EIPS/eip-137.md @@ -1,386 +1,7 @@ --- eip: 137 -title: Ethereum Domain Name Service - Specification -author: Nick Johnson -status: Final -type: Standards Track category: ERC -created: 2016-04-04 +status: Moved --- -# Abstract - -This draft EIP describes the details of the Ethereum Name Service, a proposed protocol and ABI definition that provides flexible resolution of short, human-readable names to service and resource identifiers. This permits users and developers to refer to human-readable and easy to remember names, and permits those names to be updated as necessary when the underlying resource (contract, content-addressed data, etc) changes. - -The goal of domain names is to provide stable, human-readable identifiers that can be used to specify network resources. In this way, users can enter a memorable string, such as 'vitalik.wallet' or 'www.mysite.swarm', and be directed to the appropriate resource. The mapping between names and resources may change over time, so a user may change wallets, a website may change hosts, or a swarm document may be updated to a new version, without the domain name changing. Further, a domain need not specify a single resource; different record types allow the same domain to reference different resources. For instance, a browser may resolve 'mysite.swarm' to the IP address of its server by fetching its A (address) record, while a mail client may resolve the same address to a mail server by fetching its MX (mail exchanger) record. -# Motivation - -Existing [specifications](https://github.com/ethereum/wiki/wiki/Registrar-ABI) and [implementations](https://ethereum.gitbooks.io/frontier-guide/content/registrar_services.html) for name resolution in Ethereum provide basic functionality, but suffer several shortcomings that will significantly limit their long-term usefulness: -- A single global namespace for all names with a single 'centralised' resolver. -- Limited or no support for delegation and sub-names/sub-domains. -- Only one record type, and no support for associating multiple copies of a record with a domain. -- Due to a single global implementation, no support for multiple different name allocation systems. -- Conflation of responsibilities: Name resolution, registration, and whois information. - -Use-cases that these features would permit include: -- Support for subnames/sub-domains - eg, live.mysite.tld and forum.mysite.tld. -- Multiple services under a single name, such as a DApp hosted in Swarm, a Whisper address, and a mail server. -- Support for DNS record types, allowing blockchain hosting of 'legacy' names. This would permit an Ethereum client such as Mist to resolve the address of a traditional website, or the mail server for an email address, from a blockchain name. -- DNS gateways, exposing ENS domains via the Domain Name Service, providing easier means for legacy clients to resolve and connect to blockchain services. - -The first two use-cases, in particular, can be observed everywhere on the present-day internet under DNS, and we believe them to be fundamental features of a name service that will continue to be useful as the Ethereum platform develops and matures. - -The normative parts of this document does not specify an implementation of the proposed system; its purpose is to document a protocol that different resolver implementations can adhere to in order to facilitate consistent name resolution. An appendix provides sample implementations of resolver contracts and libraries, which should be treated as illustrative examples only. - -Likewise, this document does not attempt to specify how domains should be registered or updated, or how systems can find the owner responsible for a given domain. Registration is the responsibility of registrars, and is a governance matter that will necessarily vary between top-level domains. - -Updating of domain records can also be handled separately from resolution. Some systems, such as swarm, may require a well defined interface for updating domains, in which event we anticipate the development of a standard for this. -# Specification -## Overview - -The ENS system comprises three main parts: -- The ENS registry -- Resolvers -- Registrars - -The registry is a single contract that provides a mapping from any registered name to the resolver responsible for it, and permits the owner of a name to set the resolver address, and to create subdomains, potentially with different owners to the parent domain. - -Resolvers are responsible for performing resource lookups for a name - for instance, returning a contract address, a content hash, or IP address(es) as appropriate. The resolver specification, defined here and extended in other EIPs, defines what methods a resolver may implement to support resolving different types of records. - -Registrars are responsible for allocating domain names to users of the system, and are the only entities capable of updating the ENS; the owner of a node in the ENS registry is its registrar. Registrars may be contracts or externally owned accounts, though it is expected that the root and top-level registrars, at a minimum, will be implemented as contracts. - -Resolving a name in ENS is a two-step process. First, the ENS registry is called with the name to resolve, after hashing it using the procedure described below. If the record exists, the registry returns the address of its resolver. Then, the resolver is called, using the method appropriate to the resource being requested. The resolver then returns the desired result. - -For example, suppose you wish to find the address of the token contract associated with 'beercoin.eth'. First, get the resolver: - -```javascript -var node = namehash("beercoin.eth"); -var resolver = ens.resolver(node); -``` - -Then, ask the resolver for the address for the contract: - -```javascript -var address = resolver.addr(node); -``` - -Because the `namehash` procedure depends only on the name itself, this can be precomputed and inserted into a contract, removing the need for string manipulation, and permitting O(1) lookup of ENS records regardless of the number of components in the raw name. -## Name Syntax - -ENS names must conform to the following syntax: - -
<domain> ::= <label> | <domain> "." <label>
-<label> ::= any valid string label per [UTS46](https://unicode.org/reports/tr46/)
-
- -In short, names consist of a series of dot-separated labels. Each label must be a valid normalised label as described in [UTS46](https://unicode.org/reports/tr46/) with the options `transitional=false` and `useSTD3AsciiRules=true`. For Javascript implementations, a [library](https://www.npmjs.com/package/idna-uts46) is available that normalises and checks names. - -Note that while upper and lower case letters are allowed in names, the UTS46 normalisation process case-folds labels before hashing them, so two names with different case but identical spelling will produce the same namehash. - -Labels and domains may be of any length, but for compatibility with legacy DNS, it is recommended that labels be restricted to no more than 64 characters each, and complete ENS names to no more than 255 characters. For the same reason, it is recommended that labels do not start or end with hyphens, or start with digits. - -## namehash algorithm - -Before being used in ENS, names are hashed using the 'namehash' algorithm. This algorithm recursively hashes components of the name, producing a unique, fixed-length string for any valid input domain. The output of namehash is referred to as a 'node'. - -Pseudocode for the namehash algorithm is as follows: - -``` -def namehash(name): - if name == '': - return '\0' * 32 - else: - label, _, remainder = name.partition('.') - return sha3(namehash(remainder) + sha3(label)) -``` - -Informally, the name is split into labels, each label is hashed. Then, starting with the last component, the previous output is concatenated with the label hash and hashed again. The first component is concatenated with 32 '0' bytes. Thus, 'mysite.swarm' is processed as follows: - -``` -node = '\0' * 32 -node = sha3(node + sha3('swarm')) -node = sha3(node + sha3('mysite')) -``` - -Implementations should conform to the following test vectors for namehash: - - namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000 - namehash('eth') = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae - namehash('foo.eth') = 0xde9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f - -## Registry specification - -The ENS registry contract exposes the following functions: - -```solidity -function owner(bytes32 node) constant returns (address); -``` - -Returns the owner (registrar) of the specified node. - -```solidity -function resolver(bytes32 node) constant returns (address); -``` - -Returns the resolver for the specified node. - -```solidity -function ttl(bytes32 node) constant returns (uint64); -``` - -Returns the time-to-live (TTL) of the node; that is, the maximum duration for which a node's information may be cached. - -```solidity -function setOwner(bytes32 node, address owner); -``` - -Transfers ownership of a node to another registrar. This function may only be called by the current owner of `node`. A successful call to this function logs the event `Transfer(bytes32 indexed, address)`. - -```solidity -function setSubnodeOwner(bytes32 node, bytes32 label, address owner); -``` - -Creates a new node, `sha3(node, label)` and sets its owner to `owner`, or updates the node with a new owner if it already exists. This function may only be called by the current owner of `node`. A successful call to this function logs the event `NewOwner(bytes32 indexed, bytes32 indexed, address)`. - -```solidity -function setResolver(bytes32 node, address resolver); -``` - -Sets the resolver address for `node`. This function may only be called by the owner of `node`. A successful call to this function logs the event `NewResolver(bytes32 indexed, address)`. - -```solidity -function setTTL(bytes32 node, uint64 ttl); -``` - -Sets the TTL for a node. A node's TTL applies to the 'owner' and 'resolver' records in the registry, as well as to any information returned by the associated resolver. -## Resolver specification - -Resolvers may implement any subset of the record types specified here. Where a record types specification requires a resolver to provide multiple functions, the resolver MUST implement either all or none of them. Resolvers MUST specify a fallback function that throws. - -Resolvers have one mandatory function: - -```solidity -function supportsInterface(bytes4 interfaceID) constant returns (bool) -``` - -The `supportsInterface` function is documented in [EIP-165](./eip-165.md), and returns true if the resolver implements the interface specified by the provided 4 byte identifier. An interface identifier consists of the XOR of the function signature hashes of the functions provided by that interface; in the degenerate case of single-function interfaces, it is simply equal to the signature hash of that function. If a resolver returns `true` for `supportsInterface()`, it must implement the functions specified in that interface. - -`supportsInterface` must always return true for `0x01ffc9a7`, which is the interface ID of `supportsInterface` itself. - - Currently standardised resolver interfaces are specified in the table below. - -The following interfaces are defined: - -| Interface name | Interface hash | Specification | -| --- | --- | --- | -| `addr` | 0x3b3b57de | [Contract address](#addr) | -| `name` | 0x691f3431 | #181 | -| `ABI` | 0x2203ab56 | #205 | -| `pubkey` | 0xc8690233 | #619 | - -EIPs may define new interfaces to be added to this registry. - -### Contract Address Interface - -Resolvers wishing to support contract address resources must provide the following function: - -```solidity -function addr(bytes32 node) constant returns (address); -``` - -If the resolver supports `addr` lookups but the requested node does not have an addr record, the resolver MUST return the zero address. - -Clients resolving the `addr` record MUST check for a zero return value, and treat this in the same manner as a name that does not have a resolver specified - that is, refuse to send funds to or interact with the address. Failure to do this can result in users accidentally sending funds to the 0 address. - -Changes to an address MUST trigger the following event: - -```solidity -event AddrChanged(bytes32 indexed node, address a); -``` -# Appendix A: Registry Implementation - -```solidity -contract ENS { - struct Record { - address owner; - address resolver; - uint64 ttl; - } - - mapping(bytes32=>Record) records; - - event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); - event Transfer(bytes32 indexed node, address owner); - event NewResolver(bytes32 indexed node, address resolver); - - modifier only_owner(bytes32 node) { - if(records[node].owner != msg.sender) throw; - _ - } - - function ENS(address owner) { - records[0].owner = owner; - } - - function owner(bytes32 node) constant returns (address) { - return records[node].owner; - } - - function resolver(bytes32 node) constant returns (address) { - return records[node].resolver; - } - - function ttl(bytes32 node) constant returns (uint64) { - return records[node].ttl; - } - - function setOwner(bytes32 node, address owner) only_owner(node) { - Transfer(node, owner); - records[node].owner = owner; - } - - function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { - var subnode = sha3(node, label); - NewOwner(node, label, owner); - records[subnode].owner = owner; - } - - function setResolver(bytes32 node, address resolver) only_owner(node) { - NewResolver(node, resolver); - records[node].resolver = resolver; - } - - function setTTL(bytes32 node, uint64 ttl) only_owner(node) { - NewTTL(node, ttl); - records[node].ttl = ttl; - } -} -``` -# Appendix B: Sample Resolver Implementations -### Built-in resolver - -The simplest possible resolver is a contract that acts as its own name resolver by implementing the contract address resource profile: - -```solidity -contract DoSomethingUseful { - // Other code - - function addr(bytes32 node) constant returns (address) { - return this; - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` - -Such a contract can be inserted directly into the ENS registry, eliminating the need for a separate resolver contract in simple use-cases. However, the requirement to 'throw' on unknown function calls may interfere with normal operation of some types of contract. - -### Standalone resolver - -A basic resolver that implements the contract address profile, and allows only its owner to update records: - -```solidity -contract Resolver { - event AddrChanged(bytes32 indexed node, address a); - - address owner; - mapping(bytes32=>address) addresses; - - modifier only_owner() { - if(msg.sender != owner) throw; - _ - } - - function Resolver() { - owner = msg.sender; - } - - function addr(bytes32 node) constant returns(address) { - return addresses[node]; - } - - function setAddr(bytes32 node, address addr) only_owner { - addresses[node] = addr; - AddrChanged(node, addr); - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` - -After deploying this contract, use it by updating the ENS registry to reference this contract for a name, then calling `setAddr()` with the same node to set the contract address it will resolve to. -### Public resolver - -Similar to the resolver above, this contract only supports the contract address profile, but uses the ENS registry to determine who should be allowed to update entries: - -```solidity -contract PublicResolver { - event AddrChanged(bytes32 indexed node, address a); - event ContentChanged(bytes32 indexed node, bytes32 hash); - - ENS ens; - mapping(bytes32=>address) addresses; - - modifier only_owner(bytes32 node) { - if(ens.owner(node) != msg.sender) throw; - _ - } - - function PublicResolver(address ensAddr) { - ens = ENS(ensAddr); - } - - function addr(bytes32 node) constant returns (address ret) { - ret = addresses[node]; - } - - function setAddr(bytes32 node, address addr) only_owner(node) { - addresses[node] = addr; - AddrChanged(node, addr); - } - - function supportsInterface(bytes4 interfaceID) constant returns (bool) { - return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7; - } - - function() { - throw; - } -} -``` -# Appendix C: Sample Registrar Implementation - -This registrar allows users to register names at no cost if they are the first to request them. - -```solidity -contract FIFSRegistrar { - ENS ens; - bytes32 rootNode; - - function FIFSRegistrar(address ensAddr, bytes32 node) { - ens = ENS(ensAddr); - rootNode = node; - } - - function register(bytes32 subnode, address owner) { - var node = sha3(rootNode, subnode); - var currentOwner = ens.owner(node); - if(currentOwner != 0 && currentOwner != msg.sender) - throw; - - ens.setSubnodeOwner(rootNode, subnode, owner); - } -} -``` +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-137.md diff --git a/EIPS/eip-1380.md b/EIPS/eip-1380.md index 6be8374064b7b8..9f32f1b5737a2e 100644 --- a/EIPS/eip-1380.md +++ b/EIPS/eip-1380.md @@ -11,9 +11,11 @@ requires: 150 --- ## Abstract + Reduce the gas cost for call instructions, when the goal is to run a new instance of the currently loaded contract. ## Motivation + The current gas cost of 700 for all call types (`CALL`, `DELEGATECALL`, `CALLCODE` and `STATICCALL`) does not take into account that a call to a contract itself does not need to perform additional I/O operations, because the current contract code has already been loaded into memory. @@ -26,32 +28,38 @@ must be swapped in and out of the calling functions context. A desired feature i them through `JUMP` requires a bigger effort from the compiler as opposed to being able to use `CALL`s. Using call-to-self provides the guarantee that when making an internal call the function can rely on a clear reset state of memory or context, benefiting both -contract writers and contract consumers against potentially undetetected edge cases were memory could poison the context of the internal function. +contract writers and contract consumers against potentially undetected edge cases were memory could poison the context of the internal function. -Because of the `JUMP` usage for internal functions a smart contract languages are also at risk of reaching the stack depth limit considerbly faster, if nested +Because of the `JUMP` usage for internal functions a smart contract languages are also at risk of reaching the stack depth limit considerably faster, if nested function calls with many in and/or outputs are required. Reducing the gas cost, and thereby incentivising of using call-to-self instead of `JUMP`s for the internal function implementation will also benefit static analyzers and tracers. ## Specification + If `block.number >= FORK_BLKNUM`, then decrease the cost of `CALL`, `DELEGATECALL`, `CALLCODE` and `STATICCALL` from 700 to 40, if and only if, the destination address of the call equals to the address of the caller. ## Rationale + EIP150 has increased the cost of these instructions from 40 to 700 to more fairly charge for loading new contracts from disk, e.g. to reflect the I/O charge more closely. By assuming that 660 is the cost of loading a contract from disk, one can assume that the original 40 gas is a fair cost of creating a new VM instance of an already loaded contract code. ## Backwards Compatibility + This should pose no risk to backwards compatibility. Currently existing contracts should not notice the difference, just see cheaper execution. With EIP150 contract (and language) developers had a lesson that relying on strict gas costs is not feasible as costs may change. The impact of this EIP is even less that of EIP150 because the costs are changing downwards and not upwards. ## Test Cases + TBA ## Implementation + TBA ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-1386.md b/EIPS/eip-1386.md index a83217050eabf2..0eb45ced7e50e3 100644 --- a/EIPS/eip-1386.md +++ b/EIPS/eip-1386.md @@ -1,88 +1,7 @@ --- eip: 1386 -title: Attestation management contract -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1386 -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -Very often, we will need to use Attestations like "Alice lives in Australia" on the blockchain; that is issued by a valid issuer off chain for privacy reasons and is revokable inside a smart contract. - -An issuer can create a smart contract where he revokes multiple attestations in one go by building a bloom filter of all the hashes of the revoked attestations. - -An issuer can also put the validation method in their smart contract that can be called by other smart contracts who need to validate attestations issued by them. This allows each attestor to update their attestation format separately. - -### Purpose - -This ERC provides an interface for attestation issuers to manage their attestation signing keys and the attestations that are issued off chain for actions such as revocation and validation. - -In our draft implementation we include functions to hold cryptographic attestations, change the issuing contracts of attestations, revoke attestations and verify the authenticity of a cryptographic attestation. - -### Example use cases - -Let's say that our friend, Alice, wants to buy a bottle of wine to consume with her friends. She wants to do the order online and have it delivered to her home address whilst paying for it with Ether. - -Alice has a cryptographic attestation from her local road and maritime services who attests to her age, date of birth, country of residence and ability to drive. - -Alice is able to split up this attestation (see merkle tree attestations ERC [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/lib/MerkleTreeAttestation.sol)) and provides only the leaf that states she is over the age of 21. - -Alice goes to buy the wine through the wine vendors smart contract and feeds in the merkle tree attestation proving that she is above 21 and can thus buy the wine, whilst attaching the appropriate amount of ether to complete the purchase. - -The issuer smart contract is able to validate her attestation, check that the issuer contract is valid and capable of performing such an attestation to her age. In this case it would have to be from someone like a driver's licence authority, as attestations to age from a school ID are not of a high enough capacity. - -The wine vendors smart contract validates the attestation, checks the payment amount is correct and credits Alice with the wine tokens she needs to complete the sale and deliver the wine. - -When the wine vendor shows up to her apartment with the wine, there is no need to prove her age again. - -### Draft interface -```solidity -/* each attestation issuer should provide their own verify() for the - * attestations they issued. There are two reasons for this. First, we - * need to leave room for new attestation methods other than the - * Merkle Tree format we are recommending. Second, the validity of the - * attestation may depend on the context that only the attestor - * knows. For example, a ticket as an attestation issued on a - * successful redemption of an American Express credit */ - -contract Issuer { - struct Attestation - { - bytes32[] merklePath; - bool valid; - uint8 v; - bytes32 r; - bytes32 s; - address attestor; - address recipient; - bytes32 salt; - bytes32 key; - bytes32 val; - }` - /* Verify the authenticity of an attestation */ - function verify(Attestation attestation); - function addattestorKey(address newAttestor, string capacity, uint expiry); - - /* this should call the revoke first */ - function replaceKey(address attestorToReplace, string capacity, uint expiry, address newAttestor); - - /* this revokes a single key */ - function removeKey(address attestor); - - /* if the key exists with such capacity and isn't revoked or expired */ - function validateKey(address attestor, string capacity) returns (bool); - - /* revoke an attestation by replace the bloom filter, this helps preserve privacy */ - function revokeAttestations(Bloomfilter b); - -} -``` - -Please click [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/example-james-squire/james-squire.sol) to see a draft implementation of this interface - -### Related ERC's -#1388 #1387 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1386.md diff --git a/EIPS/eip-1387.md b/EIPS/eip-1387.md index 1061ffec26dc8e..cdb744a8ac774f 100644 --- a/EIPS/eip-1387.md +++ b/EIPS/eip-1387.md @@ -1,49 +1,7 @@ --- eip: 1387 -title: Merkle Tree Attestations with Privacy enabled -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1387 -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -It's often needed that an Ethereum smart contract must verify a claim (I live in Australia) attested by a valid attester. - -For example, an ICO contract might require that the participant, Alice, lives in Australia before she participates. Alice's claim of residency could come from a local Justice of the Peace who could attest that "Alice is a resident of Australia in NSW". - -Unlike previous attempts, we assume that the attestation is signed and issued off the blockchain in a Merkle Tree format. Only a part of the Merkle tree is revealed by Alice at each use. Therefore we avoid the privacy problem often associated with issuing attestations on chain. We also assume that Alice has multiple signed Merkle Trees for the same factual claim to avoid her transactions being linkable. - -## Purpose -This ERC provides an interface and reference implementation for smart contracts that need users to provide an attestation and validate it. - -### Draft implementation -```solidity -contract MerkleTreeAttestationInterface { - struct Attestation - { - bytes32[] merklePath; - bool valid; - uint8 v; - bytes32 r; - bytes32 s; - address attester; - address recipient; - bytes32 salt; - bytes32 key; - bytes32 val; - } - - function validate(Attestation attestation) public returns(bool); -} - -``` -### Relevant implementation examples -[Here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/lib/MerkleTreeAttestation.sol) is an example implementation of the MerkleTreeAttestationInterface -[Here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/example-james-squire/james-squire.sol) is an example service which would use such a merkle tree attestation - -### Related ERC's -#1388 #1386 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1387.md diff --git a/EIPS/eip-1388.md b/EIPS/eip-1388.md index ed05a6407d55bc..1d931981050c35 100644 --- a/EIPS/eip-1388.md +++ b/EIPS/eip-1388.md @@ -1,87 +1,7 @@ --- eip: 1388 -title: Attestation Issuers Management List -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/1388 -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-08 +status: Moved --- -### Introduction - -In smart contracts, we will need methods to handle cryptographic attestations to a users identifier or abilities. Let's say we have a real estate agent, KiwiRealtors, that provides an "expression of interest" function though a smart contract and requires the users to provide an attestation that they are a resident of New Zealand or Australia, as a legal requirement. This has actually happened in the New Zealand property market and it is the perfect example of a need to handle such attestations. - -However, it is not practical for a smart contract to explicitly trust an attestation issuer. There are multiple issuers who can provide an attestation to a person's residency - a local Justice of the Peace, the land title office, local police, passport authority etc. We envision a model where the effort to manage the list of qualified issuers is practically outsourced to a list. - -Anyone can publish a list of issuers. Only the most trusted and carefully maintained lists gets popular use. - -### Purpose -This ERC provides a smart contract interface for anyone to manage a list of attestation issuers. A smart contract would explicitly trust a list, and therefore all attestations issued by the issuers on the list. - -### Draft implementation -```solidity - /* The purpose of this contract is to manage the list of attestation - * issuer contracts and their capacity to fulfill requirements - */ - contract ManagedListERC - { - /* a manager is the steward of a list. Only he/she/it can change the - * list by removing/adding attestation issuers to the list. - - * An issuer in the list is represented by their contract - * addresses, not by the attestation signing keys managed by such a - * contract. - */ - struct List - { - string name; - string description; // short description of what the list entails - string capacity; // serves as a filter for the attestation signing keys - /* if a smart contract specifies a list, only attestation issued - * by issuers on that list is accepted. Furthermore, if that - * list has a non-empty capacity, only attestations signed by a - * signing key with that capacity is accepted. */ - - address[] issuerContracts; // all these addresses are contracts, no signing capacity - uint expiry; - } - - // find which list the sender is managing, then add an issuer to it - function addIssuer(address issuerContractAddress) public; - - //return false if the list identified by the sender doesn't have this issuer in the list - function removeIssuer(address issuerContractAddress, List listToRemoveIssuerFrom) public returns(bool); - - /* called by services, e.g. Kiwi Properties or James Squire */ - /* loop through all issuer's contract and execute validateKey() on - * every one of them in the hope of getting a hit, return the - * contract address of the first hit. Note that there is an attack - * method for one issuer to claim to own the key of another which - * is mitigated by later design. */ - //loop through the issuers array, calling validate on the signingKeyOfAttestation - function getIssuerCorrespondingToAttestationKey(bytes32 list_id, address signingKeyOfAttestation) public returns (address); - - /* for simplicity we use sender's address as the list ID, - * accepting these consequences: a) if one user wish to maintain - * several lists with different capacity, he or she must use a - * different sender address for each. b) if the user replaced the - * sender's key, either because he or she suspects the key is - * compromised or that it is lost and reset through special means, - * then the list is still identified by the first sender's - * address. - */ - - function createList(List list) public; - - /* replace list manager's key with the new key */ - function replaceListIndex(List list, address manager) public returns(bool); - - } -``` - -Click [here](https://github.com/alpha-wallet/blockchain-attestation/blob/master/ethereum/trustlist/ManagedList.sol) to see an example implementation of this ERC - -### Related ERC's -#1387 #1386 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1388.md diff --git a/EIPS/eip-1417.md b/EIPS/eip-1417.md index 1bf50edd79b978..1338778eb0dfad 100644 --- a/EIPS/eip-1417.md +++ b/EIPS/eip-1417.md @@ -1,283 +1,7 @@ --- eip: 1417 -title: Poll Standard -author: Chaitanya Potti (@chaitanyapotti), Partha Bhattacharya (@pb25193) -type: Standards Track category: ERC -status: Stagnant -created: 2018-09-16 -requires: 165, 1261 -discussions-to: https://github.com/ethereum/EIPs/issues/1417 +status: Moved --- -## Note to Readers - -1. We have created a couple of implementations of polls for varied use cases. - Please refer to them [here](https://github.com/chaitanyapotti/Voting) - -## Simple Summary - -A standard interface for Polls to be used with EIP-1261 (MVT). - -## Abstract - -The following standard allows for the implementation of a standard API for polls to be used with MVTs (refer [EIP-1261](./eip-1261.md)). The standard provides basic functionality to vote, unvote, tally votes, get voter turnout, and a lot more. The poll standard attempts to modularize blockchain voting by breaking down a poll into 4 crucial building blocks: voterbase qualification, vote weight calculation, vote consequences, and vote tallying. By creating a common interface for polls that have different kinds of building blocks, the poll standard makes it possible to make interactive front end applications which can seamlessly get data from a poll contract in order to bring transparency into consensus and decision making on the blockchain. - -We considered the usage of polls with MVTs because MVTs serve as a permissioning mechanism. The manual permissioning of polls allows for vote weightage functions to take up several shapes and forms. Hence the voterbase function applies several logical checks on the vote sender to confirm that they are member(see EIP 1261) of a certain entity or combination of entities. For the specification of the nature of voting, we define the vote weight function. The vote weight function decides how much of vote share each voter will receive and this can be based on several criteria, some of which are listed below in this article. There are certain kinds of polls that enforce certain consequences on the voter, for example a poll may require a voter to lock in a certain amount of tokens, or require the voter to pay a small fee. These on-chain consequences can be coded into the consequence module of the poll standard. Finally, the last module is where the votes are added. A ballot for each candidate is updated whenever relevant, depending on the vote value, and the corresponding NoV count(number of voters). This module is common for most polls, and is the most straightforward. Polls may be time bound, ie. having a finish time, after which no votes are recorded, or be unbound, such that there is no finish time. The following are some examples of specific polls which leverage the flexibility of the poll standard, and it is possible to come up with several others: - -- Plurality Voting: The simplest form of voting is when you want all eligible voters to have one vote per person. This is the simplest to code, as the vote weight is 1, and there is no vote consequence. The only relevant module here is the voterbase, which can be categorized by one or more MVT contracts. -- Token proportional voting: This kind of a poll is actually possible without the use of a voterbase function, because the vote weight function having token proportionality automatically rules out addresses which don't hold the appropriate ERC - 20/ ERC - 777 token. However the voterbase function may be leveraged to further permission the system and give voting rights only to a fixed subset of token holders. -- Capped Token Proportional Voting: This is a modified version of the previous example, where each voter is given proportional vote share only until a certain limit of token ownership. After exceeding that limit, holding more coins does not add more vote share. This format leverages the voterbase module effectively, disallowing people from spreading their coins across multiple addresses by allowing the admin to control which addresses can vote. -- Delegated Voting: Certain polls may allow voters to delegate their votes to other voters. This is known as delegated voting or liquid democracy. For such a poll, a complicated vote weight function is needed, and a data structure concerning the voterbase is also required. A consequence of voting here would be that a user cannot delegate, and a consequence of delegating is that a user cannot vote. Sample implementation of polls contains an example of this vote scheme. -- Karma Based Voting: A certain form of poll may be based on weightage from digital respect. This digital respect would be like a simple upvote from one member of voterbase to another. A mapping of mappings along with an appropriate vote weight function can serve this purpose. Sample implementation has an example. -- Quadratic voting: A system where each vote is associated with a fee, and the fee is proportional to the square of the vote weight that the voter wants. This can be designed by applying a vote weight based on the transaction message, and then charging a fee in the vote consequence module. - -The poll standard is intended to be a smart contract standard that makes poll deployment flexible, transparent and accessible. - -## Motivation - -A standard interface allows any user or applications to work with any Poll contract on Ethereum. We provide for simple ERC-1417 smart contracts. Additional applications are discussed below. - -This standard is inspired by the lack of governance tools in the blockchain space. Whenever there is a consensus collection exercise, someone goes ahead and deploys some kind of poll, and there is no standard software for accessing the data on the poll. For an end user who is not a developer, this is a real problem. The poll, which might be fully transparent, appears to be completely opaque to a common user who does not understand blockchain. In order for developers to build applications for interacting with and accessing poll data, and for poll deployers to have ready application level support, there must be a standardization of poll interfaces. - -This realization happened while conducting market research on DAICOs. The first ever DAICO, Abyss, had far from optimal user experience, and abysmal transparency. Since then, we have been working on a poll standard. During the process, we came across EIP 1202, the voting standard, and found that the discussion there had already diverged from our thoughts to an extent that it made sense to publish a separate proposal altogether. Some of the benefits brought by the poll standard - EIP 1417 aims to offer some additional benefits. - -1. Modularization: EIP 1417 modularizes the code present in the poll standard into 4 major building blocks based on functionality. These are: voterbase logic, vote weight calculation, vote consequence processing, and tallying module. This makes it easy for developers to change parts of a poll without disrupting other parts, and also helps people understand better, code written in the same format by other people. - -2. Permissioning: Permissioning is an important aspect of polls, and is missing in most poll proposals so far, on the blockchain. For some reason, most blockchain based polls seem to consider token holding as the only way to permission a poll. However this hampers flexibility, and hence our poll standard is leveraging EIP 1261 in order to clear the permissioning hurdle. Not only does it allow for more creative poll structures in terms of vote weightage, but even improves the flexibility in permissioning by allowing developers to combine several entities and read attributes from entities. - -3. Flexibility: The vote weight module of the poll standard can be used effectively to design various kinds of poll contracts which function differently and are suited to different environments. Some examples are quadratic voting, karma voting, delegated voting, token based voting, and one person one vote systems. These schemes are possible due to the separation of voterbase creation and vote weight calculation. - -4. NoV Counts: Several weighted polls have struggled to provide proper transparency because they only show the final result without enough granularity. This is because they do not store the number of voters that have voted for each proposal, and only store the total accrued vote for each option. EIP 1417 solves this by additionally recording number of voters(NoV) in each proposal. This NoV count is redundant in the case of one person one vote, but elsewhere, it is helpful in figuring out concentration of power. This ensures that malicious parties can be traced to a larger extent. - -5. Event Logging: The poll standard logs an event during a successful vote, unsuccessful vote, and a successful unvote. This is being done so that in the event of a malicious admin removing real members or adding fake members, communities can build tools in order to perform advanced audits and simulate results in the absence of the malicious attack. Such advanced features are completely absent in most polls, and hence, it is hard to investigate such polls. - -6. Pollscan.io: The Electus foundation is working on a web based application for accessing and interacting with poll data on the blockchain, it will be deployed on the domain name www.pollscan.io in the coming months. - -All that being said, we are very excited to share our proposal with the community and open up to suggestions in this space. - -### Benefits - -1. Building applications (pollscan.io) on top of a standardized voting interface enables transparency and encourage more DAO/DAICO's to act responsibly in terms of governance -2. Create Action contracts which take actions programmatically based on the result of a poll -3. Allow the compatibility with token standard such as [ERC-20](./eip-20.md) or (./eip-777.md)) and membership standard such as [EIP-1261](./eip-1261.md) -4. Flexibility allows for various voting schemes including but not limited to modern schemes such as PLCR Voting - -### Use-cases: - -Polls are useful in any context of collective decision making, which include but aren't limited to: - -1. Governing public resources, like ponds, playgrounds, streets etc -2. Maintaining fiscal policy in a transparent consensus driven manner -3. Governing crowdfunded projects - refer DAICO, Vitalik Buterin -4. Implementation of Futarchy -5. Decision making in political parties, and municipal corporations -6. Governing expenditure of a cryptocurrency community - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every ERC-1417 compliant contract must implement the `ERC1417` and `ERC165` interfaces** (subject to "caveats" below): - -```solidity -/// @title ERC-1417 Poll Standard -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1417.md -/// Note: the ERC-165 identifier for this interface is 0x4fad898b. -interface IPoll { - /// @dev This emits when a person tries to vote without permissions. Useful for auditing purposes. - /// E.g.: To prevent an admin to revoke permissions; calculate the result had they not been removed. - /// @param _from User who tried to vote - /// @param _to the index of the proposal he voted to - /// @param voteWeight the weight of his vote - event TriedToVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @dev This emits when a person votes successfully - /// @param _from User who successfully voted - /// @param _to the index of the proposal he voted to - /// @param voteWeight the weight of his vote - event CastVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @dev This emits when a person revokes his vote - /// @param _from User who successfully unvoted - /// @param _to the index of the proposal he unvoted - /// @param voteWeight the weight of his vote - event RevokedVote(address indexed _from, uint8 indexed _to, uint voteWeight); - - /// @notice Handles the vote logic - /// @dev updates the appropriate data structures regarding the vote. - /// stores the proposalId against the user to allow for unvote - /// @param _proposalId the index of the proposal in the proposals array - function vote(uint8 _proposalId) external; - - /// @notice Handles the unvote logic - /// @dev updates the appropriate data structures regarding the unvote - function revokeVote() external; - - /// @notice gets the proposal names - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the proposal list - /// @return the list of names of proposals - function getProposals() external view returns (bytes32[]); - - /// @notice returns a boolean specifying whether the user can vote - /// @dev implement logic to enable checks to determine whether the user can vote - /// if using eip-1261, use protocol addresses and interface (IERC1261) to enable checking with attributes - /// @param _to the person who can vote/not - /// @return a boolean as to whether the user can vote - function canVote(address _to) external view returns (bool); - - /// @notice gets the vote weight of the proposalId - /// @dev returns the current cumulative vote weight of a proposal - /// @param _proposalId the index of the proposal in the proposals array - /// @return the cumulative vote weight of the specified proposal - function getVoteTally(uint _proposalId) external view returns (uint); - - /// @notice gets the no. of voters who voted for the proposal - /// @dev use a struct to keep a track of voteWeights and voterCount - /// @param _proposalId the index of the proposal in the proposals array - /// @return the voter count of the people who voted for the specified proposal - function getVoterCount(uint _proposalId) external view returns (uint); - - /// @notice calculates the vote weight associated with the person `_to` - /// @dev use appropriate logic to determine the vote weight of the individual - /// For sample implementations, refer to end of the eip - /// @param _to the person whose vote weight is being calculated - /// @return the vote weight of the individual - function calculateVoteWeight(address _to) external view returns (uint); - - /// @notice gets the leading proposal at the current time - /// @dev calculate the leading proposal at the current time - /// For practical reasons, limit proposal count to 32. - /// @return the index of the proposal which is leading - function winningProposal() external view returns (uint8); - - /// @notice gets the name of the poll e.g.: "Admin Election for Autumn 2018" - /// @dev Set the name in the constructor of the poll - /// @return the name of the poll - function getName() external view returns (bytes32); - - /// @notice gets the type of the Poll e.g.: Token (XYZ) weighted poll - /// @dev Set the poll type in the constructor of the poll - /// @return the type of the poll - function getPollType() external view returns (bytes32); - - /// @notice gets the logic to be used in a poll's `canVote` function - /// e.g.: "XYZ Token | US & China(attributes in erc-1261) | Developers(attributes in erc-1261)" - /// @dev Set the Voterbase logic in the constructor of the poll - /// @return the voterbase logic - function getVoterBaseLogic() external view returns (bytes32); - - /// @notice gets the start time for the poll - /// @dev Set the start time in the constructor of the poll as Unix Standard Time - /// @return start time as Unix Standard Time - function getStartTime() external view returns (uint); - - /// @notice gets the end time for the poll - /// @dev Set the end time in the constructor of the poll as Unix Time or specify duration in constructor - /// @return end time as Unix Standard Time - function getEndTime() external view returns (uint); - - /// @notice returns the list of entity addresses (eip-1261) used for perimissioning purposes. - /// @dev addresses list can be used along with IERC1261 interface to define the logic inside `canVote()` function - /// @return the list of addresses of entities - function getProtocolAddresses() external view returns (address[]); - - /// @notice gets the vote weight against all proposals - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the vote tally list - /// @return the list of vote weights against all proposals - function getVoteTallies() external view returns (uint[]); - - /// @notice gets the no. of people who voted against all proposals - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the vote count list - /// @return the list of voter count against all proposals - function getVoterCounts() external view returns (uint[]); - - /// @notice For single proposal polls, returns the total voterbase count. - /// For multi proposal polls, returns the total vote weight against all proposals - /// this is used to calculate the percentages for each proposal - /// @dev limit the proposal count to 32 (for practical reasons), loop and generate the voter base denominator - /// @return an integer which specifies the above mentioned amount - function getVoterBaseDenominator() external view returns (uint); -} -``` - -### Caveats - -The 0.4.24 Solidity interface grammar is not expressive enough to document the ERC-1417 standard. A contract which complies with ERC-1417 MUST also abide by the following: - -- Solidity issue #3412: The above interfaces include explicit mutability guarantees for each function. Mutability guarantees are, in order weak to strong: `payable`, implicit nonpayable, `view`, and `pure`. Your implementation MUST meet the mutability guarantee in this interface and you MAY meet a stronger guarantee. For example, a `payable` function in this interface may be implemented as nonpayble (no state mutability specified) in your contract. We expect a later Solidity release will allow your stricter contract to inherit from this interface, but a workaround for version 0.4.24 is that you can edit this interface to add stricter mutability before inheriting from your contract. -- Solidity issue #2330: If a function is shown in this specification as `external` then a contract will be compliant if it uses `public` visibility. As a workaround for version 0.4.24, you can edit this interface to switch to `public` before inheriting from your contract. - -_If a newer version of Solidity allows the caveats to be expressed in code, then this EIP MAY be updated and the caveats removed, such will be equivalent to the original specification._ - -## Rationale - -As the poll standard is built with the intention of creating a system that allows for more transparency and accessibility of governance data, the design choices in the poll standard are driven by this motivator. In this section we go over some of the major design choices, and why these choices were made: - -1. Event logging: The logic behind maintaining event logs in the cases of: - - - Cast Vote - - Unvote - - Failed Vote - is to ensure that in the event of a manipulated voterbase, simple off chain checks can be performed to audit the integrity of the poll result. - -2. No poll finish trigger: There was a consideration of adding functions in the poll which execute after completion of the poll to carry out some pre-decided logic. However this was deemed to be unnecessary - because such an action can be deployed in a separate contract which simply reads the result of a given poll, and against the spirit of modularity, because no actions can be created after the poll has been deployed. Also, such functions would not be able to combine the results of polls, and definitely would not fit into polls that do not have an end time. - -3. Allow for unbound polls: The poll standard, unlike other voting standard proposals, does not force polls to have an end time. This becomes relevant in some cases where the purpose of a poll is to have a live register of ongoing consensus. Some other use cases come into picture when you want to deploy a set of action contracts which read from the poll, and want to be able to execute the action contract whenever a poll reaches a certain threshold, rather than waiting for the end of the poll. - -4. Modularization: There have been opinions in the Ethereum community that there cannot exist a voting standard, because voting contracts can be of various types, and have several shapes and forms. However we disagree, and make the case that modularization is the solution. While different polls may need different logic, they all need consistent end points. All polls need to give out results along with headcounts, all polls should have event logs, all polls should be examinable with frontend tools, and so on. The poll standard is not a statement saying “all polls should be token based” or any such specific system. However the poll standard is a statement saying that all polls should have a common access and modification protocol - this will enable more apps to include governance without having to go through the trouble of making customers start using command line. - -Having explained our rationale, we are looking forward to hearing from the community some thoughts on how this can be made more useful or powerful. - -**Gas and Complexity** (regarding the enumeration for proposal count) - -This specification contemplates implementations that contain a sample of 32 proposals (max up to blockgaslimit). If your application is able to grow and needs more than 32 proposals, then avoid using for/while loops in your code. These indicate your contract may be unable to scale and gas costs will rise over time without bound - -**Privacy** - -Personal information: The standard does not put any personal information on to the blockchain, so there is no compromise of privacy in that respect. - -**Community Consensus** - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Test Cases - -Voting Standard includes test cases written using Truffle. - -## Implementations - -Voting Standard -- a reference implementation - -- MIT licensed, so you can freely use it for your projects -- Includes test cases -- Also available as a npm package - npm i electusvoting - -## References - -**Standards** - -- [EIP-20: ERC-20 Token Standard (a.k.a. ERC-20)](./eip-20.md) -- [EIP-165: Standard Interface Detection](./eip-165.md) -- [EIP-721: Non-Fungible Token Standard(a.k.a. ERC-721)](./eip-721.md) -- [ERC-1261 MV Token Standard](./eip-1261.md) -- [RFC 2119 Key words for use in RFCs to Indicate Requirement Levels](https://www.ietf.org/rfc/rfc2119.txt) - -**Issues** - -1. The Original ERC-1417 Issue. https://github.com/ethereum/eips/issues/1417 -1. Solidity Issue \#2330 -- Interface Functions are Axternal. https://github.com/ethereum/solidity/issues/2330 -1. Solidity Issue \#3412 -- Implement Interface: Allow Stricter Mutability. https://github.com/ethereum/solidity/issues/3412 -1. Solidity Issue \#3419 -- Interfaces Can't Inherit. https://github.com/ethereum/solidity/issues/3419 - -**Discussions** - -1. ERC-1417 (announcement of first live discussion). https://github.com/ethereum/eips/issues/1417 - -**Voting Implementations and Other Projects** - -- [Voting Implementations](https://github.com/chaitanyapotti/Voting) - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1417.md diff --git a/EIPS/eip-1418.md b/EIPS/eip-1418.md index f0df952197267e..ac932f21780b58 100644 --- a/EIPS/eip-1418.md +++ b/EIPS/eip-1418.md @@ -1,10 +1,10 @@ --- eip: 1418 title: Blockchain Storage Rent Payment -description: At each block, deduct an amount of value from every account based on the quantity of storage used by that account. +description: At each block, deduct value from every account based on the quantity of storage used by that account. author: William Entriken (@fulldecent) discussions-to: https://ethereum-magicians.org/t/eip-1418-storage-rent/10737 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2018-09-16 @@ -13,7 +13,7 @@ requires: 1559 ## Abstract -At each block, deduct an amount of value or rent from every account based on the quantity of storage used by that account. +At each block, deduct an amount of value ("rent") from every account based on the quantity of storage used by that account. ## Motivation @@ -23,7 +23,7 @@ Ethereum is a public utility and we are underpricing the long-term costs of stor **Updated transaction type** -[EIP-1559](./eip-1559.md) transaction type 2 is updated so that clients can send a contract's code as part of a transaction, just the same way as now how clients can send state variables. +A new transaction type is introduced. Whereas [EIP-1559](./eip-1559.md) introduced warm access for contract state, this new type introduces warm access for contract code. **New state variables (per account)** @@ -39,7 +39,7 @@ Ethereum is a public utility and we are underpricing the long-term costs of stor **New opcodes** * **`RENTBALANCE(address)`** -- G_BALANCE -- Similar to `BALANCE` - * This returns the logical `σ[a]_rent` value which is defined to reduce each block. It is possible for the implementation to calculate this value using the recommended implementation variables, rather than storing an updating `σ[a]_rent` every block for every account. + * This returns the logical `σ[a]_rent` value which is defined to reduce each block. It is possible for the implementation to calculate this value using the recommended implementation variables, rather than storing and updating `σ[a]_rent` every block for every account. * **`SENDRENT(address, amount)`** -- G_BASE -- Convert value to rent and send to account 1. `σ[account]_rent` += amount 2. `σ[msg.sender]_balance` -= amount @@ -69,19 +69,20 @@ END PAYRENT * **`SSTORE(account, key, value)`** * Perform PAYRENT(account) - * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless the transaction includes this storage key in EIP-1559 type 2 transaction. + * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proofs are included to validate the old storage root and calculate the new root. * Do normal SSTORE operation - * If the old value was zero for this [account, key] and the new value is non-zero, then `σ[account]_storageWord++` + * If the old value was zero for this [account, key] and the new value is non-zero, then `σ[account]_storageWords++` * If the old value was non-zero for this [account, key] and the new value is zero, then `σ[account]_storageWords--`, and if the result is negative then set to zero * **`SLOAD(account, key)`** - * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless the transaction includes this storage key in EIP-1559 type 2 transaction. + * If `account` is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proofs are included to validate the existing storage root and the existing storage value. * Do normal SLOAD operation. * **`CALL (and derivatives)`** - * If the target block is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless the transaction includes this account's code in EIP-1559 type 2 extended transaction. + * If the target block is evicted (i.e. `NUMBER` > `σ[account]_rentEvictBlock`) then transaction fails unless using the new transaction type and sufficient proof is included to validate the existing code. * Do normal CALL operation * **`CREATE`** * Set σ[account]_rentLastPaid = NUMBER * Do normal CREATE operation + * `σ[account]_storageWord = 0` * Note: it is possible there is a pre-existing rent balance here **New built-in contract** @@ -90,6 +91,22 @@ END PAYRENT * This is a convenience for humans to send Ether from their accounts and turn it into rent. Note that simple accounts (CODESIZE == 0) cannot call arbitrary opcodes, they can only call CREATE or CALL. * The gas cost of PAYRENT will be 10,000 or lower if possible. +**Calculating `σ[account]_storageWord` for existing accounts** + +DRAFT... + +It is not an acceptable upgrade if on the fork block it is necessary for only archive nodes to participate which know the full storage amount for each account. + +An acceptable upgrade will be if the required `σ[account]_storageWord` can be calculated (or estimated) incrementally based on new transaction activity. + +DRAFT: I think it is possible to make such an acceptable upgrade using an unbiased estimator + +* add one bit of storage per `SSTORE` for legacy accounts on the first access of a given key +* add log(n) bits for each trie level +* assume that storage keys are a random variable + +To think more about... + **No changes to current opcode gas costs.** ## Rationale @@ -120,6 +137,8 @@ But the contract can spend all of its value. By maintaining a separate rent and value balance, this allows people to contribute to the rent while being confident that this is allowing the contract to stay around. +NOTE: cloning. With this EIP, it may become feasible to allow storage cloning. Yes really. Because the new clone will be paying rent. See other EIP, I think made by Augur team. + ### Economics & constants An `SSTORE` executed in 2015 cost 20,000 gas and has survived about 6 million blocks. The gas price has been around 1 ~ 50 Gwei. So basically 4,000 Wei per block per word so far. Maybe storing an account is 10 times more intensive than storing a word. But actually `G_transaction` is 21,000 and `G_sstore` is 20,000 so these are similar and they can both create new accounts / words. @@ -167,9 +186,10 @@ Many smart contracts allow anybody to use an arbitrary amount of storage in them Copyright and related rights waived via CC0. + --> diff --git a/EIPS/eip-1438.md b/EIPS/eip-1438.md index 547724516af113..3f46c40d2adf45 100644 --- a/EIPS/eip-1438.md +++ b/EIPS/eip-1438.md @@ -1,142 +1,7 @@ --- eip: 1438 -title: dApp Components (avatar) & Universal Wallet -author: Jet Lim (@Nitro888) -discussions-to: https://ethresear.ch/t/avatar-system-and-universal-wallet-for-ethereum-address/3473 -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-21 +status: Moved --- -## Simple Summary -Contracts are open source based. And most developers use the public contracts at the start of the project to modify or simply include them. This is project-oriented centralized development and I think it is a waste of resources. Therefore, we propose to make dApp or contracts component-ready for use in other services. - -## Abstract -There have been suggestions for modified tokens based on erc20, but since many tokens have already been built on erc20, it is necessary to increase the utilization of already developed erc20 tokens. Therefore, we propose a universal wallet that can use erc20 tokens universally. We also propose a component dApp that allows you to create and save your avatar (& social badge system), and use it immediately in other services. All of the dApps suggested in this document are based on decentralized development and use that anyone can create and participate in. - -## Motivation -While many projects are under development in an open source way, they are simply adding and deploy with open sources to their projects. This means that you are developing a centralized service that uses your own dApp-generated information on your own. In order to improve the block chain ecosystem, all resources created by dApp and placed in the public block chain must be reusable in another dApp. This means that you can enhance your service by exchanging the generated information with other dApp. Likewise, ERC20 Tokens require Universal Wallet standards to be easy to use for direct transactions. - -### Seeds for improvement of the blockchain ecosystem. -- Synergy - With other dApps and resources. -- Enhanced interface - For ERC20 tokens. -- Easy & Decentralized - Everyone should be able to add to their services easily, without censorship. - - -#### The following avatar store, badge system, and universal wallet are kind of examples about component dApp. -![intro](/assets/eip-1438/intro.png) - -## Specification -### 1. Avatar -#### 1.1. Avatar Shop -- The avatar store is created after ERC20 currency is set. -- You can customize asset category & viewer script. - -#### 1.2. Upload asset & user data -The avatar's information & assets are stored in the event log part of the block chain. -- Assets are SVG format. (compressed with gzip) -- avatar information data is json (compressed with msgpack) - -![avatar](/assets/eip-1438/avatar.png) -** The avatar assets from [Avataaars](https://github.com/fangpenlin/avataaars) developed by [Fang-Pen Lin](https://twitter.com/fangpenlin), the original avatar is designed by [Pablo Stanley](https://twitter.com/pablostanley). - -### 2. Universal Wallet -![wallet](/assets/eip-1438/wallet.png) -#### 2.1. ERC20 interface -``` js -contract ERC20Interface { - function totalSupply() public constant returns (uint); - function balanceOf(address tokenOwner) public constant returns (uint balance); - function allowance(address tokenOwner, address spender) public constant returns (uint remaining); - function transfer(address to, uint tokens) public returns (bool success); - function approve(address spender, uint tokens) public returns (bool success); - function transferFrom(address from, address to, uint tokens) public returns (bool success); - - event Transfer(address indexed from, address indexed to, uint tokens); - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); -} -``` - -#### 2.2. Fixed ERC20 contract for receive approval and execute function in one call -``` js -function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { - allowed[msg.sender][spender] = tokens; - emit Approval(msg.sender, spender, tokens); - ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); - return true; -} -``` - -#### 2.3. And ApproveAndCallFallBack contract for Fixed ERC20. -However, many ERC20 tokens are not prepared. -``` js -contract ApproveAndCallFallBack { - function receiveApproval(address from, uint256 tokens, address token, bytes data) public; -} -``` -#### 2.4. Universal Wallet -We propose a Universal Wallet to solve this problem. - -``` js -contract UniversalWallet is _Base { - - constructor(bytes _msgPack) _Base(_msgPack) public {} - function () public payable {} - - //------------------------------------------------------- - // erc20 interface - //------------------------------------------------------- - function balanceOf(address _erc20) public constant returns (uint balance) { - if(_erc20==address(0)) - return address(this).balance; - return _ERC20Interface(_erc20).balanceOf(this); - } - function transfer(address _erc20, address _to, uint _tokens) onlyOwner public returns (bool success) { - require(balanceOf(_erc20)>=_tokens); - if(_erc20==address(0)) - _to.transfer(_tokens); - else - return _ERC20Interface(_erc20).transfer(_to,_tokens); - return true; - } - function approve(address _erc20, address _spender, uint _tokens) onlyOwner public returns (bool success) { - require(_erc20 != address(0)); - return _ERC20Interface(_erc20).approve(_spender,_tokens); - } - - //------------------------------------------------------- - // pay interface - //------------------------------------------------------- - function pay(address _store, uint _tokens, uint256[] _options) onlyOwner public { - address erc20 = _ApproveAndCallFallBack(_store).erc20(); - address spender = _ApproveAndCallFallBack(_store).spender(); - if(erc20 == address(0)) { - transfer(erc20,spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_options); - } else { - _ERC20Interface(erc20).approve(spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_options); - } - } - function pay(address _store, uint _tokens, bytes _msgPack) onlyOwner public { - address erc20 = _ApproveAndCallFallBack(_store).erc20(); - address spender = _ApproveAndCallFallBack(_store).spender(); - if(erc20 == address(0)) { - transfer(erc20,spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_msgPack); - } else { - _ERC20Interface(erc20).approve(spender,_tokens); - _ApproveAndCallFallBack(_store).receiveApproval(_msgPack); - } - } -} -``` - -## Test Cases -- https://www.nitro888.com -- https://github.com/Nitro888/nitro888.github.io -- https://github.com/Nitro888/dApp-Alliance - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1438.md diff --git a/EIPS/eip-1444.md b/EIPS/eip-1444.md index 4ee0142325e876..4c40d99448fcd6 100644 --- a/EIPS/eip-1444.md +++ b/EIPS/eip-1444.md @@ -1,322 +1,7 @@ --- eip: 1444 -title: Localized Messaging with Signal-to-Text -author: Brooklyn Zelenka (@expede), Jennifer Cooper (@jenncoop) -discussions-to: https://ethereum-magicians.org/t/eip-1444-localized-messaging-with-signal-to-text/ -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-23 +status: Moved --- -## Simple Summary - -A method of converting machine codes to human-readable text in any language and phrasing. - -## Abstract - -An on-chain system for providing user feedback by converting machine-efficient codes into human-readable strings in any language or phrasing. The system does not impose a list of languages, but rather lets users create, share, and use the localizated text of their choice. - -## Motivation - -There are many cases where an end user needs feedback or instruction from a smart contact. Directly exposing numeric codes does not make for good UX or DX. If Ethereum is to be a truly global system usable by experts and lay persons alike, systems to provide feedback on what happened during a transaction are needed in as many languages as possible. - -Returning a hard-coded string (typically in English) only serves a small segment of the global population. This standard proposes a method to allow users to create, register, share, and use a decentralized collection of translations, enabling richer messaging that is more culturally and linguistically diverse. - -There are several machine efficient ways of representing intent, status, state transition, and other semantic signals including booleans, enums and [ERC-1066 codes](./eip-1066.md). By providing human-readable messages for these signals, the developer experience is enhanced by returning easier to consume information with more context (ex. `revert`). End user experience is enhanced by providing text that can be propagated up to the UI. - -## Specification - -### Contract Architecture - -Two types of contract: `LocalizationPreferences`, and `Localization`s. - -The `LocalizationPreferences` contract functions as a proxy for `tx.origin`. - -```diagram - +--------------+ - | | - +------> | Localization | - | | | - | +--------------+ - | - | -+-----------+ +-------------------------+ | +--------------+ -| | | | <------+ | | -| Requestor | <------> | LocalizationPreferences | <-------------> | Localization | -| | | | <------+ | | -+-----------+ +-------------------------+ | +--------------+ - | - | - | +--------------+ - | | | - +------> | Localization | - | | - +--------------+ -``` - -### `Localization` - -A contract that holds a simple mapping of codes to their text representations. - -```solidity -interface Localization { - function textFor(bytes32 _code) external view returns (string _text); -} -``` - -#### `textFor` - -Fetches the localized text representation. - -```solidity -function textFor(bytes32 _code) external view returns (string _text); -``` - -### `LocalizationPreferences` - -A proxy contract that allows users to set their preferred `Localization`. Text lookup is delegated to the user's preferred contract. - -A fallback `Localization` with all keys filled MUST be available. If the user-specified `Localization` has not explicitly set a loalization (ie. `textFor` returns `""`), the `LocalizationPreferences` MUST redelegate to the fallback `Localization`. - -```solidity -interface LocalizationPreferences { - function set(Localization _localization) external returns (bool); - function textFor(bytes32 _code) external view returns (bool _wasFound, string _text); -} -``` - -#### `set` - -Registers a user's preferred `Localization`. The registering user SHOULD be considered `tx.origin`. - -```solidity -function set(Localization _localization) external; -``` - -#### `textFor` - -Retrieve text for a code found at the user's preferred `Localization` contract. - -The first return value (`bool _wasFound`) represents if the text is available from that `Localization`, or if a fallback was used. If the fallback was used in this context, the `textFor`'s first return value MUST be set to `false`, and is `true` otherwise. - -```solidity -function textFor(bytes32 _code) external view returns (bool _wasFound, string _text); -``` - -### String Format - -All strings MUST be encoded as [UTF-8](https://www.ietf.org/rfc/rfc3629.txt). - -```solidity -"Špeĉiäl chârãçtérs are permitted" -"As are non-Latin characters: アルミ缶の上にあるみかん。" -"Emoji are legal: 🙈🙉🙊🎉" -"Feel free to be creative: (ノ◕ヮ◕)ノ*:・゚✧" -``` - -### Templates - -Template strings are allowed, and MUST follow the [ANSI C `printf`](https://pubs.opengroup.org/onlinepubs/009696799/utilities/printf.html) conventions. - -```solidity -"Satoshi's true identity is %s" -``` - -Text with 2 or more arguments SHOULD use the POSIX parameter field extension. - -```solidity -"Knock knock. Who's there? %1$s. %1$s who? %2$s!" -``` - -## Rationale - -### `bytes32` Keys - -`bytes32` is very efficient since it is the EVM's base word size. Given the enormous number of elements (card(A) > 1.1579 × 1077), it can embed nearly any practical signal, enum, or state. In cases where an application's key is longer than `bytes32`, hashing that long key can map that value into the correct width. - -Designs that use datatypes with small widths than `bytes32` (such as `bytes1` in [ERC-1066](./eip-1066.md)) can be directly embedded into the larger width. This is a trivial one-to-one mapping of the smaller set into the the larger one. - -### Local vs Globals and Singletons - -This spec has opted to not _force_ a single global registry, and rather allow any contract and use case deploy their own system. This allows for more flexibility, and does not restrict the community for opting to use singleton `LocalizationPreference` contracts for common use cases, share `Localization`s between different proxys, delegate translations between `Localization`s, and so on. - -There are many practical uses of agreed upon singletons. For instance, translating codes that aim to be fairly universal and integrated directly into the broader ecosystem (wallets, frameworks, debuggers, and the like) will want to have a single `LocalizationPreference`. - -Rather the dispersing several `LocalizationPreference`s for different use cases and codes, one could imagine a global "registry of registries". While this approach allows for a unified lookups of all translations in all use cases, it is antithetical to the spirit of decentralization and freedom. Such a system also increases the lookup complexity, places an onus on getting the code right the first time (or adding the overhead of an upgradable contract), and need to account for use case conflicts with a "unified" or centralized numbering system. Further, lookups should be lightweight (especially in cases like looking up revert text). - -For these reasons, this spec chooses the more decentralized, lightweight, free approach, at the cost of on-chain discoverability. A registry could still be compiled, but would be difficult to enforce, and is out of scope of this spec. - -### Off Chain Storage - -A very viable alternative is to store text off chain, with a pointer to the translations on-chain, and emit or return a `bytes32` code for another party to do the lookup. It is difficult to guarantee that off-chain resources will be available, and requires coordination from some other system like a web server to do the code-to-text matching. This is also not compatible with `revert` messages. - -### ASCII vs UTF-8 vs UTF-16 - -UTF-8 is the most widely used encoding at time of writing. It contains a direct embedding of ASCII, while providing characters for most natural languages, emoji, and special characters. - -Please see the [UTF-8 Everywhere Manifesto](https://utf8everywhere.org/) for more information. - -### When No Text is Found - -Returning a blank string to the requestor fully defeats the purpose of a localization system. The two options for handling missing text are: - -1. A generic "text not found" message in the preferred language -2. The actual message, in a different language - -#### Generic Option - -This designed opted to not use generic fallback text. It does not provide any useful information to the user other than to potentially contact the `Localization` maintainer (if one even exists and updating is even possible). - -#### Fallback Option - -The design outlined in this proposal is to providing text in a commonly used language (ex. English or Mandarin). First, this is the language that will be routed to if the user has yet to set a preference. Second, there is a good chance that a user may have _some_ proficiency with the language, or at least be able to use an automated translation service. - -Knowing that the text fell back via `textFor`s first return field boolean is _much_ simpler than attempting language detection after the fact. This information is useful for certain UI cases. for example where there may be a desire to explain why localization fell back. - -### Decentralized Text Crowdsourcing - -In order for Ethereum to gain mass adoption, users must be able to interact with it in the language, phrasing, and level of detail that they are most comfortable with. Rather than imposing a fixed set of translations as in a traditional, centralized application, this EIP provides a way for anyone to create, curate, and use translations. This empowers the crowd to supply culturally and linguistically diverse messaging, leading to broader and more distributed access to information. - -### `printf`-style Format Strings - -C-style `printf` templates have been the de facto standard for some time. They have wide compatibility across most languages (either in standard or third-party libraries). This makes it much easier for the consuming program to interpolate strings with low developer overhead. - -#### Parameter Fields - -The POSIX parameter field extension is important since languages do not share a common word order. Parameter fields enable the reuse and rearrangement of arguments in different localizations. - -```solidity -("%1$s is an element with the atomic number %2$d!", "Mercury", 80); -// => "Mercury is an element with the atomic number 80!" -``` - -#### Simplified Localizations - -Localization text does not require use of all parameters, and may simply ignore values. This can be useful for not exposing more technical information to users that would otherwise find it confusing. - -```ruby -#!/usr/bin/env ruby - -sprintf("%1$s é um elemento", "Mercurio", 80) -# => "Mercurio é um elemento" -``` - -```clojure -#!/usr/bin/env clojure - -(format "Element #%2$s" "Mercury" 80) -;; => Element #80 -``` - -### Interpolation Strategy - -Please note that it is highly advisable to return the template string _as is_, with arguments as multiple return values or fields in an `event`, leaving the actual interpolation to be done off chain. - - -```solidity -event AtomMessage { - bytes32 templateCode; - bytes32 atomCode; - uint256 atomicNumber; -} -``` - -```javascript -#!/usr/bin/env node - -var printf = require('printf'); - -const { returnValues: { templateCode, atomCode, atomicNumber } } = eventResponse; - -const template = await AppText.textFor(templateCode); -// => "%1$s ist ein Element mit der Ordnungszahl %2$d!" - -const atomName = await PeriodicTableText.textFor(atomCode); -// => "Merkur" - -printf(template, atomName, 80); -// => "Merkur ist ein Element mit der Ordnungszahl 80!" -``` - -### Unspecified Behaviour - -This spec does not specify: - -* Public or private access to the default `Localization` -* Who may set text - * Deployer - * `onlyOwner` - * Anyone - * Whitelisted users - * and so on -* When text is set - * `constructor` - * Any time - * Write to empty slots, but not overwrite existing text - * and so on - -These are intentionally left open. There are many cases for each of these, and restricting any is fully beyond the scope of this proposal. - -## Implementation - -```solidity -pragma solidity ^0.4.25; - -contract Localization { - mapping(bytes32 => string) private dictionary_; - - constructor() public {} - - // Currently overwrites anything - function set(bytes32 _code, string _message) external { - dictionary_[_code] = _message; - } - - function textFor(bytes32 _code) external view returns (string _message) { - return dictionary_[_code]; - } -} - -contract LocalizationPreference { - mapping(address => Localization) private registry_; - Localization public defaultLocalization; - - bytes32 private empty_ = keccak256(abi.encodePacked("")); - - constructor(Localization _defaultLocalization) public { - defaultLocalization = _defaultLocalization; - } - - function set(Localization _localization) external returns (bool) { - registry_[tx.origin] = _localization; - return true; - } - - function get(bytes32 _code) external view returns (bool, string) { - return get(_code, tx.origin); - } - - // Primarily for testing - function get(bytes32 _code, address _who) public view returns (bool, string) { - string memory text = getLocalizationFor(_who).textFor(_code); - - if (keccak256(abi.encodePacked(text)) != empty_) { - return (true, text); - } else { - return (false, defaultLocalization.textFor(_code)); - } - } - - function getLocalizationFor(address _who) internal view returns (Localization) { - if (Localization(registry_[_who]) == Localization(0)) { - return Localization(defaultLocalization); - } else { - return Localization(registry_[tx.origin]); - } - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1444.md diff --git a/EIPS/eip-145.md b/EIPS/eip-145.md index f2bfed54a325fc..be0aca3e57f1ee 100644 --- a/EIPS/eip-145.md +++ b/EIPS/eip-145.md @@ -1,17 +1,14 @@ --- eip: 145 title: Bitwise shifting instructions in EVM +description: To Provide native bitwise shifting with cost on par with other arithmetic operations. author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast) +status: Final type: Standards Track category: Core -status: Final created: 2017-02-13 --- -## Simple Summary - -To provide native bitwise shifting with cost on par with other arithmetic operations. - ## Abstract Native bitwise shifting instructions are introduced, which are more efficient processing wise on the host and are cheaper to use by a contract. @@ -33,6 +30,7 @@ The `SHL` instruction (shift left) pops 2 values from the stack, first `arg1` an ``` Notes: + - The value (`arg2`) is interpreted as an unsigned number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0. @@ -47,6 +45,7 @@ floor(arg2 / 2^arg1) ``` Notes: + - The value (`arg2`) is interpreted as an unsigned number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0. @@ -61,6 +60,7 @@ floor(arg2 / 2^arg1) ``` Notes: + - The value (`arg2`) is interpreted as a signed number. - The shift amount (`arg1`) is interpreted as an unsigned number. - If the shift amount (`arg1`) is greater or equal 256 the result is 0 if `arg2` is non-negative or -1 if `arg2` is negative. @@ -70,7 +70,7 @@ The cost of the shift instructions is set at `verylow` tier (3 gas). ## Rationale -Instruction operands were chosen to fit the more natural use case of shifting a value already on the stack. This means the operand order is swapped compared to most arithmetic insturctions. +Instruction operands were chosen to fit the more natural use case of shifting a value already on the stack. This means the operand order is swapped compared to most arithmetic instructions. ## Backwards Compatibility @@ -87,6 +87,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -94,6 +95,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000002 ``` + 3. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0xff @@ -101,6 +103,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x8000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x0100 @@ -108,6 +111,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 5. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x0101 @@ -115,6 +119,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 6. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -122,6 +127,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -129,6 +135,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -136,6 +143,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x8000000000000000000000000000000000000000000000000000000000000000 ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -143,6 +151,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 10. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -150,6 +159,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 11. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -158,7 +168,6 @@ The newly introduced instructions have no effect on bytecode created in the past 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe ``` - ### `SHR` (logical shift right) 1. ``` @@ -168,6 +177,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -175,6 +185,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 3. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -182,6 +193,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x4000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0xff @@ -189,6 +201,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 5. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0100 @@ -196,6 +209,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 6. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0101 @@ -203,6 +217,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -210,6 +225,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -217,6 +233,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -224,6 +241,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 10. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -231,6 +249,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 11. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -248,6 +267,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 2. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000001 PUSH 0x01 @@ -255,6 +275,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 3. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -262,6 +283,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xc000000000000000000000000000000000000000000000000000000000000000 ``` + 4. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0xff @@ -269,6 +291,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 5. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0100 @@ -276,6 +299,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 6. ``` PUSH 0x8000000000000000000000000000000000000000000000000000000000000000 PUSH 0x0101 @@ -283,6 +307,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 7. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x00 @@ -290,6 +315,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 8. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x01 @@ -297,6 +323,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 9. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -304,6 +331,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 10. ``` PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -311,6 +339,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ``` + 11. ``` PUSH 0x0000000000000000000000000000000000000000000000000000000000000000 PUSH 0x01 @@ -318,6 +347,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 12. ``` PUSH 0x4000000000000000000000000000000000000000000000000000000000000000 PUSH 0xfe @@ -325,6 +355,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 13. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xf8 @@ -332,6 +363,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x000000000000000000000000000000000000000000000000000000000000007f ``` + 14. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xfe @@ -339,6 +371,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000001 ``` + 15. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0xff @@ -346,6 +379,7 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` + 16. ``` PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff PUSH 0x0100 @@ -353,22 +387,25 @@ The newly introduced instructions have no effect on bytecode created in the past --- 0x0000000000000000000000000000000000000000000000000000000000000000 ``` - - -## Implementation + +### Implementation Client support: + - cpp-ethereum: https://github.com/ethereum/cpp-ethereum/pull/4054 Compiler support: + - Solidity/LLL: https://github.com/ethereum/solidity/pull/2541 -## Tests +### Tests Sources: + - https://github.com/ethereum/tests/tree/develop/src/GeneralStateTestsFiller/stShift Filled Tests: + - https://github.com/ethereum/tests/tree/develop/GeneralStateTests/stShift - https://github.com/ethereum/tests/tree/develop/BlockchainTests/GeneralStateTests/stShift diff --git a/EIPS/eip-1450.md b/EIPS/eip-1450.md index 4e6e0daae175d7..9650ebb2ee5350 100644 --- a/EIPS/eip-1450.md +++ b/EIPS/eip-1450.md @@ -1,326 +1,7 @@ --- eip: 1450 -title: ERC-1450 A compatible security token for issuing and trading SEC-compliant securities -author: John Shiple (@johnshiple), Howard Marks , David Zhang -discussions-to: https://ethereum-magicians.org/t/erc-proposal-ldgrtoken-a-compatible-security-token-for-issuing-and-trading-sec-compliant-securities/1468 -status: Stagnant -type: Standards Track category: ERC -created: 2018-09-25 +status: Moved --- -# ERC-1450 - A compatible security token for issuing and trading SEC-compliant securities - -## Simple Summary -`ERC-1450` is an `ERC-20` compatible token that enables issuing tokens representing securities that are required to comply with one or more of the following [Securities Act Regulations: Regulation Crowdfunding, Regulation D, and Regulation A](https://www.sec.gov/smallbusiness/exemptofferings). - -## Abstract -`ERC-1450` facilitates the recording of ownership and transfer of securities sold in compliance with the [Securities Act Regulations CF, D and A](https://www.sec.gov/smallbusiness/exemptofferings). The issuance and trading of securities is subject to the Securities Exchange Commission (SEC) and specific U.S. state blue sky laws and regulations. - -`ERC-1450` manages securities ownership during issuance and trading. The Issuer is the only role that should create a `ERC-1450` and assign the RTA. The RTA is the only role that is allowed to execute `ERC-1450`’s `mint`, `burnFrom`, and `transferFrom` functions. No role is allowed to execute `ERC-1450`’s `transfer` function. - -## Motivation -With the advent of the [JOBS Act](https://www.sec.gov/spotlight/jobs-act.shtml) in 2012 and the launch of Regulation Crowdfunding and the amendments to Regulation A and Regulation D in 2016, there has been an expansion in the exemptions available to Issuers and Investors to sell and purchase securities that have not been "registered" with the SEC under the Securities Act of 1933. - -There are currently no token standards that expressly facilitate conformity to securities law and related regulations. ERC-20 tokens do not support the regulated roles of Funding Portal, Broker Dealer, RTA, and Investor and do not support the [Bank Secrecy Act/USA Patriot Act KYC and AML requirements](https://www.occ.treas.gov/topics/compliance-bsa/bsa/index-bsa.html). Other improvements (notably [EIP-1404 (Simple Restricted Token Standard)](https://github.com/ethereum/EIPs/issues/1404) have tried to tackle KYC and AML regulatory requirement. This approach is novel because the RTA is solely responsible for performing KYC and AML and should be solely responsible for `transferFrom`, `mint`, and `burnFrom`. - -## Specification -`ERC-1450` extends `ERC-20`. - -### `ERC-1450` -`ERC-1450` requires that only the Issuer can create a token representing the security that only the RTA manages. Instantiating the `ERC-1450` requires the `Owned` and `IssuerControlled` modifiers, and only the Issuer should execute the `ERC-1450` constructor for a compliant token. `ERC-1450` extends the general `Ownable` modifier to describe a specific subset of owners that automate and decentralize compliance through the contract modifiers `Owned` and `IssuerControlled` and the function modifiers `onlyOwner` and `onlyIssuerTransferAgent`. The `Owned` contract modifier instantiates the `onlyOwner` modifier for functions. The `IssuerControlled` modifier instantiates the `onlyIssuerTransferAgent` modifier for functions. - -`ERC-1450` must prevent anyone from executing the `transfer`, `allowance`, and `approve` functions and/or implement these functions to always fail. `ERC-1450` updates the `transferFrom`, `mint`, and `burnFrom` functions. `transferFrom`, `mint`, and `burnFrom` may only be executed by the RTA and are restricted with the `onlyIssuerTransferAgent` modifier. Additionally, `ERC-1450` defines the functions `transferOwnership`, `setTransferAgent`, `setPhysicalAddressOfOperation`, and `isTransferAgent`. Only the issuer may call the `transferOwnership`, `setTransferAgent`, and `setPhysicalAddressOfOperation` functions. Anyone may call the `isTransferAgent` function. - -### Issuers and RTAs -For compliance reasons, the `ERC-1450` constructor must specify the issuer (the `owner`), the RTA (`transferAgent`), the security’s `name`, and the security’s `symbol`. - -#### Issuer Owned -`ERC-1450` must specify the `owner` in its constructor, apply the `Owned` modifier, and instantiate the `onlyOwner` modifier to enable specific functions to permit only the Issuer’s `owner` address to execute them. `ERC-1450` also defines the function `transferOwnership` which transfers ownership of the Issuer to the new `owner`’s address and can only be called by the `owner`. `transferOwnership` triggers the `OwnershipTransferred` event. - -#### Issuer Controlled -`IssuerControlled` maintains the Issuer’s ownership of their securities by owning the contract and enables the Issuer to set and update the RTA for the Issuer’s securities. `ERC-1450`‘s constructor must have an `IssuerControlled` modifier with the issuer specified in its `ERC-1450` constructor. `IssuerControlled` instantiates the `onlyIssuerTransferAgent` modifier for `ERC-1450` to enable specific functions (`setPhysicalAddressOfOperation` and `setTransferAgent`) to permit only the Issuer to execute these functions. - -#### Register Transfer Agent Controlled -`ERC-1450` defines the `setTransferAgent` function (to change the RTA) and `setPhysicalAddressOfOperation` function (to change the Issuer’s address) and must restrict execution to the Issuer’s owner with the `onlyOwner` modifier. `setTransferAgent` must emit the `TransferAgentUpdated` event. `setPhysicalAddressOfOperation` must emit the `PhysicalAddressOfOperationUpdated` event. - -`ERC-1450` must specify the `transferAgent` in its constructor and instantiate the `onlyIssuerTransferAgent` modifier to enable specific functions (`transferFrom`, `mint`, and `burnFrom`) to permit only the Issuer’s `transferAgent` address to execute them. `ERC-1450` also defines the public function `isTransferAgent` to lookup and identify the Issuer’s RTA. - -#### Securities -`ERC-1450` updates the `transferFrom`, `mint`, and `burnFrom` functions by applying the `onlyIssuerTransferAgent` to enable the issuance, re-issuance, and trading of securities. - -### ERC-20 Extension -`ERC-20` tokens provide the following functionality: - -```solidity -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); - event Transfer(address indexed from, address indexed to, uint256 value); -} -``` - -`ERC-20` is extended as follows: - -```solidity -/** - * ERC-1450 is an ERC-20 compatible token that facilitates compliance with one or more of Securities Act Regulations CF, D and A. - * - * Implementations of the ERC-1450 standard must define the following optional ERC-20 - * fields: - * - * name - The name of the security - * symbol - The symbol of the security - * - * Implementations of the ERC-1450 standard must specify the following constructor - * arguments: - * - * _owner - the address of the owner - * _transferAgent - the address of the transfer agent - * _name - the name of the security - * _symbol - the symbol of the security - * - * Implementations of the ERC-1450 standard must implement the following contract - * modifiers: - * - * Owned - Only the address of the security’s issuer is permitted to execute the - * token’s constructor. This modifier also sets up the onlyOwner function modifier. - * IssuerControlled - This modifier sets up the onlyIssuerTransferAgent function modifier. - * - * Implementations of the ERC-1450 standard must implement the following function - * modifiers: - * - * onlyOwner - Only the address of the security’s issuer is permitted to execute the - * functions transferOwnership, setTransferAgent, and setPhysicalAddressOfOperation. - * onlyIssuerTransferAgent - Only the address of the issuer’s Registered Transfer - * Agent is permitted to execute the functions transferFrom, mint, and burnFrom. - * - * Implementations of the ERC-1450 standard must implement the following required ERC-20 - * event to always fail: - * - * Approval - Should never be called as the functions that emit this event must be - * implemented to always fail. - * - * Implementations of the ERC-1450 standard must implement the following required - * ERC-20 functions to always fail: - * - * transfer - Not a legal, regulated call for transferring securities because - * the token holder initiates the token transfer. The function must be implemented to - * always fail. - * allowance - Not a legal, regulated call for transferring securities because - * the token holder may not allow third parties to initiate token transfers. The - * function must be implemented to always fail. - * approve - Not a legal, regulated call for transferring securities because - * the token holder may not allow third parties to initiate token transfers. The - * function must be implemented to always fail. - * - * Implementations of the ERC-1450 standard must implement the following optional - * ERC-20 function: - * decimals - Must return '0' because securities are indivisible entities. - * - * Implementations of the ERC-1450 standard must implement the following functions: - * - * mint - Only the address of the issuer's Registered Transfer Agent may create new - * securities. - * burnFrom - Only the address of the issuer’s Registered Transfer Agent may burn or - * destroy securities. - */ - -Contract ERC-1450 is Owned, IssuerControlled { - - /** - * The constructor must implement a modifier (Owned) that creates the onlyOwner modifier - * to allow only the address of the issuer (the owner) to execute the transferOwnership, - * setTransferAgent, and setPhysicalAddressOfOperation functions. The construct must also - * implement a modifier (TransferAgentControlled) that creates the onlyIssuerTransferAgent - * modifier to allow only the address of the issuer’s Registered Transfer Agent to execute - * the functions transferFrom, mint, and burnFrom). - */ - constructor(address _owner, address _transferAgent, string _name, string _symbol) - Owned(_issuer) TransferAgentControlled(_transferAgent) public; - - /** - * Specify that only the owner (issuer) may execute a function. - * - * onlyOwner requires the msg.sender to be the owner’s address. - */ - modifier onlyOwner(); - - /** - * Specify that only the issuer’s transferAgent may execute a function. - * - * onlyIssuerTransferAgent requires the msg.sender to be the transferAgent’s address. - */ - modifier onlyIssuerTransferAgent(); - - /** - * Transfer ownership of a security from one issuer to another issuer. - * - * transferOwnership must implement the onlyOwner modifier to only allow the - * address of the issuer’s owner to transfer ownership. - * transferOwnership requires the _newOwner address to be the address of the new - * issuer. - */ - function transferOwnership(address _newOwner) public onlyOwner; - - /** - * Triggered after transferOwnership is executed. - */ - event OwnershipTransferred() - - /** - * Sets the transfer agent for the security. - * - * setTransferAgent must implement the onlyOwner modifier to only allow the - * address of the issuer’s specify the security’s transfer agent. - * setTransferAgent requires the _newTransferAgent address to be the address of the - * new transfer agent. - */ - function setTransferAgent(address _newTransferAgent) public onlyOwner; - - /** - * Triggered after setTransferAgent is executed. - */ - event TransferAgentUpdated(address indexed previousTransferAgent, address indexed - newTransferAgent); - - /** - * Sets the issuers physical address of operation. - * - * setPhysicalAddressOfOperation must implement the onlyOwner modifier to only allow - * the address of the issuer’s owner to transfer ownership. - * setPhysicalAddressOfOperation requires the _newPhysicalAddressOfOperation address - * to be the new address of the issuer. - */ - function setPhysicalAddressOfOperation(string _newPhysicalAddressOfOperation) public - onlyOwner; - - /** - * Triggered after setPhysicalAddressOfOperation is executed. - */ - event PhysicalAddressOfOperationUpdated(string previousPhysicalAddressOfOperation, - string newPhysicalAddressOfOperation); - - /** - * Look up the security’s transfer agent. - * - * isTransferAgent is a public function. - * isTransferAgent requires the _lookup address to determine if that address - * is the security’s transfer agent. - */ - function isTransferAgent(address _lookup) public view returns (bool); - - /** - * transfer is not a legal, regulated call and must be implemented to always fail. - */ - transfer(address to, uint tokens) public returns (bool success); - - /** - * Approval does not have to be implemented. This event should never be triggered as - * the functions that emit this even are not legal, regulated calls. - */ - event Approval(address indexed tokenOwner, address indexed spender, uint tokens); - - /** - * allowance is not a legal, regulated call and must be implemented to always fail. - */ - allowance(address tokenOwner, address spender) public constant returns (uint remaining); - - /** - * approve is not a legal, regulated call and must be implemented to always fail. - */ - approve(address spender, uint tokens) public returns (bool success); - - /** - * Transfer securities. - * - * transferFrom must implement the onlyIssuerTransferAgent modifier to only allow the - * address of the issuer’s Registered Transfer Agent to transfer `ERC-1450`s. - * transferFrom requires the _from address to have _value tokens. - * transferFrom requires that the _to address must not be 0 because securities must - * not destroyed in this manner. - */ - function transferFrom(address _from, address _to, uint256 _value) public - onlyIssuerTransferAgent returns (bool); - - /** - * Create new securities. - * - * mint must implement the onlyIssuerTransferAgent modifier to only allow the address - * of the issuer’s Registered Transfer Agent to mint `ERC-1450` tokens. - * mint requires that the _to address must not be 0 because securities must - * not destroyed in this manner. - * mint must add _value tokens to the _to address and increase the totalSupply by - * _value. - * mint must emit the Transfer event. - */ - function mint(address _to, uint256 _value) public onlyIssuerTransferAgent returns - (bool); - - /** - * Burn or destroy securities. - * - * burnFrom must implement the onlyIssuerTransferAgent modifier to only allow the - * address of the issuer’s Registered Transfer Agent to burn `ERC-1450`s. - * burnFrom requires the _from address to have _value tokens. - * burnFrom must subtract _value tokens from the _from address and decrease the - * totalSupply by _value. - * burnFrom must emit the Transfer event. - */ - function burnFrom(address _who, uint256 _value) public onlyIssuerTransferAgent returns - (bool); -} -``` - -### Securities Exchange Commission Requirements -The SEC has very strict requirements as to the specific roles that are allowed to perform specific actions. Specifically, only the RTA may `mint` and `transferFrom` securities. - -Implementers must maintain off-chain services and databases that record and track the Investor’s name, physical address, Ethereum address, and security ownership amount. The implementers and the SEC must be able to access the Investor’s private information on an as needed basis. Issuers and the RTA must be able to produce a current list of all Investors, including the names, addresses, and security ownership levels for every security at any given moment. Issuers and the RTA must be able to re-issue securities to Investors for a variety of regulated reasons. - -Private Investor information must never be publicly exposed on a public blockchain. - -### Managing Investor Information -Special care and attention must be taken to ensure that the personally identifiable information of Investors is never exposed or revealed to the public. - -### Issuers who lost access to their address or private keys -There is no recourse if the Issuer loses access to their address to an existing instance of their securities. Special care and efforts must be made by the Issuer to secure and safely store their address and associated private key. The Issuer can reassign ownership to another Issuer but not in the case where the Issuer loses their private key. - -If the Issuer loses access, the Issuer’s securities must be rebuilt using off-chain services. The Issuer must create (and secure) a new address. The RTA can read the existing Issuer securities, and the RTA can `mint` Investor securities accordingly under a new `ERC-1450` smart contract. - -### Registered Transfer Agents who lost access to their address or private keys -If the RTA loses access, the RTA can create a new Ethereum address, and the Issuer can execute the `setTransferAgent` function to reassign the RTA. - -### Handling Investors (security owners) who lost access to their addresses or private keys -Investors may “lose” their credentials for a number of reasons: they simply “lost” their credentials, they were hacked or the victim of fraud, they committed securities-related fraud, or a life event (like death) occurred. Because the RTA manages the Issuer’s securities, the RTA may authorize ownership related changes of securities (as long as they are properly notarized and verified). - -If an Investor (or, say, the Investor’s heir) loses their credentials, the Investor must go through a notarized process to notify the RTA of the situation and supply a new Investor address. From there, the RTA can `mint` the “lost” securities to the new Investor address and `burnFrom` the old Investor address (because the RTA knows all Investors’ addresses). - -## Rationale -The are currently no token standards that facilitate compliance with SEC regulations. The closest token is [ERC-884 (Delaware General Corporations Law (DGCL) compatible share token)](./eip-884.md) which states that SEC requirements are out of scope. [EIP-1404 (Simple Restricted Token Standard)](https://github.com/ethereum/EIPs/issues/1404) does not go far enough to address SEC requirements around re-issuing securities to Investors. - -## Backwards Compatibility -`ERC-1450` maintains compatibility with ERC-20 tokens with the following stipulations: -* `function allowance(address tokenOwner, address spender) public constant returns (uint remaining);` - * Must be implemented to always fail because allowance is not a legal, regulated call for a security. -* `function transfer(address to, uint tokens) public returns (bool success);` - * As the token holder initiates the transfer, must be implemented to always fail because transfer is not a legal, regulated call for a security. -* `function approve(address spender, uint tokens) public returns (bool success);` - * Must be implemented to always fail because approve is not a legal, regulated call for a security -* `function transferFrom(address from, address to, uint tokens) public returns (bool success);` - * Must be implemented so that only the Issuer’s RTA can perform this action -* `event Approval(address indexed tokenOwner, address indexed spender, uint tokens);` - * Does not have to be implemented. Approval should never be called as the functions that emit this event must be implemented to always fail - -## Test Cases -Test cases are available at [https://github.com/StartEngine/ldgr_smart_contracts/tree/master/test](https://github.com/StartEngine/ldgr_smart_contracts/tree/master/test). - -## Implementations -A reference implementation is available at [https://github.com/StartEngine/ldgr_smart_contracts](https://github.com/StartEngine/ldgr_smart_contracts). - -## Copyright Waiver -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1450.md diff --git a/EIPS/eip-1459.md b/EIPS/eip-1459.md index b59df0eddbd370..dc84e58c8e8c17 100644 --- a/EIPS/eip-1459.md +++ b/EIPS/eip-1459.md @@ -4,7 +4,7 @@ title: Node Discovery via DNS description: Scheme for authenticated updateable Ethereum node lists via DNS. author: Felix Lange (@fjl), Péter Szilágyi (@karalabe) discussions-to: https://github.com/ethereum/devp2p/issues/50 -status: Draft +status: Stagnant type: Standards Track category: Networking created: 2018-09-26 diff --git a/EIPS/eip-1462.md b/EIPS/eip-1462.md index 9bb902088f7839..9f12e73031aa79 100644 --- a/EIPS/eip-1462.md +++ b/EIPS/eip-1462.md @@ -1,117 +1,7 @@ --- eip: 1462 -title: Base Security Token -author: Maxim Kupriianov , Julian Svirsky -discussions-to: https://ethereum-magicians.org/t/erc-1462-base-security-token/1501 -status: Stagnant -type: Standards Track category: ERC -created: 2018-10-01 -requires: 20, 1066 +status: Moved --- -## Simple Summary - -An extension to ERC-20 standard token that provides compliance with securities regulations and legal enforceability. - -## Abstract - -This EIP defines a minimal set of additions to the default token standard such as [ERC-20](./eip-20.md), that allows for compliance with domestic and international legal requirements. Such requirements include KYC (Know Your Customer) and AML (Anti Money Laundering) regulations, and the ability to lock tokens for an account, and restrict them from transfer due to a legal dispute. Also the ability to attach additional legal documentation, in order to set up a dual-binding relationship between the token and off-chain legal entities. - -The scope of this standard is being kept as narrow as possible to avoid restricting potential use-cases of this base security token. Any additional functionality and limitations not defined in this standard may be enforced on per-project basis. - -## Motivation - -There are several security token standards that have been proposed recently. Examples include [ERC-1400](https://github.com/ethereum/EIPs/issues/1411), also [ERC-1450](https://eips.ethereum.org/EIPS/eip-1450). We have concerns about each of them, mostly because the scope of each of these EIPs contains many project-specific or market-specific details. Since many EIPs are coming from the respective backing companies, they capture many niche requirements that are excessive for a general case. - -For instance, ERC-1411 uses dependency on [ERC-1410](https://github.com/ethereum/eips/issues/1410) but it falls out of the "security tokens" scope. Also its dependency on [ERC-777](./eip-777.md) will block the adoption for a quite period of time before ERC-777 is finalized, but the integration guidelines for existing ERC-20 workflows are not described in that EIP, yet. Another attempt to make a much simpler base standard [ERC-1404](https://github.com/ethereum/EIPs/issues/1404) is missing a few important points, specifically it doesn't provide enough granularity to distinguish between different ERC-20 transfer functions such as `transfer` and `transferFrom`. It also doesn't provide a way to bind legal documentation to the issued tokens. - -What we propose in this EIP is a simple and very modular solution for creating a base security token for the widest possible scope of applications, so it can be used by other issuers to build upon. The issuers should be able to add more restrictions and policies to the token, using the functions and implementation proposed below, but they must not be limited in any way while using this ERC. - -## Specification - -The ERC-20 token provides the following basic features: - -```solidity -contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); - event Transfer(address indexed from, address indexed to, uint256 value); -} -``` - -This will be extended as follows: - -```solidity -interface BaseSecurityToken /* is ERC-20 */ { - // Checking functions - function checkTransferAllowed (address from, address to, uint256 value) public view returns (byte); - function checkTransferFromAllowed (address from, address to, uint256 value) public view returns (byte); - function checkMintAllowed (address to, uint256 value) public view returns (byte); - function checkBurnAllowed (address from, uint256 value) public view returns (byte); - - // Documentation functions - function attachDocument(bytes32 _name, string _uri, bytes32 _contentHash) external; - function lookupDocument(bytes32 _name) external view returns (string, bytes32); -} -``` - -### Transfer Checking Functions - -We introduce four new functions that should be used to check that the actions are allowed for the provided inputs. The implementation details of each function are left for the token issuer, it is the issuer's responsibility to add all necessary checks that will validate an operation in accordance with KYC/AML policies and legal requirements set for a specific token asset. - -Each function must return a status code from the common set of Ethereum status codes (ESC), according to [ERC-1066](./eip-1066.md). Localization of these codes is out of the scope of this proposal and may be optionally solved by adopting [ERC-1444](./eip-1444.md) on the application level. If the operation is allowed by a checking function, the return status code must be `0x11` (Allowed) or an issuer-specific code with equivalent but more precise meaning. If the operation is not allowed by a checking function, the status must be `0x10` (Disallowed) or an issuer-specific code with equivalent but more precise meaning. Upon an internal error, the function must return the most relevant code from the general code table or an issuer-specific equivalent, example: `0xF0` (Off-Chain Failure). - -**For [ERC-20](./eip-20.md) based tokens,** -* It is required that transfer function must be overridden with logic that checks the corresponding checkTransferAllowed return status code. -* It is required that `transferFrom` function must be overridden with logic that checks the corresponding `checkTransferFromAllowed` return status code. -* It is required that `approve` function must be overridden with logic that checks the corresponding `checkTransferFromAllowed` return status code. -* Other functions such as `mint` and `burn` must be overridden, if they exist in the token implementation, they should check `checkMintAllowed` and `checkBurnAllowed` status codes accordingly. - -**For [ERC-777](./eip-777.md) based tokens,** -* It is required that `send` function must be overridden with logic that checks the corresponding return status codes: - - `checkTransferAllowed` return status code, if transfer happens on behalf of the tokens owner; - - `checkTransferFromAllowed` return status code, if transfer happens on behalf of an operator (i.e. delegated transfer). -* It is required that `burn` function must be overridden with logic that checks the corresponding `checkBurnAllowed` return status code. -* Other functions, such as `mint` must be overridden, if they exist in the token implementation, e.g. if the security token is mintable. `mint` function must call `checkMintAllowed` ad check it return status code. - -For both cases, - -* It is required for guaranteed compatibility with ERC-20 and ERC-777 wallets that each checking function returns `0x11` (Allowed) if not overridden with the issuer's custom logic. -* It is required that all overridden checking functions must revert if the action is not allowed or an error occurred, according to the returned status code. - -Inside checker functions the logic is allowed to use any feature available on-chain: perform calls to registry contracts with whitelists/blacklists, use built-in checking logic that is defined on the same contract, or even run off-chain queries through an oracle. - -### Documentation Functions - -We also introduce two new functions that should be used for document management purposes. Function `attachDocument` adds a reference pointing to an off-chain document, with specified name, URI and contents hash. The hashing algorithm is not specified within this standard, but the resulting hash must not be longer than 32 bytes. Function `lookupDocument` gets the referenced document by its name. - -* It is not required to use documentation functions, they are optional and provided as a part of a legal framework. -* It is required that if `attachDocument` function has been used, the document reference must have a unique name, overwriting the references under same name is not allowed. All implementations must check if the reference under the given name is already existing. - -## Rationale - -This EIP targets both ERC-20 and ERC-777 based tokens, although the most emphasis is given to ERC-20 due to its widespread adoption. However, this extension is designed to be compatible with the forthcoming ERC-777 standard, as well. - -All checking functions are named with prefixes `check` since they return check status code, not booleans, because that is important to facilitate the debugging and tracing process. It is responsibility of the issuer to implement the logic that will handle the return codes appropriately. Some handlers will simply throw errors, other handlers would log information for future process mining. More rationale for status codes can be seen in [ERC-1066](./eip-1066.md). - -We require two different transfer validation functions: `checkTransferAllowed` and `checkTransferFromAllowed` since the corresponding `transfer` and `transferFrom` are usually called in different contexts. Some token standards such as [ERC-1450](./eip-1450.md) explicitly disallow use of `transfer`, while allowing only `transferFrom`. There might be also different complex scenarios, where `transfer` and `transferFrom` should be treated differently. ERC-777 is relying on its own `send` for transferring tokens, so it is reasonable to switch between checker functions based on its call context. We decided to omit the `checkApprove` function since it would be used in exactly the same context as `checkTransferFromAllowed`. In many cases it is required not only regulate securities transfers, but also restrict burn and `mint` operations, and additional checker functions have been added for that. - -The documentation functions that we propose here are a must-have tool to create dual-bindings with off-chain legal documents, a great example of this can be seen in [Neufund's Employee Incentive Options Plan](https://medium.com/@ZoeAdamovicz/37376fd0384a) legal framework that implements full legal enforceability: the smart contract refers to printed ESOP Terms & Conditions Document, which itself refers back to smart contract. This is becoming a widely adopted practice even in cases where there are no legal requirements to reference the documents within the security token. However they're almost always required, and it's a good way to attach useful documentation of various types. - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of ERC-20 and ERC-777 tokens. - -## Implementation - -* https://github.com/AtlantPlatform/BaseSecurityToken - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1462.md diff --git a/EIPS/eip-1474.md b/EIPS/eip-1474.md index b3834dc8c8d5b4..52575223dd45cd 100644 --- a/EIPS/eip-1474.md +++ b/EIPS/eip-1474.md @@ -293,10 +293,10 @@ Common chain IDs: ```sh # Request curl -X POST --data '{ - "id": 1337 + "id": 1337, "jsonrpc": "2.0", "method": "net_version", - "params": [], + "params": [] }' # Response diff --git a/EIPS/eip-1484.md b/EIPS/eip-1484.md index 396602186bb305..ad952a72f854b9 100644 --- a/EIPS/eip-1484.md +++ b/EIPS/eip-1484.md @@ -1,544 +1,7 @@ --- eip: 1484 -title: Digital Identity Aggregator -author: Anurag Angara , Andy Chorlian , Shane Hampton , Noah Zinsmeister -discussions-to: https://github.com/ethereum/EIPs/issues/1495 -status: Stagnant -type: Standards Track category: ERC -created: 2018-10-12 -requires: 191 +status: Moved --- -## Simple Summary -A protocol for aggregating digital identity information that's broadly interoperable with existing, proposed, and hypothetical future digital identity standards. - -## Abstract -This EIP proposes an identity management and aggregation framework on the Ethereum blockchain. It allows entities to claim an `Identity` via a singular `Identity Registry` smart contract, associate it with Ethereum addresses in a variety of meaningful ways, and use it to interact with smart contracts. This enables arbitrarily complex identity-related functionality. Notably (among other features) ERC-1484 `Identities`: are self-sovereign, can natively support [ERC-725](./eip-725.md) and [ERC-1056](./eip-1056.md) identities, are [DID compliant](https://github.com/NoahZinsmeister/ERC-1484/blob/master/best-practices/DID-Method.md), and can be fully powered by [meta-transactions](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Providers/MetaTransactions). - -## Motivation -Emerging identity standards and related frameworks proposed by the Ethereum community (including ERCs/EIPs [725](./eip-725.md), [735](https://github.com/ethereum/EIPs/issues/735), [780](https://github.com/ethereum/EIPs/issues/780), [1056](./eip-1056.md), etc.) define and instrumentalize digital identity in a variety of ways. As existing approaches mature, new standards emerge, and isolated, non-standard approaches to identity develop, coordinating on identity will become increasingly burdensome for blockchain users and developers, and involve the unnecessary duplication of work. - -The proliferation of on-chain identity solutions can be traced back to the fact that each codifies a notion of identity and links it to specific aspects of Ethereum (claims protocols, per-identity smart contracts, signature verification schemes, etc.). This proposal eschews that approach, instead introducing a protocol layer in between the Ethereum network and individual identity applications. This solves identity management and interoperability challenges by enabling any identity-driven application to leverage an un-opinionated identity management protocol. - -## Definitions -- `Identity Registry`: A single smart contract which is the hub for all `Identities`. The primary responsibility of the `Registry` is to define and enforce the rules of a global namespace for `Identities`, which are individually denominated by Ethereum Identification Numbers (EINs). - -- `Identity`: A data structure containing all the core information relevant to an identity, namely: a `Recovery Address`, an `Associated Addresses` set, a `Providers` set, and a `Resolvers` set. `Identities` are denominated by EINs (incrementing `uint` identifiers starting at 1), which are unique but otherwise uninformative. Each `Identity` is a Solidity struct: - -```solidity -struct Identity { - address recoveryAddress; - AddressSet.Set associatedAddresses; - AddressSet.Set providers; - AddressSet.Set resolvers; -} -``` - -- `Associated Address`: An Ethereum address publicly associated with an `Identity`. In order for an address to become an `Associated Address`, an `Identity` must either transact from or produce an appropriately signed message from the candidate address and an existing `Associated Address`, indicating intent to associate. An `Associated Address` can be removed from an `Identity` by transacting/producing a signature indicating intent to disassociate. A given address may only be an `Associated Address` for one `Identity` at any given time. - -- `Provider`: An Ethereum address (typically but not by definition a smart contract) authorized to act on behalf of `Identities` who have authorized them to do so. This includes but is not limited to managing the `Associated Address`, `Provider`, and `Resolver` sets for an `Identity`. `Providers` exist to facilitate user adoption by making it easier to manage `Identities`. - -- `Resolver`: A smart contract containing arbitrary information pertaining to `Identities`. A resolver may implement an identity standard, such as ERC-725, or may consist of a smart contract leveraging or declaring identifying information about `Identities`. These could be simple attestation structures or more sophisticated financial dApps, social media dApps, etc. Each `Resolver` added to an `Identity` makes the `Identity` more informative. - -- `Recovery Address`: An Ethereum address (either an account or smart contract) that can be used to recover lost `Identities` as outlined in the [Recovery](#recovery) section. - -- `Destruction`: In the event of irrecoverable loss of control of an `Identity`, `Destruction` is a contingency measure to permanently disable the `Identity`. It removes all `Associated Addresses`, `Providers`, and optionally `Resolvers` while preserving the `Identity`. Evidence of the existence of the `Identity` persists, while control over the `Identity` is nullified. - -## Specification -A digital identity in this proposal can be viewed as an omnibus account, containing more information about an identity than any individual identity application could. This omnibus identity is resolvable to an unlimited number of sub-identities called `Resolvers`. This allows an atomic entity, the `Identity`, to be resolvable to abstract data structures, the `Resolvers`. `Resolvers` recognize `Identities` by any of their `Associated Addresses`, or by their `EIN`. - -The protocol revolves around claiming an `Identity` and managing `Associated Addresses`, `Providers` and `Resolvers`. Identities can delegate much or all of this responsibility to one or more `Providers`, or perform it directly from an `Associated Address`. `Associated Addresses`/`Providers` may add and remove `Resolvers` and `Providers` indiscriminately. `Associated Addresses` may only be added or removed with the appropriate permission. - -### Identity Registry -The `Identity Registry` contains functionality to create new `Identities` and for existing `Identities` to manage their `Associated Addresses`, `Providers`, and `Resolvers`. It is important to note that this registry fundamentally requires transactions for every aspect of building out an `Identity`. However, recognizing the importance of accessibility to dApps and identity applications, we empower `Providers` to build out `Identities` on the behalf of users, without requiring users to pay gas costs. An example of this pattern, often referred to as a meta transactions, can be [seen in the reference implementation](https://github.com/NoahZinsmeister/ERC-1484/tree/master/contracts/examples/Providers/MetaTransactions). - -Due to the fact that multiple addresses can be associated with a given identity (though not the reverse), `Identities` are denominated by `EIN`. This `uint` identifier can be encoded in QR format or mapped to more user-friendly formats, such as a `string`, in registries at the `Provider` or `Resolver` level. - -### Address Management -The address management function consists of trustlessly connecting multiple user-owned `Associated Addresses` to an `Identity`. It does not give special status to any particular `Associated Address`, rather leaving this (optional) specification to identity applications built on top of the protocol - for instance, `management`, `action`, `claim` and `encryption` keys denominated in the ERC-725 standard, or `identifiers` and `delegates` as denominated in ERC-1056. This allows a user to access common identity data from multiple wallets while still: - -- retaining the ability to interact with contracts outside of their identity -- taking advantage of address-specific permissions established at the application layer of a user's identity. - -Trustlessness in the address management function is achieved through a robust permissioning scheme. To add an `Associated Address` to an `Identity`, implicit permission from a transaction sender or explicit permission from a signature is required from 1) an address already within the registry and 2) an address to be claimed. Importantly, the transaction need not come from any particular address, as long as permission is established, which allows not only users but third parties (companies, governments, etc.) to bear the overhead of managing identities. To prevent a compromised `Associated Address` from unilaterally removing other `Associated Addresses`, it's only possible to remove an `Associated Address` by transacting or producing a signature from it. - -All signatures required in ERC-1484 are designed per the [ERC-191](./eip-191.md) v0 specification. To avoid replay attacks, all signatures must include a timestamp within a rolling lagged window of the current `block.timestamp`. For more information, see this [best practices document](https://github.com/NoahZinsmeister/ERC-1484/blob/master/best-practices/VerifyingSignatures.md) in the reference implementation. - -### Provider Management -While the protocol allows users to directly call identity management functions, it also aims to be more robust and future-proof by allowing `Providers`, typically smart contracts, to perform identity management functions on a user's behalf. A `Provider` set by an `Identity` can perform address management and resolver management functions by passing a user's `EIN` in function calls. - -### Resolver Management -A `Resolver` is any smart contract that encodes information which resolves to an `Identity`. We remain agnostic about the specific information that can be encoded in a resolver and the functionality that this enables. The existence of `Resolvers` is primarily what makes this ERC an identity *protocol* rather than an identity *application*. `Resolvers` resolve abstract data in smart contracts to an atomic entity, the `Identity`. - -### Recovery -If users lose control over an `Associated Address`, the `Recovery Address` provides a fallback mechanism. Upon `Identity` creation, a `Recovery Address` is passed as a parameter by the creator. Recovery functionality is triggered in three scenarios: - -**1. Changing Recovery Address**: If a recovery key is lost, an `Associated Address`/`Provider` can [triggerRecoveryAddressChange](#triggerrecoveryaddresschange)/[triggerRecoveryAddressChangeFor](#triggerrecoveryaddresschangefor). To prevent malicious behavior from someone who has gained control of an `Associated Address` or `Provider` and is changing the `Recovery Address` to one under their control, this action triggers a 14 day challenge period during which the old `Recovery Address` may reject the change by [triggering recovery](#triggerrecovery). If the `Recovery Address` does not reject the change within 14 days, the `Recovery Address` is changed. - -**2. Recovery**: Recovery occurs when a user recognizes that an `Associated Address` or the `Recovery Address` belonging to the user is lost or stolen. In this instance the `Recovery Address` must call [triggerRecovery](#triggerrecovery). This removes all `Associated Addresses` and `Providers` from the corresponding `Identity` and replaces them with an address passed in the function call. The `Identity` and associated `Resolvers` maintain integrity. The user is now responsible for adding the appropriate un-compromised addresses back to their `Identity`. - -*Importantly, the `Recovery Address` can be a user-controlled wallet or another address, such as a multisig wallet or smart contract. This allows for arbitrarily sophisticated recovery logic! This includes the potential for recovery to be fully compliant with standards such as [DID](https://decentralized.id/).* - -**3. Destruction** -The Recovery scheme offers considerable power to a `Recovery Address`; accordingly, `Destruction` is a nuclear option to combat malicious control over an `Identity` when a `Recovery Address` is compromised. If a malicious actor compromises a user's `Recovery Address` and triggers recovery, any address removed in the `Recovery` process can call [triggerDestruction](#triggerdestruction) within 14 days to permanently disable the `Identity`. The user would then need to create a new `Identity`, and would be responsible for engaging in recovery schemes for any identity applications built in the `Resolver` or `Provider` layers. - -#### Alternative Recovery Considerations -We considered many possible alternatives when devising the Recovery process outlined above. We ultimately selected the scheme that was most un-opinionated, modular, and consistent with the philosophy behind the `Associated Address`, `Provider`, and `Resolver` components. Still, we feel that it is important to highlight some of the other recovery options we considered, to provide a rationale as to how we settled on what we did. - -**High Level Concerns** -Fundamentally, a Recovery scheme needs to be resilient to a compromised address taking control of a user's `Identity`. A secondary concern is preventing a compromised address from maliciously destroying a user's identity due to off-chain utility, which is not an optimal scenario, but is strictly better than if they've gained control. - -**Alternative 1: Nuclear Option** -This approach would allow any `Associated Address` to destroy an `Identity` whenever another `Associated Address` is compromised. While this may seem severe, we strongly considered it because this ERC is an identity *protocol*, not an identity *application*. This means that though a user's compromised `Identity` is destroyed, they should still have recourse to whatever restoration mechanisms are available in each of their actual identities at the `Resolver` and/or `Provider` level. We ultimately dismissed this approach for two main reasons: - -- It is not robust in cases where a user has only one `Associated Address` -- It would increase the frequency of recovery requests to identity applications due to its unforgiving nature. - -**Alternative 2: Unilateral Address Removal via Providers** -This would allow `Associated Addresses`/`Providers` to remove `Associated Addresses` without a signature from said address. This implementation would allow `Providers` to include arbitrarily sophisticated schemes for removing a rogue address - for instance, multi-sig requirements, centralized off-chain verification, user controlled master addresses, deferral to a jurisdictional contract, and more. To prevent a compromised `Associated Address` from simply setting a malicious `Provider` to remove un-compromised addresses, it would have required a waiting period between when a `Provider` is set and when they would be able to remove an `Associated Address`. We dismissed this approach because we felt it placed too high of a burden on `Providers`. If a `Provider` offered a sophisticated range of functionality to a user, but post-deployment a threat was found in the Recovery logic of the provider, `Provider`-specific infrastructure would need to be rebuilt. We also considered including a flag that would allow a user to decide whether or not a `Provider` may remove `Associated Addresses` unilaterally. Ultimately, we concluded that only allowing removal of `Associated Addresses` via the `Recovery Address` enables equally sophisticated recovery logic while separating the functionality from `Providers`, leaving less room for users to relinquish control to potentially flawed implementations. - -## Rationale -We find that at a protocol layer, identities should not rely on specific claim or attestation structures, but should instead be a part of a trustless framework upon which arbitrarily sophisticated claim and attestation structures may be built. - -The main criticism of existing identity solutions is that they're overly restrictive. We aim to limit requirements, keep identities modular and future-proof, and remain un-opinionated regarding any functionality a particular identity component may have. This proposal gives users the option to interact on the blockchain using an robust `Identity` rather than just an address. - -## Implementation -**The reference implementation for ERC-1484 may be found in [NoahZinsmeister/ERC-1484](https://github.com/NoahZinsmeister/ERC-1484).** - -#### identityExists - -Returns a `bool` indicating whether or not an `Identity` denominated by the passed `EIN` exists. - -```solidity -function identityExists(uint ein) public view returns (bool); -``` - -#### hasIdentity - -Returns a `bool` indicating whether or not the passed `_address` is associated with an `Identity`. - -```solidity -function hasIdentity(address _address) public view returns (bool); -``` - -#### getEIN - -Returns the `EIN` associated with the passed `_address`. Throws if the address is not associated with an `EIN`. - -```solidity -function getEIN(address _address) public view returns (uint ein); -``` - -#### isAssociatedAddressFor - -Returns a `bool` indicating whether or not the passed `_address` is associated with the passed `EIN`. - -```solidity -function isAssociatedAddressFor(uint ein, address _address) public view returns (bool); -``` - -#### isProviderFor - -Returns a `bool` indicating whether or not the passed `provider` has been set by the passed `EIN`. - -```solidity -function isProviderFor(uint ein, address provider) public view returns (bool); -``` - -#### isResolverFor - -Returns a `bool` indicating whether or not the passed `resolver` has been set by the passed `EIN`. - -```solidity -function isResolverFor(uint ein, address resolver) public view returns (bool); -``` - -#### getIdentity - -Returns the `recoveryAddress`, `associatedAddresses`, `providers` and `resolvers` of the passed `EIN`. - -```solidity -function getIdentity(uint ein) public view - returns ( - address recoveryAddress, - address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers - ); -``` - -#### createIdentity - -Creates an `Identity`, setting the `msg.sender` as the sole `Associated Address`. Returns the `EIN` of the new `Identity`. - -```solidity -function createIdentity(address recoveryAddress, address[] memory providers, address[] memory resolvers) - public returns (uint ein); -``` - -Triggers event: [IdentityCreated](#identitycreated) - -#### createIdentityDelegated - -Performs the same logic as `createIdentity`, but can be called by any address. This function requires a signature from the `associatedAddress` to ensure their consent. - -```solidity -function createIdentityDelegated( - address recoveryAddress, address associatedAddress, address[] memory providers, address[] memory resolvers, - uint8 v, bytes32 r, bytes32 s, uint timestamp -) - public returns (uint ein); -``` - -Triggers event: [IdentityCreated](#identitycreated) - -#### addAssociatedAddress - -Adds the `addressToAdd` to the `EIN` of the `approvingAddress`. The `msg.sender` must be either of the `approvingAddress` or the `addressToAdd`, and the signature must be from the other one. - -```solidity -function addAssociatedAddress( - address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp -) - public -``` - -Triggers event: [AssociatedAddressAdded](#associatedaddressadded) - -#### addAssociatedAddressDelegated - -Adds the `addressToAdd` to the `EIN` of the `approvingAddress`. Requires signatures from both the `approvingAddress` and the `addressToAdd`. - -```solidity -function addAssociatedAddressDelegated( - address approvingAddress, address addressToAdd, - uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp -) - public -``` - -Triggers event: [AssociatedAddressAdded](#associatedaddressadded) - -#### removeAssociatedAddress - -Removes the `msg.sender` as an `Associated Address` from its `EIN`. - -```solidity -function removeAssociatedAddress() public; -``` - -Triggers event: [AssociatedAddressRemoved](#associatedaddressremoved) - - -#### removeAssociatedAddressDelegated - -Removes the `addressToRemove` from its associated `EIN`. Requires a signature from the `addressToRemove`. - -```solidity -function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) - public; -``` - -Triggers event: [AssociatedAddressRemoved](#associatedaddressremoved) - -#### addProviders - -Adds an array of `Providers` to the `Identity` of the `msg.sender`. - -```solidity -function addProviders(address[] memory providers) public; -``` - -Triggers event: [ProviderAdded](#provideradded) - -#### addProvidersFor - -Performs the same logic as `addProviders`, but must be called by a `Provider`. - -```solidity -function addProvidersFor(uint ein, address[] memory providers) public; -``` - -Triggers event: [ProviderAdded](#provideradded) - -#### removeProviders - -Removes an array of `Providers` from the `Identity` of the `msg.sender`. - -```solidity -function removeProviders(address[] memory providers) public; -``` - -Triggers event: [ProviderRemoved](#providerremoved) - - -#### removeProvidersFor - -Performs the same logic as `removeProviders`, but is called by a `Provider`. - -```solidity -function removeProvidersFor(uint ein, address[] memory providers) public; -``` - -Triggers event: [ProviderRemoved](#providerremoved) - - -#### addResolvers - -Adds an array of `Resolvers` to the `EIN` of the `msg.sender`. - -```solidity -function addResolvers(address[] memory resolvers) public; -``` - -Triggers event: [ResolverAdded](#resolveradded) - -#### addResolversFor - -Performs the same logic as `addResolvers`, but must be called by a `Provider`. - -```solidity -function addResolversFor(uint ein, address[] memory resolvers) public; -``` - -Triggers event: [ResolverAdded](#resolveradded) - -#### removeResolvers - -Removes an array of `Resolvers` from the `EIN` of the `msg.sender`. - -```solidity -function removeResolvers(address[] memory resolvers) public; -``` - -Triggers event: [ResolverRemoved](#resolverremoved) - -#### removeResolversFor - -Performs the same logic as `removeResolvers`, but must be called by a `Provider`. - -```solidity -function removeResolversFor(uint ein, address[] memory resolvers) public; -``` - -Triggers event: [ResolverRemoved](#resolverremoved) - -#### triggerRecoveryAddressChange - -Initiates a change in the current `recoveryAddress` for the `EIN` of the `msg.sender`. - -```solidity -function triggerRecoveryAddressChange(address newRecoveryAddress) public; -``` - -Triggers event: [RecoveryAddressChangeTriggered](#recoveryaddresschangetriggered) - -#### triggerRecoveryAddressChangeFor - -Initiates a change in the current `recoveryAddress` for a given `EIN`. - -```solidity -function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) public; -``` - -Triggers event: [RecoveryAddressChangeTriggered](#recoveryaddresschangetriggered) - -#### triggerRecovery - -Triggers `EIN` recovery from the current `recoveryAddress`, or the old `recoveryAddress` if changed within the last 2 weeks. - -```solidity -function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) public; -``` - -Triggers event: [RecoveryTriggered](#recoverytriggered) - -#### triggerDestruction - -Triggers destruction of an `EIN`. This renders the `Identity` permanently unusable. - -```solidity -function triggerDestruction(uint ein, address[] memory firstChunk, address[] memory lastChunk, bool clearResolvers) - public; -``` - -Triggers event: [IdentityDestroyed](#identitydestroyed) - -### Events - -#### IdentityCreated - -MUST be triggered when an `Identity` is created. - -```solidity -event IdentityCreated( - address indexed initiator, uint indexed ein, - address recoveryAddress, address associatedAddress, address[] providers, address[] resolvers, bool delegated -); -``` - -#### AssociatedAddressAdded - -MUST be triggered when an address is added to an `Identity`. - -```solidity -event AssociatedAddressAdded( - address indexed initiator, uint indexed ein, address approvingAddress, address addedAddress, bool delegated -); -``` - -#### AssociatedAddressRemoved - -MUST be triggered when an address is removed from an `Identity`. - -```solidity -event AssociatedAddressRemoved(address indexed initiator, uint indexed ein, address removedAddress, bool delegated); -``` - -#### ProviderAdded - -MUST be triggered when a provider is added to an `Identity`. - -```solidity -event ProviderAdded(address indexed initiator, uint indexed ein, address provider, bool delegated); -``` - -#### ProviderRemoved - -MUST be triggered when a provider is removed. - -```solidity -event ProviderRemoved(address indexed initiator, uint indexed ein, address provider, bool delegated); -``` - -#### ResolverAdded - -MUST be triggered when a resolver is added. - -```solidity -event ResolverAdded(address indexed initiator, uint indexed ein, address resolvers, bool delegated); -``` - -#### ResolverRemoved - -MUST be triggered when a resolver is removed. - -```solidity -event ResolverRemoved(address indexed initiator, uint indexed ein, address resolvers, bool delegated); -``` - -#### RecoveryAddressChangeTriggered - -MUST be triggered when a recovery address change is triggered. - -```solidity -event RecoveryAddressChangeTriggered( - address indexed initiator, uint indexed ein, - address oldRecoveryAddress, address newRecoveryAddress, bool delegated -); -``` - -#### RecoveryTriggered - -MUST be triggered when recovery is triggered. - -```solidity -event RecoveryTriggered( - address indexed initiator, uint indexed ein, address[] oldAssociatedAddresses, address newAssociatedAddress -); -``` - -#### IdentityDestroyed - -MUST be triggered when an `Identity` is destroyed. - -```solidity -event IdentityDestroyed(address indexed initiator, uint indexed ein, address recoveryAddress, bool resolversReset); -``` - -### Solidity Interface -```solidity -interface IdentityRegistryInterface { - function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) - external pure returns (bool); - - // Identity View Functions ///////////////////////////////////////////////////////////////////////////////////////// - function identityExists(uint ein) external view returns (bool); - function hasIdentity(address _address) external view returns (bool); - function getEIN(address _address) external view returns (uint ein); - function isAssociatedAddressFor(uint ein, address _address) external view returns (bool); - function isProviderFor(uint ein, address provider) external view returns (bool); - function isResolverFor(uint ein, address resolver) external view returns (bool); - function getIdentity(uint ein) external view returns ( - address recoveryAddress, - address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers - ); - - // Identity Management Functions /////////////////////////////////////////////////////////////////////////////////// - function createIdentity(address recoveryAddress, address[] calldata providers, address[] calldata resolvers) - external returns (uint ein); - function createIdentityDelegated( - address recoveryAddress, address associatedAddress, address[] calldata providers, address[] calldata resolvers, - uint8 v, bytes32 r, bytes32 s, uint timestamp - ) external returns (uint ein); - function addAssociatedAddress( - address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp - ) external; - function addAssociatedAddressDelegated( - address approvingAddress, address addressToAdd, - uint8[2] calldata v, bytes32[2] calldata r, bytes32[2] calldata s, uint[2] calldata timestamp - ) external; - function removeAssociatedAddress() external; - function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) - external; - function addProviders(address[] calldata providers) external; - function addProvidersFor(uint ein, address[] calldata providers) external; - function removeProviders(address[] calldata providers) external; - function removeProvidersFor(uint ein, address[] calldata providers) external; - function addResolvers(address[] calldata resolvers) external; - function addResolversFor(uint ein, address[] calldata resolvers) external; - function removeResolvers(address[] calldata resolvers) external; - function removeResolversFor(uint ein, address[] calldata resolvers) external; - - // Recovery Management Functions /////////////////////////////////////////////////////////////////////////////////// - function triggerRecoveryAddressChange(address newRecoveryAddress) external; - function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) external; - function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) - external; - function triggerDestruction( - uint ein, address[] calldata firstChunk, address[] calldata lastChunk, bool resetResolvers - ) external; - - // Events ////////////////////////////////////////////////////////////////////////////////////////////////////////// - event IdentityCreated( - address indexed initiator, uint indexed ein, - address recoveryAddress, address associatedAddress, address[] providers, address[] resolvers, bool delegated - ); - event AssociatedAddressAdded( - address indexed initiator, uint indexed ein, address approvingAddress, address addedAddress - ); - event AssociatedAddressRemoved(address indexed initiator, uint indexed ein, address removedAddress); - event ProviderAdded(address indexed initiator, uint indexed ein, address provider, bool delegated); - event ProviderRemoved(address indexed initiator, uint indexed ein, address provider, bool delegated); - event ResolverAdded(address indexed initiator, uint indexed ein, address resolvers); - event ResolverRemoved(address indexed initiator, uint indexed ein, address resolvers); - event RecoveryAddressChangeTriggered( - address indexed initiator, uint indexed ein, address oldRecoveryAddress, address newRecoveryAddress - ); - event RecoveryTriggered( - address indexed initiator, uint indexed ein, address[] oldAssociatedAddresses, address newAssociatedAddress - ); - event IdentityDestroyed(address indexed initiator, uint indexed ein, address recoveryAddress, bool resolversReset); -} -``` - -## Backwards Compatibility -`Identities` established under this standard consist of existing Ethereum addresses; accordingly, there are no backwards compatibility issues. Deployed, non-upgradeable smart contracts that wish to become `Resolvers` for `Identities` will need to write wrapper contracts that resolve addresses to `EIN`-denominated `Identities`. - -## Additional References -- [ERC-1484 Reference Implementation](https://github.com/NoahZinsmeister/ERC-1484) -- [ERC-191 Signatures](./eip-191.md) -- [ERC-725 Identities](./eip-725.md) -- [ERC-1056 Identities](./eip-1056.md) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1484.md diff --git a/EIPS/eip-1491.md b/EIPS/eip-1491.md index 9007dcb0bee6a2..e5cdf4854be6e5 100644 --- a/EIPS/eip-1491.md +++ b/EIPS/eip-1491.md @@ -1,528 +1,7 @@ --- eip: 1491 -title: Human Cost Accounting Standard (Like Gas but for humans) -author: Iamnot Chris (@cohabo) -discussions-to: https://github.com/freeworkculture/kazini/issues/11 -status: Stagnant -type: Standards Track category: ERC -created: 2018-10-12 +status: Moved --- -## Simple Summary -A standard interface for Human Capital Accounting tokens. - -## Abstract -The following standard allows for the implementation of a standard API for HUCAP tokens within smart contracts. This standard provides basic functionality to discover, track and transfer the motivational hierarchy of human resources. While blockchain architecture has succeeded in the financialisation of integrity by way of transparency; correspondingly real world outcomes will be proportional to the degree of individualisation of capital by way of knowledge. - -## Motivation -The Ethereum protocol architecture has a deterministic world-view bounded to the random reality of the human domain that supplies the intentions and logic. The yellow paper formally defines the EVM as a state machine with only deterministic parameters and state transition operators. Oracle requests to another on-chain contract, and/or off-chain HTTP lookups still make for multiple deterministic transactions. - -A standard interface that allows the appraisal of individual capabilities concurrently with output and the overall knowledge-base will reduce market search costs and increase the autonomous insertion of mindful innovation into the blockchain ecosystem. We provide for simple smart contracts to define and track an arbitrarily large number of HUCAP assets. Additional applications are discussed below. - -The Belief-Desire-Intention model is a plan-theoretic framework for establishing means-end coherence in agent based modelling system. -The blockchain's cryptographic security architecture reliably scales to a blockchain based PKI web-of-trust hierarchies. -ERC-20 token standard allows any tokens on Ethereum to be re-used by other applications: from wallets to decentralized exchanges. -ERC-721 token standard allows wallet/broker/auction applications to work with any NFT on Ethereum. -ERC-1155 Crypto Item standard allows a smart contract interface where one can represent any number of ERC-20 and ERC-721 assets in a single contract. - -This standard is inspired by the belief–desire–intention (BDI) model of human practical reasoning developed by Michael Bratman as a way of explaining future-directed intention. A BDI agent is a particular type of bounded rational software agent, imbued with particular mental attitudes, viz: Beliefs, Desires and Intentions (BDI). The model identifies commitment as the distinguishing factor between desire and intention, and a noteworthy property that leads to (1) temporal persistence in plans and in the sense of explicit reference to time, (2) further plans being made on the basis of those to which it is already committed, (3) hierarchical nature of plans, since the overarching plan remains in effect while subsidiary plans are being executed. - -The BDI software model is an attempt to solve a problem of plans and planning choice and the execution thereof. The complement of which tenders a sufficient metric for indicating means-end coherence and ascribing cost baselines to such outcomes. - -## Specification - -#### Main Interface -```solidity -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -/** - @title ERC-**** Human Capital Accounting Standard - @dev See https://github.com/freeworkculture/kazini/issues/11 - Note: the ERC-165 identifier for this interface is 0xf23a6e61. - */ - -interface IERC_HUCAP { - - /** - @notice Compute the index value of an Agents BDI in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function updateIndex() internal returns (bool); - - /** - @notice Get the active/inactive and states of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function iam() view public returns (bool iam_, IERC_HUCAP_TYPES.IS state_); - - /** - @notice Fetch the bdi index value of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function index() view public returns (uint8 index_); - - /** - @notice Count of Public Keys in key ring of an Agent in the ecosystem. - @param _address Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function ringLength() view public returns (uint ringlength_); - - /** - @notice Get the PGP Public Key Id of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function keyId() view public returns (bytes32 KEYID_); - - /** - @notice Get the merit data of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function merits() view public returns ( - uint experience_, - bytes32 reputation_, - bytes32 talent_, - uint8 index_, - bytes32 hash_); - - /** - @notice Get the accreditation of an Agent in the ecosystem. - @param "" Set the stance of an agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function kbase() view public returns (IERC_HUCAP_TYPES.KBase kbase_); - - /** - @notice Get the desire of an Agent in the ecosystem. - @param _desire Pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function desire(bytes1 _desire) view external returns (bytes32); - - /** - @notice Get the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function intention(bool _intention) view external returns (bytes32); - - /** - @notice Cycle the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function flipIntention() external returns (bool); - - - /** - @notice Get the user data of an Agent in the ecosystem. - @param "" Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function getDoer() view external returns ( - bytes32 fPrint, - bool iam_, - bytes32 email, - bytes32 fName, - bytes32 lName, - uint age, - bytes32 data_); - - /** - @notice Get the belief data of an Agent in the ecosystem. - @param _kbase Source address - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getBelief(IERC_HUCAP_TYPES.KBase _kbase) view external returns ( - bytes32 country_, - bytes32 cAuthority_, - bytes32 score_); - - /** - @notice Get the desire data of an Agent in the ecosystem. - @param _desire Pro-attitides - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getDesire(bytes1 _desire) view external returns (bytes32,bool); - - /** - @notice Get the intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function getIntention(bool _intention) view external returns (IERC_HUCAP_TYPES.IS,bytes32,uint256); - - /** - @notice Sign the Public Key of an Agent in the ecosystem. - @param _address Address of key to sign, must belong to an Agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function sign(address _address) public onlyOwner returns (uint, bool signed); - - /** - @notice Sign the Public Key of an Agent in the ecosystem. - @param "" internal helper function to add key in keyring - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function sign() external onlyDoer returns (uint, bool signed); - - /** - @notice Revoke the Public Key of an Agent in the ecosystem. - @param _address Address of key to revoke, must belong to an Agent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function revoke(address _address) external onlyDoer returns (uint, bool revoked); - - /** - @notice Revoke the Public Key of an Agent in the ecosystem. - @param "" internal helper function to remove key from keyring - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function revoke() external onlyDoer returns (uint, bool revoked); - - /** - @notice Set the trust level for a Public Key of an Agent in the ecosystem. - @param _level Degree of trust - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function trust(Trust _level) returns (bool); - - /** - @notice Increment the number of keys in the keyring of an Agent in the ecosystem. - @param _keyd Target key - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function incSigns(bytes32 _keyd) external ProxyKey returns (uint); - - /** - @notice Decrement the number of keys in the keyring of an Agent in the ecosystem. - @param _keyd Target key - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function decSigns(bytes32 _keyd) external ProxyKey returns (uint); - - /** - @notice Set the knowledge credentials of an Agent in the ecosystem. - @param _kbase Level of accreditation - @param _country Source country - @param _cAuthority Accreditation authority - @param _score Accreditation - @param _year Year of Accreditation - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi( - KBase _kbase, - bytes32 _country, - bytes32 _cAuthority, - bytes32 _score, - uint _year - ) external ProxyBDI returns (bool qualification_); - - /** - @notice Set the SNA metrics of an Agent in the ecosystem - @param _refMSD Minimum shortest distance - @param _refRank Rank of target key - @param _refSigned No of keys signed I have signed - @param _refSigs No. of keys that have signed my key - @param _refTrust Degree of tructThrows on any error rather than return a false flag to minimize user errors - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi( - uint _refMSD, - uint _refRank, - uint _refSigned, - uint _refSigs, - bytes32 _refTrust - ) external ProxyBDI returns (bool reputation_); - - /** - @notice Set the talents of an Agent in the ecosystem - @param _talent Agent's talent - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(bytes32 _talent) external ProxyBDI returns (bool talent_); - - /** - @notice Set the desires of an Agent in the ecosystem - @param _desire Pro-attitude - @param _goal A goal is an instatiated pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(bytes1 _desire, Desire _goal) public onlyDoer returns (bool); - - /** - @notice Set the intention of an Agent in the ecosystem - @param _service Conducting-controlling pro-attitude - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - */ - function setbdi(Intention _service) public onlyDoer returns (bool); - - /** - @notice Set the targeted intention of an Agent in the ecosystem. - @param _intention Conduct-controlling pro-attitude - @param _state Agent stance - @dev For the purpose of - Throws on any error rather than return a false flag to minimize user errors - - */ - function intention(bool _intention, IERC_HUCAP_TYPES.IS _state) external returns (IERC_HUCAP_TYPES.IS); - -/* End of interface IERC_HUCAP */ -} - - -``` -#### User Defined Types Extension Interface - -```solidity - -interface IERC_HUCAP_TYPES { - -/* Enums*/ - - // Weights 1, 2, 4, 8, 16, 32, 64, 128 256 - enum KBase {PRIMARY,SECONDARY,TERTIARY,CERTIFICATION,DIPLOMA,LICENSE,BACHELOR,MASTER,DOCTORATE} - - - enum IS { CLOSED, CREATOR, CURATOR, ACTIVE, INACTIVE, RESERVED, PROVER } - -/* Structus */ - - struct Clearance { - bytes32 Zero; - bytes32 Unknown; - bytes32 Generic; - bytes32 Poor; - bytes32 Casual; - bytes32 Partial; - bytes32 Complete; - bytes32 Ultimate; - } -/* End of interface IERC_HUCAP_TYPES */ -} - -``` -#### Web-of-trust Extension Interface - -```solidity -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -interface IERC_HUCAP_KEYSIGNING_EXTENSION { - - bytes32 constant public _InterfaceId_ERC165_ = "CREATOR 0.0118 XOR OF ALL FUNCTIONS IN THE INTERFACE"; // Complies to ERC165 - -// KEY MASKING TABLE -// bytes32 constant public MASK = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; -// bytes32 constant public KEYID = 0xffffffffffffffffffffffffffffffffff90EBAC34FC40EAC30FC9CB464A2E56; // EXAMPLE PGP PUBLIC KEY ID -// bytes32 constant public KEY_CERTIFICATION = 0x01ffffffffffffff << 192; // “C” Key Certification -// bytes32 constant public SIGN_DATA = 0x02ffffffffffffff << 192; // “S” Sign Data -// bytes32 constant public ENCRYPT_COMMUNICATIONS = 0x04ffffffffffffff << 192; // “E” Encrypt Communications -// Clearance constant public Trust = 0x03ff << 192; // Trust: Unknown - // BYTES32 Value with - // Public Key Id, masking - // Key Certification masking - // Split Key masking - // Generic masking - // Ordinary masking - // Trust.Unknown masking - // bytes32 constant public DOER = 0x11ff10ff100f03ffff00ffffffffffffffff90EBAC34FC40EAC30FC9CB464A2E56; - - bytes32 constant public KEY_CERTIFICATION = 0x01ffffffffffffff << 192; // “C” Key Certification - bytes32 constant public SIGN_DATA = 0x02ffffffffffffff << 192; // “S” Sign Data - bytes32 constant public ENCRYPT_COMMUNICATIONS = 0x04ffffffffffffff << 192; // “E” Encrypt Communications - bytes32 constant public ENCRYPT_STORAGE = 0x08ffffffffffffff << 192; // “E” Encrypt Storage - bytes32 constant public SPLIT_KEY = 0x10ffffffffffffff << 192; // Split key - bytes32 constant public AUTHENTICATION = 0x20ffffffffffffff << 192; // “A” Authentication - bytes32 constant public MULTI_SIGNATURE = 0x80ffffffffffffff << 192; // Held by more than one person - bytes32 constant public TRUST_AMOUNT = 0xffffffffffff00ff << 192; - bytes32 constant public BINARY_DOCUMENT = 0xffff00ffffffffff << 192; // 0x00: Signature of a binary document. - bytes32 constant public CANONICAL_DOCUMENT = 0xffff01ffffffffff << 192; // 0x01: Signature of a canonical text document. - bytes32 constant public STANDALONE_SIGNATURE = 0xffff02ffffffffff << 192; // 0x02: Standalone signature. - bytes32 constant public GENERIC = 0xffff10ffffffffff << 192; // 0x10: Generic certification of a User ID and Public-Key packet. - bytes32 constant public PERSONA = 0xffff11ffffffffff << 192; // 0x11: Persona certification of a User ID and Public-Key packet. - bytes32 constant public CASUAL = 0xffff12ffffffffff << 192; // 0x12: Casual certification of a User ID and Public-Key packet. - bytes32 constant public POSITIVE = 0xffff13ffffffffff << 192; // 0x13: Positive certification of a User ID and Public-Key packet. - bytes32 constant public SUBKEY_BINDING = 0xffff18ffffffffff << 192; // 0x18: Subkey Binding Signature - bytes32 constant public PRIMARY_KEY_BINDING = 0xffff19ffffffffff << 192; // 0x19: Primary Key Binding Signature - bytes32 constant public DIRECTLY_ON_KEY = 0xffff1Fffffffffff << 192; // 0x1F: Signature directly on a key - bytes32 constant public KEY_REVOCATION = 0xffff20ffffffffff << 192; // 0x20: Key revocation signature - bytes32 constant public SUBKEY_REVOCATION = 0xffff28ffffffffff << 192; // 0x28: Subkey revocation signature - bytes32 constant public CERTIFICATION_REVOCATION = 0xffff30ffffffffff << 192; // 0x30: Certification revocation signature - bytes32 constant public TIMESTAMP = 0xffff40ffffffffff << 192; // 0x40: Timestamp signature. - bytes32 constant public THIRD_PARTY_CONFIRMATION = 0xffff50ffffffffff << 192; // 0x50: Third-Party Confirmation signature. - bytes32 constant public ORDINARY = 0xffffffff100fffff << 192; - bytes32 constant public INTRODUCER = 0xffffffff010fffff << 192; - bytes32 constant public ISSUER = 0xffffffff001fffff << 192; - -// EDGES MASKING TABLE - Clearance internal TRUST = Clearance({ - Zero: 0x01ff << 192, - Unknown: 0x03ff << 192, - Generic: 0x07ff << 192, - Poor: 0xF0ff << 192, - Casual: 0xF1ff << 192, - Partial: 0xF3ff << 192, - Complete: 0xF7ff << 192, - Ultimate: 0xFFff << 192 - }); - - /** - /// @notice Cycle through state transition of an Agent in the ecosystem. - /// @param _address toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function flipTo(address _address) external onlyOwner returns (IS); - - /** - /// @notice Turn Agent in the ecosystem to on/off. - /// @param _address toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function toggle(address _address) external onlyOwner returns (bool); - - /** - /// @notice Set the trust level of an Agent in the ecosystem. - /// @param _level toggle on/off a doer agent - // @dev `anybody` can retrieve the talent data in the contract - */ - function trust(Trust _level) returns (bytes32 Trust); - - event LogCall(address indexed from, address indexed to, address indexed origin, bytes _data); - -/* End of interface IERC_HUCAP_KEYSIGNING_EXTENSION */ -} - -``` -#### Human Capital Accounting Extension Interface - -```solidity -pragma solidity ^0.4.25; -pragma experimental ABIEncoderV2; - -interface IERC_HUCAP_TRACKUSERS_EXTENSION { - - /// @notice Instantiate an Agent in the ecosystem with default data. - /// @param _address initialise a doer agent - // @dev `anybody` can retrieve the talent data in the contract - function initAgent(Doers _address) external onlyControlled returns (bool); - - /// @notice Get the data by uuid of an Agent in the ecosystem. - /// @param _uuid Get the address of a unique uid - // @dev `anybody` can retrieve the talent data in the contract - function getAgent(bytes32 _uuid) view external returns (address); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _address Query if address belongs to an agent - // @dev `anybody` can retrieve the talent data in the contract - function iam(address _address) view public returns (bool); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _address Query if address belongs to a doer - // @dev `anybody` can retrieve the talent data in the contract - function isDoer(address _address) view public returns (IS); - - /// @notice Get the number of doers that can be spawned by a Creators. - /// The query condition of the contract - // @dev `anybody` can retrieve the count data in the contract - function getAgent(address _address) - view public returns (bytes32 keyid_, IS state_, bool active_, uint myDoers_); - - /// @notice Get the data of all Talents in the ecosystem. - /// @param _talent The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function getTalents(bytes32 _talent) - view external returns (uint talentK_, uint talentI_, uint talentR_, uint talentF_); - - /// @notice Increment a kind of talent in the ecosystem. - /// @param The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function incTalent() payable public onlyDoer returns (bool); - - /// @notice Decrement a kind of talent in the ecosystem.. - /// @param The talent whose frequency is being queried - // @dev `anybody` can retrieve the talent data in the contract - function decTalent() payable public onlyDoer returns (bool); - - /// @notice Set the Public-Key Id of an Agent in the ecosystem. - /// @param _address Set the Public-key Id of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, bytes32 _keyId) external onlyControlled returns (bytes32); - - /// @notice Transition the states of an Agent in the ecosystem. - /// @param _address Set the stance of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, IS _state) external onlyControlled returns (IS); - - /// @notice Set the active status of an Agent in the ecosystem. - /// @param _address Toggle the true/false status of an agent - // @dev `anybody` can retrieve the talent data in the contract - function setAgent(address _address, bool _active) external onlyControlled returns (bool); - - /// @notice Set the data of all Intentions of Agents in the ecosystem. - /// @param _serviceId Track number of offers available - // @dev `anybody` can retrieve the talent data in the contract - function setAllPromises(bytes32 _serviceId) external onlyControlled; - -/* End of interface IERC_HUCAP_TRACKUSERS_EXTENSION */ -} - - -``` -## Rationale -[WIP] - -## Backwards Compatibility -[WIP] - -## Test Cases -[WIP] - -## Implementation -[WIP] - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1491.md diff --git a/EIPS/eip-1504.md b/EIPS/eip-1504.md index afed611194173d..3badb18dfe7716 100644 --- a/EIPS/eip-1504.md +++ b/EIPS/eip-1504.md @@ -1,351 +1,7 @@ --- eip: 1504 -title: Upgradable Smart Contract -author: Kaidong Wu , Chuqiao Ren , Ruthia He , Yun Ma , Xuanzhe Liu -discussions-to: https://github.com/ethereum/EIPs/issues/1503 -status: Stagnant -type: Standards Track category: ERC -created: 2018-10-17 +status: Moved --- -## Simple Summary - -A standard interface/guideline that makes a smart contract upgradable. - -## Abstract - -Ethereum smart contracts have suffered a number of security issues in the past few years. The cost of fixing such a bug in smart contract is significant; for example, the consequences of The DAO attack in June 2016 caused tremendous financial loss and the hard fork of Ethereum blockchain. - -The following standard makes it possible to upgrade a standard API within smart contracts. This standard provides basic functionalities to upgrade the operations of the contract without data migration. To ensure the decentralization/community interests, it also contains a voting mechanism to control the upgrading process. - -## Motivation - -Smart contract is immutable after deployment. If any security risk is identified or program bug is detected, developers always have to destruct the old contract, deploy a new one and potentially migrate the data (hard fork) to the new contract. In some cases, deploying a smart contract with bugs and potential security vulnerabilities can cause a significant amount of financial loss. - -We propose this upgradable contract to fix the current situation. With the upgradable contract, developers can deploy a new version of smart contract after previous deployment and retain the data at the same time. - -For example, after an ERC20-compliant token contract is deployed, the users exploit a vulnerability in the source code. Without the support of upgradable contract, developers have to fix this issue by deploy a new, secured contract otherwise the attackers would take advantage of the security hole, which may cause a tremendous financial loss. A challenge is how to migrate data from the old contract to a new one. With the upgradable contract below, this will become relatively easy as developers only have to upgrade the Handler contract to fix bugs while the Data contract will remain the same. - -## Specification - -The upgradable contract consists of three parts: - -- **Handler contract** (implements **Handler interface**) defines operations and provides services. This contract can be upgraded; -- **Data contract** keeps the resources (data) and is controlled by the Handler contract; -- **Upgrader contract (optional)** deals with the voting mechanism and upgrades the Handler contract. The voters are pre-defined by the contract owner. - -> The following codes are exact copies of the [ERC-1504 Upgradable Smart Contract.](https://gist.github.com/swordghost/77c96a972106af6ec6ccea9c2d66e768) - -### Handler contract and Handler interface - -Functions of the Handler contract vary with requirements, so developers would better design interfaces for Handler contracts to limit them and make sure external applications are always supported. - -Below is the specification of Handler interface. In the Handler interface we define the following actions: - -- Initialize the Data contract; -- Register the Upgrader contract address; -- Destruct the Handler contract after upgrading is done; -- Verify the current Handler is the working one → it should always return true. - -Developers have to define their business-related functions as well. - - -```solidity -/// Handler interface. -/// Handler defines business related functions. -/// Use the interface to ensure that your external services are always supported. -/// Because of function live(), we design IHandler as an abstract contract rather than a true interface. -contract IHandler { - - /// Initialize the data contarct. - /// @param _str value of exmStr of Data contract. - /// @param _int value of exmInt of Data contract. - /// @param _array value of exmArray of Data contract. - function initialize (string _str, uint256 _int, uint16 [] _array) public; - - /// Register Upgrader contract address. - /// @param _upgraderAddr address of the Upgrader contract. - function registerUpgrader (address _upgraderAddr) external; - - /// Upgrader contract calls this to check if it is registered. - /// @return if the Upgrader contract is registered. - function isUpgraderRegistered () external view returns(bool); - - /// Handler has been upgraded so the original one has to self-destruct. - function done() external; - - /// Check if the Handler contract is a working Handler contract. - /// It is used to prove the contract is a Handler contract. - /// @return always true. - function live() external pure returns(bool) { - return true; - } - - /** Functions - define functions here */ - - /** Events - add events here */ -} -``` - - -The process of deploying a Handler contract: - -1. Deploy Data contract; -2. Deploy a Handler contract at a given address specified in the Data contract; -3. Register the Handler contract address by calling setHandler() in the Data contract, or use an Upgrader contract to switch the Handler contract, which requires that Data contract is initialized; -4. Initialize Data contract if haven’t done it already. - -### Data Contract - -Below is the specification of Data contract. There are three parts in the Data contract: - -- **Administrator Data**: owner’s address, Handler contract’s address and a boolean indicating whether the contract is initialized or not; -- **Upgrader Data**: Upgrader contract’s address, upgrade proposal’s submission timestamp and proposal’s time period; -- **Resource Data**: all other resources that the contract needs to keep and manage. - - -```solidity -/// Data Contract -contract DataContract { - - /** Management data */ - /// Owner and Handler contract - address private owner; - address private handlerAddr; - - /// Ready? - bool private valid; - - /** Upgrader data */ - address private upgraderAddr; - uint256 private proposalBlockNumber; - uint256 private proposalPeriod; - /// Upgrading status of the Handler contract - enum UpgradingStatus { - /// Can be upgraded - Done, - /// In upgrading - InProgress, - /// Another proposal is in progress - Blocked, - /// Expired - Expired, - /// Original Handler contract error - Error - } - - /** Data resources - define variables here */ - - /** Modifiers */ - - /// Check if msg.sender is the Handler contract. It is used for setters. - /// If fail, throw PermissionException. - modifier onlyHandler; - - /// Check if msg.sender is not permitted to call getters. It is used for getters (if necessary). - /// If fail, throw GetterPermissionException. - modifier allowedAddress; - - /// Check if the contract is working. - /// It is used for all functions providing services after initialization. - /// If fail, throw UninitializationException. - modifier ready; - - /** Management functions */ - - /// Initializer. Just the Handler contract can call it. - /// @param _str default value of this.exmStr. - /// @param _int default value of this.exmInt. - /// @param _array default value of this.exmArray. - /// exception PermissionException msg.sender is not the Handler contract. - /// exception ReInitializationException contract has been initialized. - /// @return if the initialization succeeds. - function initialize (string _str, uint256 _int, uint16 [] _array) external onlyHandler returns(bool); - - /// Set Handler contract for the contract. Owner must set one to initialize the Data contract. - /// Handler can be set by owner or Upgrader contract. - /// @param _handlerAddr address of a deployed Handler contract. - /// @param _originalHandlerAddr address of the original Handler contract, only used when an Upgrader contract want to set the Handler contract. - /// exception PermissionException msg.sender is not the owner nor a registered Upgrader contract. - /// exception UpgraderException Upgrader contract does not provide a right address of the original Handler contract. - /// @return if Handler contract is successfully set. - function setHandler (address _handlerAddr, address _originalHandlerAddr) external returns(bool); - - /** Upgrader contract functions */ - - /// Register an Upgrader contract in the contract. - /// If a proposal has not been accepted until proposalBlockNumber + proposalPeriod, it can be replaced by a new one. - /// @param _upgraderAddr address of a deployed Upgrader contract. - /// exception PermissionException msg.sender is not the owner. - /// exception UpgraderConflictException Another Upgrader contract is working. - /// @return if Upgrader contract is successfully registered. - function startUpgrading (address _upgraderAddr) public returns(bool); - - /// Getter of proposalPeriod. - /// exception UninitializationException uninitialized contract. - /// exception GetterPermissionException msg.sender is not permitted to call the getter. - /// @return this.proposalPeriod. - function getProposalPeriod () public view isReady allowedAddress returns(uint256); - - /// Setter of proposalPeriod. - /// @param _proposalPeriod new value of this.proposalPeriod. - /// exception UninitializationException uninitialized contract. - /// exception PermissionException msg.sender is not the owner. - /// @return if this.proposalPeriod is successfully set. - function setProposalPeriod (uint256 _proposalPeriod) public isReady returns(bool); - - /// Return upgrading status for Upgrader contracts. - /// @param _originalHandlerAddr address of the original Handler contract. - /// exception UninitializationException uninitialized contract. - /// @return Handler contract's upgrading status. - function canBeUpgraded (address _originalHandlerAddr) external view isReady returns(UpgradingStatus); - - /// Check if the contract has been initialized. - /// @return if the contract has been initialized. - function live () external view returns(bool); - - /** Getters and setters of data resources: define functions here */ -} -``` - - -### Upgrader Contract (Optional) - -Handler contract can be upgraded by calling setHandler() of Data contract. If the owner wants to collect ideas from users, an Upgrader contract will help him/her manage voting and upgrading. - -Below is the specification of Upgrader contract: - -- The Upgrader contract has the ability to take votes from the registered voters. - - The contract owner is able to add voters any time before the proposal expires; - - Voter can check the current status of the proposal (succeed or expired). -- Developers are able to delete this Upgrader contract by calling done() any time after deployment. - -The Upgrader contract works as follows: - -1. Verify the Data contract, its corresponding Handler contract and the new Handler contract have all been deployed; -2. Deploy an Upgrader contract using Data contract address, previous Handler contract address and new Handler contract address; -3. Register upgrader address in the new Handler contract first, then the original handler and finally the Data contract; -4. Call startProposal() to start the voting process; -5. Call getResolution() before the expiration; -6. Upgrading succeed or proposal is expired. - -Note: - -- Function done() can be called at any time to let upgrader destruct itself. -- Function status() can be called at any time to show caller status of the upgrader. - - -```solidity -/// Handler upgrader -contract Upgrader { - // Data contract - DataContract public data; - // Original Handler contract - IHandler public originalHandler; - // New Handler contract - address public newHandlerAddr; - - /** Marker */ - enum UpgraderStatus { - Preparing, - Voting, - Success, - Expired, - End - } - UpgraderStatus public status; - - /// Check if the proposal is expired. - /// If so, contract would be marked as expired. - /// exception PreparingUpgraderException proposal has not been started. - /// exception ReupgradingException upgrading has been done. - /// exception ExpirationException proposal is expired. - modifier notExpired { - require(status != UpgraderStatus.Preparing, "Invalid proposal!"); - require(status != UpgraderStatus.Success, "Upgrading has been done!"); - require(status != UpgraderStatus.Expired, "Proposal is expired!"); - if (data.canBeUpgraded(address(originalHandler)) != DataContract.UpgradingStatus.InProgress) { - status = UpgraderStatus.Expired; - require(false, "Proposal is expired!"); - } - _; - } - - /// Start voting. - /// Upgrader must do upgrading check, namely checking if Data contract and 2 Handler contracts are ok. - /// exception RestartingException proposal has been already started. - /// exception PermissionException msg.sender is not the owner. - /// exception UpgraderConflictException another upgrader is working. - /// exception NoPreparationException original or new Handler contract is not prepared. - function startProposal () external; - - /// Anyone can try to get resolution. - /// If voters get consensus, upgrade the Handler contract. - /// If expired, self-destruct. - /// Otherwise, do nothing. - /// exception PreparingUpgraderException proposal has not been started. - /// exception ExpirationException proposal is expired. - /// @return status of proposal. - function getResolution() external returns(UpgraderStatus); - - /// Destruct itself. - /// exception PermissionException msg.sender is not the owner. - function done() external; - - /** Other voting mechanism related variables and functions */ -} -``` - - -### Caveats - -Since the Upgrader contract in [ERC-1504](./eip-1504.md) has a simple voting mechanism, it is prone to all the limitations that the voting contract is facing: - -- The administrator can only be the owner of data and Handler contracts. Furthermore, only the administrator has the power to add voters and start a proposal. -- It requires voters to be constantly active, informative and attentive to make a upgrader succeed. -- The voting will only be valid in a given time period. If in a given time period the contract cannot collect enough “yes” to proceed, the proposal will be marked expired. - -## Rationale - -### Data Contract and Handler Contract - -A smart contract is actually a kind of software, which provides some kind of services. From the perspective of software engineering, a service consists of **resources** that abstract the data and **operations** that abstract the process logic on the data. The requirement of upgrading is mostly on the logic part. Therefore, in order to make a smart contract upgradable, we divide it into two parts: - -1. Data contract keeps the resources; -2. Handler contract contains operations. - -The Handler contract can be upgraded in the future while the Data contract is permanent. Handler contract can manipulate the variables in Data contract through the getter and setter functions provided by Data contract. - -### Upgrader Contract and Voting Mechanism - -In order to prevent centralization and protect the interests of the community and stakeholders, we also design a voting mechanism in the Upgrader contract. Upgrader contract contains addresses of Data contract and two Handler contracts, and collects votes from pre-defined voters to upgrade the Handler contract when the pre-set condition is fulfilled. - -For simplicity, the upgradable contract comes with a very minimal version of the voting mechanism. If the contract owner wants to implement a more complex voting mechanism, he/she can modify the existing voting mechanism to incorporate upgradability. The expiration mechanism (see modifier notExpried in Upgrader contract and related functions in Data contract) and upgrading check (see function startProposal() in Upgrader contract) to the contract are mandatory. - -### Gas and Complexity (regarding the enumeration extension) - -Using an upgrader will cost some gas. If the Handler contract is upgraded by the owner, it just costs gas that a contract call will cost, which is usually significantly lower than creating and deploying a new contract. - -Although upgrading contract may take some efforts and gas, it is a much less painful than deprecating the insecure contract/creating a new contract or hard fork (e.g. DAO attack). Contract creation requires a significant amount of effort and gas. One of the advantages of upgradable contracts is that the contract owners don’t have to create new contracts; instead, they only need to upgrade parts of contract that cause issues, which is less expensive compared to data loss and blockchain inconsistency. In other words, upgradable contracts make Data contract more scalable and flexible. - -### Community Consensus - -Thank you to those who helped on review and revise the proposal: - -- [@lsankar4033](https://github.com/lsankar4033) from MIT -- more - -The proposal is initiated and developed by the team Renaissance and the Research Group of Blockchain System @ Center for Operating System at Peking University. - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Implementations - -1. [Renaissance](https://www.renaissance.app) - a protocol that connect creators and fans financially -2. [ERC-1504](./eip-1504.md) - a reference implementation - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1504.md diff --git a/EIPS/eip-1523.md b/EIPS/eip-1523.md index 2469e83d69d4a9..a74d332e5eb318 100644 --- a/EIPS/eip-1523.md +++ b/EIPS/eip-1523.md @@ -1,125 +1,7 @@ --- eip: 1523 -title: Standard for Insurance Policies as ERC-721 Non Fungible Tokens -author: Christoph Mussenbrock (@christoph2806) -discussions-to: https://github.com/ethereum/EIPs/issues/1523 -status: Stagnant -type: Standards Track category: ERC -created: 2018-10-10 -requires: 721 +status: Moved --- -## Simple Summary -A standard interface for insurance policies, based on ERC 721. - -## Abstract -The following standard allows for the implementation of a standard API for insurance policies within smart contracts. -Insurance policies are financial assets which are unique in some aspects, as they are connected to a customer, a specific risk, or have other unique properties like premium, period, carrier, underwriter etc. -Nevertheless, there are many potential applications where insurance policies can be traded, transferred or otherwise treated as an asset. -The ERC 721 standard already provides the standard and technical means to handle policies as a specific class of non fungible tokens. -insurance In this proposal, we define a minimum metadata structure with properties which are common to the greatest possible class of policies. - -## Motivation -For a decentralized insurance protocol, a standard for insurance policies is crucial for interoperability of the involved services and application. -It allows policies to be bundled, securitized, traded in a uniform and flexible way by many independent actors like syndicates, brokers, and insurance companies. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -An ERC-1523 compliant insurance policy is a non-fungible token which **MUST adhere to the ERC-721 token standard** and **MUST implement theERC721Metadata and the ERC721Enumerable interface**: - -```solidity -/// @title ERC-1523 Insurance Policy Standard -/// Note: the ERC-165 identifier for this interface is 0x5a04be32 -interface ERC1523 /* is ERC721, ERC721Metadata, ERC721Enumerable */ { - -} -``` - -The implementor MAY choose values for the ```name``` and ```symbol```. - -The **policy metadata extension** is **RECOMMENDED** for ERC-1523 smart contracts. -This allows your smart contract to be interrogated for policy metadata. - -```solidity -/// @title ERC-1523 Insurance Policy Standard, optional policy metadata extension -/// @dev See ... -/// Note: the ERC-165 identifier for this interface is 0x5a04be32 -interface ERC1523PolicyMetadata /* is ERC1523 */ { - - /// @notice Metadata string for a given property. - /// Properties are identified via hash of their property path. - /// e.g. the property "name" in the ERC721 Metadata JSON Schema has the path /properties/name - /// and the property path hash is the keccak256() of this property path. - /// this allows for efficient addressing of arbitrary properties, as the set of properties is potentially unlimited. - /// @dev Throws if `_propertyPathHash` is not a valid property path hash. - function policyMetadata(uint256 _tokenId, bytes32 _propertyPathHash) external view returns (string _property); - -} -``` - -In analogy to the “ERC721 Metadata JSON Schema”, the tokenURI **MUST** point to a JSON file with the following properties: -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents", - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents", - }, - \[additional parameters according to the following table\] - } -} -``` - -### Additional parameters for the metadata JSON Schema - -| Parameter | Type | Mandatory | Description | -| ------------- | ------------- | ----------| ---------------------------------------------------------------------------------- | -| carrier | string | yes | Describes the carrier which takes the primary risk | -| risk | string | yes | Describes the risk | -| status | string | yes | Describes the status of the policy, e.g. applied for, underwritten, expired | -| parameters | string | no | Describes further parameters characterizing the risk | -| terms | string | no | Describes legal terms & conditions which apply for this policy | -| premium | string | no | A string representation of the premium, **MAY** contain currency denominator | -| sum_insured | string | no | A string representation of the sum insured, **MAY** contain currency denominator | - -Parameters which are mandatory **MUST** be included in the metadata JSON. Other parameters **MAY** be included. However, the proposed optional parameters **SHOULD** be used for the intended purpose, so e.g. if the premium amount would be included in the metadata, the parameter name **SHOULD** be "premium". -All parameters **MAY** be plain text or **MAY** also be URIs pointing to resources which contain the respective information, and which **MAY** be protected by an authentication mechanism. - -## Rationale -Insurance policies form an important class of financial assets, and it is natural to express those assets as a class of non-fungible tokens which adhere to the established ERC-721 standard. -We propose a standard for the accompanying metadata structures which are needed to uniquely define an insurance policy. Standardization is key because we expect decentralized insurance to receive widespread adoption and it is crucial to establish a unified standard to enable composability and the creation of universal toolsets. -We therefore propose a standardized naming scheme for the different parameters describing an insurance policy. We propose three mandatory parameters which need to be included in every NFT and further parameters which **MAY** be used, and for which we only standardize the naming conventions. -### Mandatory parameters -While policies can have a multitude of possible properties, it is common that policies are issued by some entity, which is basically the entity responsible for paying out claims. -Second, an insurance policy is typically related to a specific risk. Some risks are unique, but there are cases where many policies share the same risk -(e.g. all flight delay policies for the same flight). -In general, the relation of policies to risks is a many-to-one relation with the special case of a one-to-one relation. -Third, a policy has a lifecycle of different statuses. Therefore the NFT -We believe that those four properties are necessary to describe a policy. For many applications, those properties may be even sufficient. - -### Optional parameters -Most policies need more parameters to characterize the risk and other features, like premium, period etc. The naming conventions are listed in the above table. -However, any implementation **MAY** chose to implement more properties. - -### On-chain vs. off-chain metadata -For some applications it will be sufficient to store the metadata in an off-chain repository or database which can be addressed by the tokenURI resource locator. -For more advanced applications, it can be desirable to have metadata available on-chain. -Therefore, we require that the ```tokenURI``` **MUST** point to a JSON with the above structure, while the implementation of the ```policyMetadata``` function is **OPTIONAL**. - - -## Backwards Compatibility - -## Test Cases - -## Implementation - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1523.md diff --git a/EIPS/eip-1538.md b/EIPS/eip-1538.md index afa991a7e7961d..f984a6b46164e9 100644 --- a/EIPS/eip-1538.md +++ b/EIPS/eip-1538.md @@ -1,468 +1,7 @@ --- eip: 1538 -title: Transparent Contract Standard -author: Nick Mudge -discussions-to: https://github.com/ethereum/EIPs/issues/1538 -status: Withdrawn -type: Standards Track category: ERC -created: 2018-10-31 +status: Moved --- -Replaced by [EIP-2535 Diamond Standard](./eip-2535.md). - -## Simple Summary -This standard provides a contract architecture that makes upgradeable contracts flexible, unlimited in size, and transparent. - -A transparent contract publicly documents the full history of all changes made to it. - -All changes to a transparent contract are reported in a standard format. - -## Abstract -A transparent contract is a proxy contract design pattern that provides the following: - -1. A way to add, replace and remove multiple functions of a contract atomically (at the same time). -1. Standard events to show what functions are added, replaced and removed from a contract, and why the changes are made. -2. A standard way to query a contract to discover and retrieve information about all functions exposed by it. -3. Solves the 24KB maximum contract size limitation, making the maximum contract size of a transparent contract practically unlimited. This standard makes the worry about contract size a thing of the past. -4. Enables an upgradeable contract to become immutable in the future if desired. - -## Motivation -A fundamental benefit of Ethereum contracts is that their code is immutable, thereby acquiring trust by trustlessness. People do not have to trust others if it is not possible for a contract to be changed. - -However, a fundamental problem with trustless contracts that cannot be changed is that they cannot be changed. - -#### Bugs - -Bugs and security vulnerabilities are unwittingly written into immutable contracts that ruin them. - -#### Improvements - -Immutable, trustless contracts cannot be improved, resulting in increasingly inferior contracts over time. - -Contract standards evolve, new ones come out. People, groups and organizations learn over time what people want and what is better and what should be built next. Contracts that cannot be improved not only hold back the authors that create them, but everybody who uses them. - -#### Upgradeable Contracts vs. Centralized Private Database -Why have an upgradeable contract instead of a centralized, private, mutable database? -Here are some reasons: -1. Because of the openness of storage data and verified code, it is possible to show a provable history of trustworthiness. -2. Because of the openness, bad behavior can be spotted and reported when it happens. -3. Independent security and domain experts can review the change history of contracts and vouch for their history of trustworthiness. -4. It is possible for an upgradeable contract to become immutable and trustless. -5. An upgradeable contract can have parts of it that are not upgradeable and so are partially immutable and trustless. - -#### Immutability - -In some cases immutable, trustless contracts are the right fit. This is the case when a contract is only needed for a short time or it is known ahead of time that there will never be any reason to change or improve it. - -### Middle Ground - -Transparent contracts provide a middle ground between immutable trustless contracts that can't be improved and upgradeable contracts that can't be trusted. - -### Purposes - -1. Create upgradeable contracts that earn trust by showing a provable history of trustworthiness. -2. Document the development of contracts so their development and change is provably public and can be understood. -3. Create upgradeable contracts that can become immutable in the future if desired. -4. Create contracts that are not limited by a max size. - -### Benefits & Use Cases -This standard is for use cases that benefit from the following: -1. The ability to add, replace or remove multiple functions of a contract atomically (at the same time). -2. Each time a function is added, replaced or removed, it is documented with events. -3. Build trust over time by showing all changes made to a contract. -4. Unlimited contract size. -5. The ability to query information about functions currently supported by the contract. -6. One contract address that provides all needed functionality and never needs to be replaced by another contract address. -7. The ability for a contract to be upgradeable for a time, and then become immutable. -8. Add trustless guarantees to a contract with "unchangeable functions". - -### New Software Possibilities - -This standard enables a form of contract version control software to be written. - -Software and user interfaces can be written to filter the `FunctionUpdate` and `CommitMessage` events of a contract address. Such software can show the full history of changes of any contract that implements this standard. - -User interfaces and software can also use this standard to assist or automate changes of contracts. - -## Specification - -> **Note:** -The solidity `delegatecall` opcode enables a contract to execute a function from another contract, but it is executed as if the function was from the calling contract. Essentially `delegatecall` enables a contract to "borrow" another contract's function. Functions executed with `delegatecall` affect the storage variables of the calling contract, not the contract where the functions are defined. - -### General Summary - -A transparent contract delegates or forwards function calls to it to other contracts using `delegatecode`. - -A transparent contract has an `updateContract` function that enables multiple functions to be added, replaced or removed. - -An event is emitted for every function that is added, replaced or removed so that all changes to a contract can be tracked in a standard way. - -A transparent contract is a contract that implements and complies with the design points below. - -### Terms - -1. In this standard a **delegate contract** is a contract that a transparent contract fallback function forwards function calls to using `delegatecall`. -2. In this standard an **unchangeable function** is a function that is defined directly in a transparent contract and so cannot be replaced or removed. - -### Design Points - -A contract is a transparent contract if it implements the following design points: - -1. A transparent contract is a contract that contains a fallback function, a constructor, and zero or more unchangeable functions that are defined directly within it. -2. The constructor of a transparent contract associates the `updateContract` function with a contract that implements the ERC1538 interface. The `updateContract` function can be an "unchangeable function" that is defined directly in the transparent contract or it can be defined in a delegate contract. Other functions can also be associated with contracts in the constructor. -3. After a transparent contract is deployed functions are added, replaced and removed by calling the `updateContract` function. -4. The `updateContract` function associates functions with contracts that implement those functions, and emits the `CommitMessage` and `FunctionUpdate` events that document function changes. -5. The `FunctionUpdate` event is emitted for each function that is added, replaced or removed. The `CommitMessage` event is emitted one time for each time the `updateContract` function is called and is emitted after any `FunctionUpdate` events are emitted. -6. The `updateContract` function can take a list of multiple function signatures in its `_functionSignatures` parameter and so add/replace/remove multiple functions at the same time. -7. When a function is called on a transparent contract it executes immediately if it is an "unchangeable function". Otherwise the fallback function is executed. The fallback function finds the delegate contract associated with the function and executes the function using `delegatecall`. If there is no delegate contract for the function then execution reverts. -8. The source code of a transparent contract and all delegate contracts used by it are publicly viewable and verified. - -The transparent contract address is the address that users interact with. The transparent contract address never changes. Only delegate addresses can change by using the `updateContracts` function. - -Typically some kind of authentication is needed for adding/replacing/removing functions from a transparent contract, **however the scheme for authentication or ownership is not part of this standard**. - -### Example - -Here is an example of an implementation of a transparent contract. Please note that the example below is an **example only. It is not the standard**. A contract is a transparent contract when it implements and complies with the design points listed above. - -```solidity -pragma solidity ^0.5.7; - -contract ExampleTransparentContract { - // owner of the contract - address internal contractOwner; - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - // maps functions to the delegate contracts that execute the functions - // funcId => delegate contract - mapping(bytes4 => address) internal delegates; - - // maps each function signature to its position in the funcSignatures array. - // signature => index+1 - mapping(bytes => uint256) internal funcSignatureToIndex; - - event CommitMessage(string message); - event FunctionUpdate(bytes4 indexed functionId, address indexed oldDelegate, address indexed newDelegate, string functionSignature); - - // this is an example of an "unchangeable function". - // return the delegate contract address for the supplied function signature - function delegateAddress(string calldata _functionSignature) external view returns(address) { - require(funcSignatureToIndex[bytes(_functionSignature)] != 0, "Function signature not found."); - return delegates[bytes4(keccak256(bytes(_functionSignature)))]; - } - - // add a function using the updateContract function - // this is an internal helper function - function addFunction(address _erc1538Delegate, address contractAddress, string memory _functionSignatures, string memory _commitMessage) internal { - // 0x03A9BCCF == bytes4(keccak256("updateContract(address,string,string)")) - bytes memory funcdata = abi.encodeWithSelector(0x03A9BCCF, contractAddress, _functionSignatures, _commitMessage); - bool success; - assembly { - success := delegatecall(gas, _erc1538Delegate, add(funcdata, 0x20), mload(funcdata), funcdata, 0) - } - require(success, "Adding a function failed"); - } - - constructor(address _erc1538Delegate) public { - contractOwner = msg.sender; - emit OwnershipTransferred(address(0), msg.sender); - - // adding ERC1538 updateContract function - bytes memory signature = "updateContract(address,string,string)"; - bytes4 funcId = bytes4(keccak256(signature)); - delegates[funcId] = _erc1538Delegate; - emit FunctionUpdate(funcId, address(0), _erc1538Delegate, string(signature)); - emit CommitMessage("Added ERC1538 updateContract function at contract creation"); - - // associate "unchangeable functions" with this transparent contract address - // prevents function selector clashes with delegate contract functions - // uses the updateContract function - string memory functions = "delegateAddress(string)"; - addFunction(_erc1538Delegate, address(this), functions, "Associating unchangeable functions"); - - // adding ERC1538Query interface functions - functions = "functionByIndex(uint256)functionExists(string)delegateAddresses()delegateFunctionSignatures(address)functionById(bytes4)functionBySignature(string)functionSignatures()totalFunctions()"; - // "0x01234567891011121314" is an example address of an ERC1538Query delegate contract - addFunction(_erc1538Delegate, 0x01234567891011121314, functions, "Adding ERC1538Query functions"); - - // additional functions could be added at this point - } - - // Making the fallback function payable makes it work for delegate contract functions - // that are payable and not payable. - function() external payable { - // Delegate every function call to a delegate contract - address delegate = delegates[msg.sig]; - require(delegate != address(0), "Function does not exist."); - assembly { - let ptr := mload(0x40) - calldatacopy(ptr, 0, calldatasize) - let result := delegatecall(gas, delegate, ptr, calldatasize, 0, 0) - let size := returndatasize - returndatacopy(ptr, 0, size) - switch result - case 0 {revert(ptr, size)} - default {return (ptr, size)} - } - } -} -``` -As can be seen in the above example, every function call is delegated to a delegate contract, unless the function is defined directly in the transparent contract (making it an unchangeable function). - -The constructor function adds the `updateContract` function to the transparent contract, which is then used to add other functions to the transparent contract. - -Each time a function is added to a transparent contract the events `CommitMessage` and `FunctionUpdate` are emitted to document exactly what functions where added or replaced and why. - -The delegate contract that implements the `updateContract` function implements the following interface: -### ERC1538 Interface - -```solidity -pragma solidity ^0.5.7; - -/// @title ERC1538 Transparent Contract Standard -/// @dev Required interface -/// Note: the ERC-165 identifier for this interface is 0x61455567 -interface ERC1538 { - /// @dev This emits when one or a set of functions are updated in a transparent contract. - /// The message string should give a short description of the change and why - /// the change was made. - event CommitMessage(string message); - - /// @dev This emits for each function that is updated in a transparent contract. - /// functionId is the bytes4 of the keccak256 of the function signature. - /// oldDelegate is the delegate contract address of the old delegate contract if - /// the function is being replaced or removed. - /// oldDelegate is the zero value address(0) if a function is being added for the - /// first time. - /// newDelegate is the delegate contract address of the new delegate contract if - /// the function is being added for the first time or if the function is being - /// replaced. - /// newDelegate is the zero value address(0) if the function is being removed. - event FunctionUpdate( - bytes4 indexed functionId, - address indexed oldDelegate, - address indexed newDelegate, - string functionSignature - ); - - /// @notice Updates functions in a transparent contract. - /// @dev If the value of _delegate is zero then the functions specified - /// in _functionSignatures are removed. - /// If the value of _delegate is a delegate contract address then the functions - /// specified in _functionSignatures will be delegated to that address. - /// @param _delegate The address of a delegate contract to delegate to or zero - /// to remove functions. - /// @param _functionSignatures A list of function signatures listed one after the other - /// @param _commitMessage A short description of the change and why it is made - /// This message is passed to the CommitMessage event. - function updateContract(address _delegate, string calldata _functionSignatures, string calldata _commitMessage) external; -} -``` -### Function Signatures String Format - -The text format for the `_functionSignatures` parameter is simply a string of function signatures. For example: `"myFirstFunction()mySecondFunction(string)"` This format is easy to parse and is concise. - -Here is an example of calling the `updateContract` function that adds the ERC721 standard functions to a transparent contract: -```javascript -functionSignatures = "approve(address,uint256)balanceOf(address)getApproved(uint256)isApprovedForAll(address,address)ownerOf(uint256)safeTransferFrom(address,address,uint256)safeTransferFrom(address,address,uint256,bytes)setApprovalForAll(address,bool)transferFrom(address,address,uint256)" -tx = await transparentContract.updateContract(erc721Delegate.address, functionSignatures, "Adding ERC721 functions"); -``` - -### Removing Functions - -Functions are removed by passing `address(0)` as the first argument to the `updateContract` function. The list of functions that are passed in are removed. - -### Source Code Verification - -The transparent contract source code and the source code for the delegate contracts should be verified in a provable way by a third party source such as etherscan.io. - - -### Function Selector Clash -A function selector clash occurs when a function is added to a contract that hashes to the same four-byte hash as an existing function. This is unlikely to occur but should be prevented in the implementation of the `updateContract` function. See the [reference implementation of ERC1538](https://github.com/mudgen/transparent-contracts-erc1538) to see an example of how function clashes can be prevented. - -### ERC1538Query - -Optionally, the function signatures of a transparent contract can be stored in an array in the transparent contract and queried to get what functions the transparent contract supports and what their delegate contract addresses are. - -The following is an optional interface for querying function information from a transparent contract: - -```solidity -pragma solidity ^0.5.7; - -interface ERC1538Query { - - /// @notice Gets the total number of functions the transparent contract has. - /// @return The number of functions the transparent contract has, - /// not including the fallback function. - function totalFunctions() external view returns(uint256); - - /// @notice Gets information about a specific function - /// @dev Throws if `_index` >= `totalFunctions()` - /// @param _index The index position of a function signature that is stored in an array - /// @return The function signature, the function selector and the delegate contract address - function functionByIndex(uint256 _index) - external - view - returns( - string memory functionSignature, - bytes4 functionId, - address delegate - ); - - /// @notice Checks to see if a function exists - /// @param The function signature to check - /// @return True if the function exists, false otherwise - function functionExists(string calldata _functionSignature) external view returns(bool); - - /// @notice Gets all the function signatures of functions supported by the transparent contract - /// @return A string containing a list of function signatures - function functionSignatures() external view returns(string memory); - - /// @notice Gets all the function signatures supported by a specific delegate contract - /// @param _delegate The delegate contract address - /// @return A string containing a list of function signatures - function delegateFunctionSignatures(address _delegate) external view returns(string memory); - - /// @notice Gets the delegate contract address that supports the given function signature - /// @param The function signature - /// @return The delegate contract address - function delegateAddress(string calldata _functionSignature) external view returns(address); - - /// @notice Gets information about a function - /// @dev Throws if no function is found - /// @param _functionId The id of the function to get information about - /// @return The function signature and the contract address - function functionById(bytes4 _functionId) - external - view - returns( - string memory signature, - address delegate - ); - - /// @notice Get all the delegate contract addresses used by the transparent contract - /// @return An array of all delegate contract addresses - function delegateAddresses() external view returns(address[] memory); -} -``` - -See the [reference implementation of ERC1538](https://github.com/mudgen/transparent-contracts-erc1538) to see how this is implemented. - -The text format for the list of function signatures returned from the `delegateFunctionSignatures` and `functionSignatures` functions is simply a string of function signatures. Here is an example of such a string: `"approve(address,uint256)balanceOf(address)getApproved(uint256)isApprovedForAll(address,address)ownerOf(uint256)safeTransferFrom(address,address,uint256)safeTransferFrom(address,address,uint256,bytes)setApprovalForAll(address,bool)transferFrom(address,address,uint256)"` - -### How To Deploy A Transparent Contract -1. Create and deploy to a blockchain a contract that implements the ERC1538 interface. You can skip this step if there is already such a contract deployed to the blockchain. -2. Create your transparent contract with a fallback function as given above. Your transparent contract also needs a constructor that adds the `updateContract` function. -3. Deploy your transparent contract to a blockchain. Pass in the address of the ERC1538 delegate contract to your constructor if it requires it. - -See the [reference implementation](https://github.com/mudgen/transparent-contracts-erc1538) for examples of these contracts. - -### Wrapper Contract for Delegate Contracts that Depend on Other Delegate Contracts -In some cases some delegate contracts may need to call external/public functions that reside in other delegate contracts. A convenient way to solve this problem is to create a contract that contains empty implementations of functions that are needed and import and extend this contract in delegate contracts that call functions from other delegate contracts. This enables delegate contracts to compile without having to provide implementations of the functions that are already given in other delegate contracts. This is a way to save gas, prevent reaching the max contract size limit, and prevent duplication of code. This strategy was given by @amiromayer. [See his comment for more information.](https://github.com/ethereum/EIPs/issues/1538#issuecomment-451985155) Another way to solve this problem is to use assembly to call functions provided by other delegate contracts. - -### Decentralized Authority -It is possible to extend this standard to add consensus functionality such as an approval function that multiple different people call to approve changes before they are submitted with the `updateContract` function. Changes only go into effect when the changes are fully approved. The `CommitMessage` and ` FunctionUpdate` events should only be emitted when changes go into effect. - -## Security -> This standard refers to **owner(s)** as one or more individuals that have the power to add/replace/remove functions of an upgradeable contract. - -### General - -The owners(s) of an upgradeable contract have the ability to alter, add or remove data from the contract's data storage. Owner(s) of a contract can also execute any arbitrary code in the contract on behalf of any address. Owners(s) can do these things by adding a function to the contract that they call to execute arbitrary code. This is an issue for upgradeable contracts in general and is not specific to transparent contracts. - ->**Note:** The design and implementation of contract ownership is **not** part of this standard. The examples given in this standard and in the reference implementation are just **examples** of how it could be done. - -### Unchangeable Functions - -"Unchangeable functions" are functions defined in a transparent contract itself and not in a delegate contract. The owner(s) of a transparent contract are not able to replace these functions. The use of unchangeable functions is limited because in some cases they can still be manipulated if they read or write data to the storage of the transparent contract. Data read from the transparent contract's storage could have been altered by the owner(s) of the contract. Data written to the transparent contract's storage can be undone or altered by the owner(s) of the contract. - -In some cases unchangeble functions add trustless guarantees to a transparent contract. - -### Transparency - -Contracts that implement this standard emit an event every time a function is added, replaced or removed. This enables people and software to monitor the changes to a contract. If any bad acting function is added to a contract then it can be seen. To comply with this standard all source code of a transparent contract and delegate contracts must be publicly available and verified. - -Security and domain experts can review the history of change of any transparent contract to detect any history of foul play. - -## Rationale - -### String of Function Signatures Instead of bytes4[] Array of Function Selectors - -The `updateContract` function takes a `string` list of functions signatures as an argument instead of a `bytes4[]` array of function selectors for three reasons: - -1. Passing in function signatures enables the implementation of `updateContract` to prevent selector clashes. -2. A major part of this standard is to make upgradeable contracts more transparent by making it easier to see what has changed over time and why. When a function is added, replaced or removed its function signature is included in the FunctionUpdate event that is emitted. This makes it relatively easy to write software that filters the events of a contract to display to people what functions have been added/removed and changed over time without needing access to the source code or ABI of the contract. If only four-byte function selectors were provided this would not be possible. -3. By looking at the source code of a transparent contract it is not possible to see all the functions that it supports. This is why the ERC1538Query interface exists, so that people and software have a way to look up and examine or show all functions currently supported by a transparent contract. Function signatures are used so that ERC1538Query functions can show them. - -### Gas Considerations - -Delegating function calls does have some gas overhead. This is mitigated in two ways: -1. Delegate contracts can be small, reducing gas costs. Because it costs more gas to call a function in a contract with many functions than a contract with few functions. -2. Because transparent contracts do not have a max size limitation it is possible to add gas optimizing functions for use cases. For example someone could use a transparent contract to implement the ERC721 standard and implement batch transfer functions from the [ERC1412 standard](https://github.com/ethereum/EIPs/issues/1412) to help reduce gas (and make batch transfers more convenient). - -### Storage - -The standard does not specify how data is stored or organized by a transparent contract. But here are some suggestions: - -**Inherited Storage** - -1. The storage variables of a transparent contract consist of the storage variables defined in the transparent contract source code and the source code of delegate contracts that have been added. - -2. A delegate contract can use any storage variable that exists in a transparent contract as long as it defines within it all the storage variables that exist, in the order that they exist, up to and including the ones being used. - -3. A delegate contract can create new storage variables as long as it has defined, in the same order, all storage variables that exist in the transparent contract. - -Here is a simple way inherited storage could be implemented: - -1. Create a storage contract that contains the storage variables that your transparent contract and delegate contracts will use. -2. Make your delegate contracts inherit the storage contract. -3. If you want to add a new delegate contract that adds new storage variables then create a new storage contract that adds the new storage variables and inherits from the old storage contract. Use your new storage contract with your new delegate contract. -4. Repeat steps 2 or 3 for every new delegate contract. - - -**Unstructured Storage** - -Assembly is used to store and read data at specific storage locations. An advantage to this approach is that previously used storage locations don't have to be defined or mentioned in a delegate contract if they aren't used by it. - -**Eternal Storage** - -Data can be stored using a generic API based on the type of data. [See ERC930 for more information.](https://github.com/ethereum/EIPs/issues/930) - -### Becoming Immutable -It is possible to make a transparent contract become immutable. This is done by calling the `updateContract` function to remove the `updateContract` function. With this gone it is no longer possible to add, replace and remove functions. - -### Versions of Functions - -Software or a user can verify what version of a function is called by getting the delegate contract address of the function. This can be done by calling the `delegateAddress` function from the ERC1538Query interface if it is implemented. This function takes a function signature as an argument and returns the delegate contract address where it is implemented. - -### Best Practices, Tools and More Information - -> More information, tools, tutorials and best practices concerning transparent contracts need to be developed and published. - -Below is a growing list of articles concerning transparent contracts and their use. If you have an article about transparent contracts you would like to share then please submit a comment to this issue about it to get it added. - -[ERC1538: Future Proofing Smart Contracts and Tokens](https://coinjournal.net/erc1538-future-proofing-smart-contacts-and-tokens/) - -[The ERC1538 improving towards the “transparent contract” standard](https://www.crypto-economy.net/en/ethereum-eth-erc1538-transparent-contract-standard/) - -### Inspiration - -This standard was inspired by ZeppelinOS's implementation of [Upgradeability with vtables](https://github.com/zeppelinos/labs/tree/master/upgradeability_with_vtable). - -This standard was also inspired by the design and implementation of the [Mokens contract](https://etherscan.io/address/0xc1eab49cf9d2e23e43bcf23b36b2be14fc2f8838#code) from the [Mokens project](https://github.com/Mokens/MIPs/blob/master/MIPS/mip-2-Goals-and-Objectives.md). The Mokens contract has been [upgraded to implement this standard](https://etherscan.io/address/0x0ac5637fe62ec14fd9e237a81a9679d4adef701f#code). - - -## Backwards Compatibility -This standard makes a contract compatible with future standards and functionality because new functions can be added and existing functions can be replaced or removed. - -This standard future proofs a contract. - -## Implementation -A reference implementation of this standard is given in the [transparent-contracts-erc1538](https://github.com/mudgen/transparent-contracts-erc1538) repository. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1538.md diff --git a/EIPS/eip-1559.md b/EIPS/eip-1559.md index 4cfdc44dc470bb..26a5b739e1661f 100644 --- a/EIPS/eip-1559.md +++ b/EIPS/eip-1559.md @@ -21,7 +21,7 @@ The algorithm results in the base fee per gas increasing when blocks are above t The base fee per gas is burned. Transactions specify the maximum fee per gas they are willing to give to miners to incentivize them to include their transaction (aka: priority fee). Transactions also specify the maximum fee per gas they are willing to pay total (aka: max fee), which covers both the priority fee and the block's network fee per gas (aka: base fee). -The transaction will always pay the base fee per gas of the block it was included in, and they will pay the priority fee per gas set in the transaction, as long as the combined amount of the two fees doesn't exceed the transaction's maximum fee per gas. +Senders will always pay the base fee per gas of the block their transaction was included in, and they will pay the priority fee per gas set in the transaction, as long as the combined amount of the two fees doesn't exceed the transaction's maximum fee per gas. ## Motivation Ethereum historically priced transaction fees using a simple auction mechanism, where users send transactions with bids ("gasprices") and miners choose transactions with the highest bids, and transactions that get included pay the bid that they specify. This leads to several large sources of inefficiency: @@ -310,9 +310,6 @@ The datastructure that is passed into keccak256 to calculate the block hash is c ### GASPRICE Previous to this change, `GASPRICE` represented both the ETH paid by the signer per gas for a transaction as well as the ETH received by the miner per gas. As of this change, `GASPRICE` now only represents the amount of ETH paid by the signer per gas, and the amount a miner was paid for the transaction is no longer accessible directly in the EVM. -## Test Cases -TODO - ## Security Considerations ### Increased Max Block Size/Complexity This EIP will increase the maximum block size, which could cause problems if miners are unable to process a block fast enough as it will force them to mine an empty block. Over time, the average block size should remain about the same as without this EIP, so this is only an issue for short term size bursts. It is possible that one or more clients may handle short term size bursts poorly and error (such as out of memory or similar) and client implementations should make sure their clients can appropriately handle individual blocks up to max size. diff --git a/EIPS/eip-1577.md b/EIPS/eip-1577.md index c555e53fe11c35..97c2eae9470fb3 100644 --- a/EIPS/eip-1577.md +++ b/EIPS/eip-1577.md @@ -1,116 +1,7 @@ --- eip: 1577 -title: contenthash field for ENS -author: Dean Eigenmann , Nick Johnson -type: Standards Track category: ERC -status: Stagnant -created: 2018-11-13 +status: Moved --- -## Abstract - -This EIP introduces the new `contenthash` field for ENS resolvers, allowing for a better defined system of mapping names to network and content addresses. Additionally the `content` and `multihash` fields are deprecated. - -## Motivation - -Multiple applications including [Metamask](https://metamask.io/) and mobile clients such as [Status](https://status.im) have begun resolving ENS names to content hosted on distributed systems such as [IPFS](https://ipfs.io/) and [Swarm](https://swarm-guide.readthedocs.io). Due to the various ways content can be stored and addressed, a standard is required so these applications know how to resolve names and that domain owners know how their content will be resolved. - -The `contenthash` field allows for easy specification of network and content addresses in ENS. - -## Specification - -The field `contenthash` is introduced, which permits a wide range of protocols to be supported by ENS names. Resolvers supporting this field MUST return `true` when the `supportsInterface` function is called with argument `0xbc1c58d1`. - -The fields `content` and `multihash` are deprecated. - -The value returned by `contenthash` MUST be represented as a machine-readable [multicodec](https://github.com/multiformats/multicodec). The format is specified as follows: - -``` - -``` - -protoCodes and their meanings are specified in the [multiformats/multicodec](https://github.com/multiformats/multicodec) repository. - -The encoding of the value depends on the content type specified by the protoCode. Values with protocodes of 0xe3 and 0xe4 represent IPFS and Swarm content; these values are encoded as v1 [CIDs](https://github.com/multiformats/cid) without a base prefix, meaning their value is formatted as follows: - -``` - -``` - -When resolving a `contenthash`, applications MUST use the protocol code to determine what type of address is encoded, and resolve the address appropriately for that protocol, if supported. - -### Example - -#### IPFS - -Input data: - -``` -storage system: IPFS (0xe3) -CID version: 1 (0x01) -content type: dag-pb (0x70) -hash function: sha2-256 (0x12) -hash length: 32 bytes (0x20) -hash: 29f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f -``` - -Binary format: - -``` -0xe3010170122029f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f -``` - -Text format: - -``` -ipfs://QmRAQB6YaCyidP37UdDnjFY5vQuiBrcqdyoW1CuDgwxkD4 -``` - -### Swarm - -Input data: - -``` -storage system: Swarm (0xe4) -CID version: 1 (0x01) -content type: swarm-manifest (0xfa) -hash function: keccak256 (0x1b) -hash length: 32 bytes (0x20) -hash: d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Binary format: -``` -0xe40101fa011b20d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Text format: -``` -bzz://d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -Example usage with swarm hash: -``` -$ swarm hash ens contenthash d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -> e40101fa011b20d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162 -``` - -### Fallback - -In order to support names that have an IPFS or Swarm hash in their `content` field, a grace period MUST be implemented offering those name holders time to update their names. If a resolver does not support the `multihash` interface, it MUST be checked whether they support the `content` interface. If they do, the value of that field SHOULD be treated in a context dependent fashion and resolved. This condition MUST be enforced until at least March 31st, 2019. - -### Implementation - -To support `contenthash`, a new resolver has been developed and can be found [here](https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol), you can also find this smart contract deployed on: - -* Mainnet : [0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3](https://etherscan.io/address/0xd3ddccdd3b25a8a7423b5bee360a42146eb4baf3) -* Ropsten : [0xde469c7106a9fbc3fb98912bb00be983a89bddca](https://ropsten.etherscan.io/address/0xde469c7106a9fbc3fb98912bb00be983a89bddca) - -There are also implementations in multiple languages to encode and decode `contenthash`: - -* [JavaScript](https://github.com/pldespaigne/content-hash) -* [Python](https://github.com/filips123/ContentHashPy) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1577.md diff --git a/EIPS/eip-1581.md b/EIPS/eip-1581.md index d4634d745bc145..3dc95e93e5a2da 100644 --- a/EIPS/eip-1581.md +++ b/EIPS/eip-1581.md @@ -1,49 +1,7 @@ --- eip: 1581 -title: Non-wallet usage of keys derived from BIP-32 trees -description: A derivation path structure for BIP32 trees to generate key pairs not meant to hold crypto assets. -author: Michele Balistreri (@bitgamma) -discussions-to: https://ethereum-magicians.org/t/non-wallet-usage-of-keys-derived-from-bip-32-trees/1817 -status: Stagnant -type: Standards Track category: ERC -created: 2018-11-13 +status: Moved --- -## Abstract -BIP32 defines a way to generate hierarchical trees of keys which can be derived from a common master key. BIP32 and [BIP44](https://https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) defines the usage of these keys as wallets. In this EIP we describe the usage of such keys outside the scope of the blockchain defining a logical tree for key usage which can coexist (and thus share the same master) with existing BIP44 compatible wallets. -## Motivation -Applications interacting with the blockchain often make use of additional, non-blockchain technologies to perform the task they are designed for. For privacy and security sensitive mechanisms, sets of keys are needed. Reusing keys used for wallets can prove to be insecure, while keeping completely independent keys make backup and migration of the full set of credentials more complex. Defining a separate (from BIP44 compliant wallets) derivation branch allows combining the security of independent keys with the convenience of having a single piece of information which needs to be backup or migrated. - -## Specification - -### Path levels -We define the following levels in BIP32 path: - -```m / purpose' / coin_type' / subpurpose' / key_type' / key_index``` - -Apostrophe in the path indicates that BIP32 hardened derivation is used. - -This structure follows the [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) recommendations and its [amendments for non-Bitcoin usage](https://github.com/bitcoin/bips/pull/523/files). Each level has a special meaning, described in the chapters below. - -### Purpose/Coin Type/Subpurpose -This part is constant and set to ```m / 43' / 60' / 1581'```, meaning BIP 43 -> Ethereum -> This EIP. - -All subtrees under this prefix are the scope of this EIP. - -### Key type -Describes the purpose for which the key is being used. Key types should be generic. "Instant messaging" is a good example whereas "Whisper" is not. The reason is that you want to be able to use the same identity across different services. Key types are defined at: TBD - -Hardened derivation is used at this level. - -### Key index -The key index is a field of variable length identifying a specific key. In its simplest case, it is a number from 0 to 2^31-1. If a larger identifier is desired (for example representing a hash or a GUID), the value must be split -across several BIP32 nesting levels, most significant bit first and left aligned, bit-padded with 0s if needed. All levels, except the last one must used hardened key derivation. The last level must use public derivation. This means that every level can carry 31-bit of the identifier to represent. - -As an example, let's assume we have a key with key type 4' and a key_index representing a 62-bit ID represented as hexadecimal 0x2BCDEFFEDCBAABCD the complete keypath would be ```m / 43' / 60' / 1581' / 4' / ‭1469833213‬' / ‭1555737549‬ ```. If you are using random identifiers, it might be convenient to generate a conventional GUID, for example 128-bit just fix the value of the most significant bit of each 32-bit word to 1 for all of them, except the last one which will be 0. - -## Rationale -The structure proposed above follows the BIP43 generic structure and is similar to the widely adopted BIP44 specification. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1581.md diff --git a/EIPS/eip-1592.md b/EIPS/eip-1592.md index dd97e594393df0..5e8d2293249514 100644 --- a/EIPS/eip-1592.md +++ b/EIPS/eip-1592.md @@ -1,171 +1,7 @@ --- eip: 1592 -title: Address and ERC20-compliant transfer rules -author: Cyril Lapinte , Laurent Aapro -discussions-to: https://github.com/ethereum/EIPs/issues/1597 -type: Standards Track category: ERC -status: Stagnant -created: 2018-11-09 +status: Moved --- -## Simple Summary - -We propose a standard and an interface to define transfer rules, in the context of ERC20 tokens and possibly beyond. - - -A rule can act based on sender, destination and amount, and is triggered (and rejects the transfer) according to any required business logic. - - -To ease rule reusability and composition, we also propose an interface and base implementation for a rule engine. - -## Abstract - -This standard proposal should answer the following challenges: -- Enable integration of rules with interacting platforms such as exchanges, decentralized wallets and DApps. -- Externale code and storage, improve altogether reusability, gas costs and contracts' memory footprint. -- Highlight contract behavior and its evolution, in order to ease user interaction with such contract. - - -If these challenges are answered, this proposal will provide a unified basis for transfer rules and hopefully address the transfer restriction needs of other EIPs as well, e.g. -[EIP-902](./eip-902.md), -[EIP-1066](./eip-1066.md) -and [EIP-1175](./eip-1175.md). - -This document proposes specifications for a standard of **transfer rules** and interfaces to both the rules and the rule engine, which was made to be inherited by a token, but may have a much broader scope in the authors' opinion. - -The last section of this document illustrates the proposal with a rule template and links to rule implementations. - -## Motivation - -ERC20 was designed as a standard interface allowing any token on Ethereum to be handled by other applications: from wallets to decentralized exchanges. This has been extremely powerful, but future developments in the industry of tokenization are bringing new challenges. For example it is already hard to know exactly why an ERC20 transfer failed, and it will become even harder when many tokens add their own transfer rules to the mix; we propose that it should be trivial to determine before a tx is sent, whether the transfer should turn out valid or invalid, and why (unless conditions change in the meantime obviously). On the other hand, if the rules were changed, it should also be easily detected, so that the interacting party knows it must adjust its expectations or model. - -## Specification - -We define below an interface for a rule. Rules are meant to be as simple as possible, to limit gas expenditure, since that logic will be executed on every transfer. Another reason for keeping rules simple and short, and strive for atomicity, is to facilitate both composition and interpretation of rejected transfers. By knowing which rule was triggered, we obtain a clear picture of the reason for rejection. - -The engine we propose executes all the rules defined by its owner, on every transfer and it is easy to add and remove rules individually, although we have chosen to use quite a raw rule update method, to save on deployment costs, which are often tight when it comes to token smart contracts. - -Rules are deployed on the blockchain as individual smart contracts, and called upon by the rule engine they were attached to. But any third party, for example an exchange preparing a cashout for a customer, can very cheaply query the rule engine of the token, or a single rule directly, to verify the validity of a transfer before execution, so as to never get a rejected transaction. - -## Rule interface - -`IRule` interface should provide a way to validate if an address or a transfer is valid. - -If one of these two methods is not applicable, it can simply be made to return true systematically. -If any parameter of `isTransferValid` is not needed, its name should be commented out with `/* */`. - -```js -pragma solidity ^0.4.25; - -interface IRule { - function isAddressValid(address _address) external view returns (bool); - function isTransferValid(address _from, address _to, uint256 _amount) - external view returns (bool); -} -``` - -## WithRules interface - -`WithRules` interface describes the integration of rules to a rule engine. -Developers may choose to not implement this interface if their code will only deal with one rule, or if it is not desirable to update the rules. - -The rules ordering must be thought through carefully. -Rules which are cheaper to validate or have a higher chance to break should be put first to reduce global gas expenditure, then business logic should guide the ordering of rules. That is why rules for a given context should be defined as a whole and not individually. - -```js -pragma solidity ^0.4.25; - -import "./IRule.sol"; - -interface IWithRules { - function ruleLength() public view returns (uint256); - function rule(uint256 _ruleId) public view returns (IRule); - function validateAddress(address _address) public view returns (bool); - function validateTransfer(address _from, address _to, uint256 _amount) - public view returns (bool); - - function defineRules(IRule[] _rules) public; - - event RulesDefined(uint256 count); -} -``` - -## WithRules implementation - -We also propose a simple implementation of the rule engine, available [here](https://github.com/MtPelerin/MtPelerin-protocol/blob/master/contracts/rule/WithRules.sol). It has been kept minimal both to save on gas costs on each transfer, and to reduce the deployment cost overhead for the derived smart contract. - - -On top of implementing the interface above, this engine also defines two modifiers (`whenAddressRulesAreValid`and `whenTransferRulesAreValid`), which can be used throughout the token contract to restrict `transfer()`, `transferFrom` and any other function that needs to respect either a simple whitelist or complex transfer rules. - - -## Integration - -To use rules within a token is as easy as having the token inherit from WithRules, then writing rules according to the IRule interface and deploying each rule individually. The token owner can then use `defineRules()` to attach all rules in the chosen order, within a single transaction. - -Below is a template for a rule. - -```solidity -import "../interface/IRule.sol"; - -contract TemplateRule is IRule { - - // state vars for business logic - - constructor(/* arguments for init */) public { - - // initializations - - } - - function isAddressValid(address _from) public view returns (bool) { - boolean isValid; - - // business logic - - return isValid; - } - - function isTransferValid( - address _from, - address _to, - uint256 _amount) - public view returns (bool) - { - boolean isValid; - - // business logic - - return isValid; - } -} -``` - -*** Notes *** -The MPS (Mt Pelerin's Share) token is the current live implementation of this standard. -Other implementations may be written with different trade-offs: from gas savings to improved security. - -#### Example of rules implementations - -- [YesNo rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/YesNoRule.sol): Trivial rule used to demonstrate both a rule and the rule engine. - -- [Freeze rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/FreezeRule.sol): This rule allows to prevent any transfer of tokens to or from chosen addresses. A smart blacklist. - -- [Lock rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/LockRule.sol): Define a global transfer policy preventing either sending or receiving tokens within a period of time. Exceptions may be granted to some addresses by the token admin. A smart whitelist. - -- [User Kyc Rule](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule/UserKycRule.sol): Rule example relying on an existing whitelist to assert transfer and addresses validity. It is a good example of a rule that completely externalizes it's tasks. - -#### Example implementations are available at -- [Mt Pelerin Bridge protocol rules implementation](https://github.com/MtPelerin/MtPelerin-protocol/tree/master/contracts/rule) -- [Mt Pelerin Token with rules](https://github.com/MtPelerin/MtPelerin-protocol/blob/master/contracts/token/component/TokenWithRules.sol) - -## History - -Historical links related to this standard: - -- The first regulated tokenized share issued by Mt Pelerin (MPS token) is using an early version of this proposal: https://www.mtpelerin.com/blog/world-first-tokenized-shares -The rule engine was updated several times, after the token issuance and during the tokensale, to match changing business and legal requirements, showcasing the solidity and flexibility of the rule engine. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). -External references outside this repository will have their own specific copyrights. +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1592.md diff --git a/EIPS/eip-161.md b/EIPS/eip-161.md index 0d63e92c48008f..b746c239881f24 100644 --- a/EIPS/eip-161.md +++ b/EIPS/eip-161.md @@ -66,4 +66,4 @@ On 2016-11-24, a consensus bug occurred due to two implementations having differ 1. EIP-158 issue and discussion: https://github.com/ethereum/EIPs/issues/158 2. EIP-161 issue and discussion: https://github.com/ethereum/EIPs/issues/161 3. https://blog.ethereum.org/2016/11/25/security-alert-11242016-consensus-bug-geth-v1-4-19-v1-5-2/ -> Details: Geth was failing to revert empty account deletions when the transaction causing the deletions of empty accounts ended with an an out-of-gas exception. An additional issue was found in Parity, where the Parity client incorrectly failed to revert empty account deletions in a more limited set of contexts involving out-of-gas calls to precompiled contracts; the new Geth behavior matches Parity’s, and empty accounts will cease to be a source of concern in general in about one week once the state clearing process finishes. +> Details: Geth was failing to revert empty account deletions when the transaction causing the deletions of empty accounts ended with an out-of-gas exception. An additional issue was found in Parity, where the Parity client incorrectly failed to revert empty account deletions in a more limited set of contexts involving out-of-gas calls to precompiled contracts; the new Geth behavior matches Parity’s, and empty accounts will cease to be a source of concern in general in about one week once the state clearing process finishes. diff --git a/EIPS/eip-1613.md b/EIPS/eip-1613.md index 287b5c759325ab..bcfccf6d9a323b 100644 --- a/EIPS/eip-1613.md +++ b/EIPS/eip-1613.md @@ -1,300 +1,7 @@ --- eip: 1613 -title: Gas stations network -author: Yoav Weiss , Dror Tirosh , Alex Forshtat -discussions-to: https://github.com/yoav-tabookey/EIPs/issues/1 -status: Stagnant -type: Standards Track category: ERC -created: 2018-11-18 -requires: 1077 +status: Moved --- -## Simple Summary -Make smart contracts (e.g. dapps) accessible to non-ether users by allowing contracts to accept "[collect-calls](https://en.wikipedia.org/wiki/Collect_call)", paying for incoming calls. -Let contracts "listen" on publicly accessible channels (e.g. web URL or a whisper address). -Incentivize nodes to run "gas stations" to facilitate this. -Require no network changes, and minimal contract changes. - -## Abstract -Communicating with dapps currently requires paying ETH for gas, which limits dapp adoption to ether users. -Therefore, contract owners may wish to pay for the gas to increase user acquisition, or let their users pay for gas with fiat money. -Alternatively, a 3rd party may wish to subsidize the gas costs of certain contracts. -Solutions such as described in [EIP-1077](./eip-1077.md) could allow transactions from addresses that hold no ETH. - -The gas stations network is an [EIP-1077](./eip-1077.md) compliant effort to solve the problem by creating an incentive for nodes to run gas stations, where gasless transactions can be "fueled up". -It abstracts the implementation details from both the dapp maintainer and the user, making it easy to convert existing dapps to accept "collect-calls". - -The network consists of a single public contract trusted by all participating dapp contracts, and a decentralized network of relay nodes (gas stations) incentivized to listen on non-ether interfaces such as web or whisper, -pay for transactions and get compensated by that contract. The trusted contract can be verified by anyone, and the system is otherwise trustless. -Gas stations cannot censor transactions as long as there's at least one honest gas station. Attempts to undermine the system can be proven on-chain and offenders can be penalized. - -## Motivation - -* Increase user adoption of smart contracts by: - * Removing the user hassle of acquiring ETH. Transactions are still paid by ETH but costs can be borne by the dapp or paid by the user through other means. - * Removing the need to interact directly with the blockchain, while maintaining decentralization and censorship-resistance. - Contracts can "listen" on multiple public channels, and users can interact with the contracts through common protocols that are generally permitted even in restrictive environments. -* Ethereum nodes get a revenue source without requiring mining equipment. The entire network benefits from having more nodes. -* No protocol changes required. The gas station network is self-organized via a smart contract, and dapps interact with the network by implementing an interface. - -## Specification - -The system consists of a `RelayHub` singleton contract, participating contracts inheriting the `RelayRecipient` contract, a decentralized network of `Relay` nodes, a.k.a. Gas Stations, -and user applications (e.g. mobile or web) interacting with contracts via relays. - -Roles of the `RelayHub`: - -* Maintain a list of active relays. Senders select a `Relay` from this list for each transaction. The selection process is discussed below. -* Mediate all communication between relays and contracts. -* Provide contracts with trusted versions of the real msg.sender and msg.data. -* Hold ETH stakes placed by relays. A minimum stake size is enforced. Stake can be withdrawn after a relay unregisters and waits for a cooldown period. -* Hold ETH prepayments made by contracts and use them to compensate relays. -* Penalize provably-offensive relays by giving their stakes to an address providing the proof, thus keeping relays honest. -* Provide a free way for relays to know whether they'll be compensated for a future transaction. - -Roles of a `Relay` node: - -* Maintain a hot wallet with a small amount of ETH, to pay for gas. -* Provide a public interface for user apps to send gasless transactions via channels such as https or whisper. -* Publish it's public interfaces and its price (as a multiplier of the actual transaction gas cost) in `RelayHub`. -* Optionally monitor reverted transactions of other relays through RelayHub, catching offending relays and claiming their stakes. This can be done by anyone, not just a relay. - -Implementing a `RelayRecipient` contract: - -* Know the address of `RelayHub` and trust it to provide information about the transaction. -* Maintain a small balance of ETH gas prepayment deposit in `RelayHub`. Can be paid directly by the `RelayRecipient` contract, or by the dapp's owner on behalf of the `RelayRecipient` address. - The dapp owner is responsible for ensuring sufficient balance for the next transactions, and can stop depositing if something goes wrong, thus limiting the potential for abuse of system bugs. In DAO usecases it will be up to the DAO logic to maintain a sufficient deposit. -* Use `getSender()` and `getMessageData()` instead of `msg.sender` and `msg.data`, everywhere. `RelayRecipient` provides these functions and gets the information from `RelayHub`. -* Implement a `acceptRelayedCall(address relay, address from, bytes memory encodedFunction, uint gasPrice, uint transactionFee, bytes memory approval)` view function that returns **zero** if and only if it is willing to accept a transaction and pay for it. - `acceptRelayedCall` is called by `RelayHub` as a view function when a `Relay` inquires it, and also during the actual transaction. Transactions are reverted if **non-zero**, and `Relay` only gets compensated for transactions (whether successful or reverted) if `acceptRelayedCall` returns **zero**. Some examples of `acceptRelayedCall()` implementations: - * Whitelist of trusted dapp members. - * Balance sheet of registered users, maintained by the dapp owner. Users pay the dapp with a credit card or other non-ETH means, and are credited in the `RelayRecipient` balance sheet. - Users can never cost the dapp more than they were credited for. - * A dapp can provide off-chain a signed message called `approval` to a transaction sender and validate it. - * Whitelist of known transactions used for onboarding new users. This allows certain anonymous calls and is subject to Sybil attacks. - Therefore it should be combined with a restricted gasPrice, and a whitelist of trusted relays, to reduce the incentive for relays to create bogus transactions and rob the dapp's prepaid gas deposit. - Dapps allowing anonymous onboarding transactions might benefit from registering their own `Relay` and accepting anonymous transactions only from that `Relay`, whereas other transactions can be accepted from any relay. - Alternatively, dapps may use the balance sheet method for onboarding as well, by applying the methods suggested in the attacks/mitigations section below. -* Implement `preRelayedCall(address relay, address from, bytes memory encodedFunction, uint transactionFee) returns (bytes32)`. This method is called before a transaction is relayed. By default, it does nothing. - -* Implement `postRelayedCall(ddress relay, address from, bytes memory encodedFunction, bool success, uint usedGas, uint transactionFee, bytes32 preRetVal)`. This method is called after a transaction is relayed. By default, it does nothing. - - These two methods can be used to charge the user in dapp-specific manner. - -Glossary of terms used in the processes below: - -* `RelayHub` - the RelayHub singleton contract, used by everyone. -* `Recipient` - a contract implementing `RelayRecipient`, accepting relayed transactions from the RelayHub contract and paying for the incoming transactions. -* `Sender` - an external address with a valid key pair but no ETH to pay for gas. -* `Relay` - a node holding ETH in an external address, listed in RelayHub and relaying transactions from Senders to RelayHub for a fee. - -![Sequence Diagram](/assets/eip-1613/sequence.png) - -The process of registering/refreshing a `Relay`: - -* Relay starts listening as a web app (or on some other communication channel). -* If starting for the first time (no key yet), generate a key pair for Relay's address. -* If Relay's address doesn't hold sufficient funds for gas (e.g. because it was just generated), Relay stays inactive until its owner funds it. -* Relay's owner funds it. -* Relay's owner sends the required stake to `RelayHub` by calling `RelayHub.stake(address relay, uint unstakeDelay)`. -* `RelayHub` puts the `owner` and `unstake delay` in the relays map, indexed by `relay` address. -* Relay calls `RelayHub.registerRelay(uint transactionFee, string memory url)` with the relay's `transaction fee` (as a multiplier on transaction gas cost), and a URL for incoming transactions. -* `RelayHub` ensures that Relay has a sufficient stake. -* `RelayHub` puts the `transaction fee` in the relays map. -* `RelayHub` emits an event, `RelayAdded(Relay, owner, transactionFee, relayStake, unstakeDelay, url)`. -* Relay starts a timer to perform a `keepalive` transaction every 6000 blocks. -* `Relay` goes to sleep and waits for signing requests. - -The process of sending a relayed transaction: - -* `Sender` selects a live `Relay` from RelayHub's list by looking at `RelayAdded` events from `RelayHub`, and sorting based on its own criteria. Selection may be based on a mix of: - * Relay published transaction fees. - * Relay stake size and lock-up time. - * Recent relay transactions (visible through `TransactionRelayed` events from `RelayHub`). - * Optionally, reputation/blacklist/whitelist held by the sender app itself, or its backend, on per-app basis (not part of the gas stations network). -* Sender prepares the transaction with Sender's address, the recipient address, the actual transaction data, Relay's transaction fee, gas price, gas limit, its current nonce from `RelayHub.nonces`, RelayHub's address, and Relay's address, and then signs it. -* Sender verifies that `RelayHub.balances[recipient]` holds enough ETH to pay Relay's fee. -* Sender verifies that `Relay.balance` has enough eth to send the transaction -* Sender reads the Relay's current `nonce` value and decides on the `max_nonce` parameter. -* Sender sends the signed transaction amd metadata to Relay's web interface. -* `Relay` wraps the transaction with a transaction to `RelayHub`, with zero ETH value. -* `Relay` signs the wrapper transaction with its key in order to pay for gas. -* `Relay` verifies that: - * The transaction's recipient contract will accept this transaction when submitted, by calling `RelayHub.canRelay()`, a view function, - which checks the recipient's `acceptRelayedCall`, also a view function, stating whether it's willing to accept the charges). - * The transaction nonce matches `RelayHub.nonces[sender]`. - * The relay address in the transaction matches Relay's address. - * The transaction's recipient has enough ETH deposited in `RelayHub` to pay the transaction fee. - * Relay has enough ETH to pay for the gas required by the transaction. - * Value of `max_nonce` is higher than current Relay's `nonce` -* If any of Relay's checks fail, it returns an error to sender, and doesn't proceed. -* Relay submits the signed wrapped transaction to the blockchain. -* Relay immediately returns the signed wrapped transaction to the sender. This step is discussed below, in attacks/mitigations. -* `Sender` receives the wrapped transaction and verifies that: - * It's a valid relay call to `RelayHub`. from Relay's address. - * The transaction's ethereum nonce matches Relay's current nonce. - * The transaction's ethereum nonce is lower than or equal to `max_nonce`. - * `Relay` is sufficiently funded to pay for it. - * The wrapped transaction is valid and signed by `sender`. - * Recipient contract has sufficient funds in `RelayHub.balances` to pay for Relay's fee as stated in the transaction. -* If any of sender's checks fails, it goes back to selecting a new Relay. Sender may also file a report on the unresponsive relay to its backend or save it locally, to down-sort this relay in future transactions. -* `Sender` may also submit the raw wrapped transaction to the blockchain without paying for gas, through any Ethereum node. - This submission is likely ignored because an identical transaction is already in the network's pending transactions, but no harm in putting it twice, to ensure that it happens. - This step is not strictly necessary, for reasons discussed below in attacks/mitigations, but may speed things up. -* `Sender` monitors the blockchain, waiting for the transaction to be mined. - The transaction was verified, with Relay's current nonce, so mining must be successful unless Relay submitted another (different) transaction with the same nonce. - If mining fails due to such attack, sender may call `RelayHub.penalizeRepeatedNonce` through another relay, to collect his reward and burn the remainder of the offending relay's stake, and then go back to selecting a new Relay for the transaction. - See discussion in the attacks/mitigations section below. -* `RelayHub` receives the transaction: - * Records `gasleft()` as `initialGas` for later payment. - * Verifies the transaction is sent from a registered relay. - * Verifies that the signature of the internal transaction matches its stated origin (sender's key). - * Verifies that the relay address written in the transaction matches msg.sender. - * Verifies that the transaction's `nonce` matches the stated origin's nonce in `RelayHub.nonces`. - * Calls recipient's `acceptRelayedCall` function, asking whether it's going to accept the transaction. If not, the `TransactionRelayed` will be emitted with status `CanRelayFailed`, and `chargeOrCanRelayStatus` will contain the return value of `acceptRelayedCall`. In this case, Relay doesn't get paid, as it was its responsibility to check `RelayHub.canRelay` before releasing the transaction. - * Calls recipient's `preRelayedCall` function. If this call reverts the `TransactionRelayed` will be emitted with status `PreRelayedFailed`. - * Sends the transaction to the recipient. If this call reverts the `TransactionRelayed` will be emitted with status `RelayedCallFailed`. - When passing gas to `call()`, enough gas is preserved by `RelayHub`, for post-call handling. Recipient may run out of gas, but `RelayHub` never does. - `RelayHub` also sends sender's address at the end of `msg.data`, so `RelayRecipient.getSender()` will be able to extract the real sender, and trust it because the transaction came from the known `RelayHub` address. -* Recipient contract handles the transaction. -* `RelayHub` calls recipient's `postRelayedCall`. -* `RelayHub` checks call's return value of call, and emits `TransactionRelayed(address relay, address from, address to, bytes4 selector, uint256 status, uint256 chargeOrCanRelayStatus)`. -* `RelayHub` increases `RelayHub.nonces[sender]`. -* `RelayHub` transfers ETH balance from recipient to `Relay.owner`, to pay the transaction fee, based on the measured transaction cost. - Note on relay payment: The relay gets paid for actual gas used, regardless of whether the recipient reverted. - The only case where the relay sustains a loss, is if `canRelay` returns non-zero, since the relay was responsible to verify this view function prior to submitting. - Any other revert is caught and paid for. See attacks/mitigations below. -* `Relay` keeps track of transactions it sent, and waits for `TransactionRelayed` events to see the charge. - If a transaction reverts and goes unpaid, which means the recipient's `acceptRelayedCall()` function was inconsistent, `Relay` refuses service to that recipient for a while (or blacklists it indefinitely, if it happens often). - See attacks/mitigations below. - -The process of winding a `Relay` down: - -* Relay's owner (the address that initially funded it) calls `RelayHub.removeRelayByOwner(Relay)`. -* `RelayHub` ensures that the sender is indeed Relay's owner, then removes `Relay`, and emits `RelayRemoved(Relay)`. -* `RelayHub` starts the countdown towards releasing the owner's stake. -* `Relay` receives its `RelayRemoved` event. -* `Relay` sends all its remaining ETH to its owner. -* `Relay` shuts down. -* Once the owner's unstake delay is over, owner calls `RelayHub.unstake()`, and withdraws the stake. - -## Rationale -The rationale for the gas stations network design is a combination of two sets of requirements: Easy adoption, and robustness. - -For easy adoption, the design goals are: - -* No network changes. -* Minimal changes to contracts, apps and frameworks. - -The robustness requirement translates to decentralization and attack resistance. The gas stations network is decentralized, and we have to assume that any entity may attack other entities in the system. - -Specifically we've considered the following types of attacks: - -* Denial-of-service attacks against individual senders, i.e. transactions censorship. -* Denial-of-service and financial attacks against individual relays. -* Denial-of-service and financial attacks against individual contracts. -* Denial-of-service attacks against the entire network, either by attacking existing entities, or by introducing any number of malicious entities. - -#### Attacks and mitigations - -##### Attack: Relay attempts to censor a transaction by not signing it, or otherwise ignoring a user request. -Relay is expected to return the signed transaction to the sender, immediately. -Sender doesn't need to wait for the transaction to be mined, and knows immediately whether it's request has been served. -If a relay doesn't return a signed transaction within a couple of seconds, sender cancels the operation, drops the connection, and switches to another relay. -It also marks Relay as unresponsive in its private storage to avoid using it in the near future. - -Therefore, the maximal damage a relay can cause with such attack, is a one-time delay of a couple of seconds. After a while, senders will avoid it altogether. - -##### Attack: Relay attempts to censor a transaction by signing it, returning it to the sender, but never putting it on the blockchain. -This attack will backfire and not censor the transaction. -The sender can submit the transaction signed by Relay to the blockchain as a raw transaction through any node, so the transaction does happen, -but Relay may be unaware and therefore be stuck with a bad nonce which will break its next transaction. - -##### Attack: Relay attempts to censor a transaction by signing it, but publishing a different transaction with the same nonce. -Reusing the nonce is the only DoS performed by a Relay, that cannot be detected within a couple of seconds during the http request. -It will only be detected when the malicious transaction with the same nonce gets mined and triggers the `RelayHub.TransactionRelayed` event. -However, the attack will backfire and cost Relay its entire stake. - -Sender has a signed transaction from Relay with nonce N, and also gets a mined transaction from the blockchain with nonce N, also signed by Relay. -This proves that Relay performed a DoS attack against the sender. -The sender calls `RelayHub.penalizeRepeatedNonce(bytes transaction1, bytes transaction2)`, which verifies the attack, confiscates Relay's stake, -and sends half of it to the sender who delivered the `penalizeRepeatedNonce` call. The other half of the stake is burned by sending it to `address(0)`. Burning is done to prevent cheating relays from effectively penalizing themselves and getting away without any loss. -The sender then proceeds to select a new relay and send the original transaction. - -The result of such attack is a delay of a few blocks in sending the transaction (until the attack is detected) but the relay gets removed and loses its entire stake. -Scaling such attack would be prohibitively expensive, and actually quite profitable for senders and honest relays. - -##### Attack: Relay attempts to censor a transaction by signing it, but using a nonce higher than it's current nonce. -In this attack, the Relay did create and return a perfectly valid transaction, but it will not be mined until this Relay fills the gap in the nonce with 'missing' transactions. -This may delay the relaying of some transactions indefinitely. In order to mitigate that, the sender includes a `max_nonce` parameter with it's signing request. -It is suggested to be higher by 2-3 from current nonce, to allow the relay process several transactions. - -When the sender receives a transaction signed by a Relay he validates that the nonce used is valid, and if it is not, the client will ignore the given relay and use other relays to relay given transaction. Therefore, there will be no actual delay introduced by such attack. - -##### Attack: Dapp attempts to burn relays funds by implementing an inconsistent acceptRelayedCall() and using multiple sender addresses to generate expensive transactions, thus performing a DoS attack on relays and reducing their profitability. -In this attack, a contract sets an inconsistent acceptRelayedCall (e.g. return zero for even blocks, nonzero for odd blocks), and uses it to exhaust relay resources through unpaid transactions. -Relays can easily detect it after the fact. -If a transaction goes unpaid, the relay knows that the recipient contract's acceptRelayedCall has acted inconsistently, because the relay has verified its view function before sending the transaction. -It might be the result of a rare race condition where the contract's state has changed between the view call and the transaction, but if it happens too frequently, relays will blacklist this contract and refuse to serve transactions to it. -Each offending contract can only cause a small damage (e.g. the cost of 2-3 transactions) to a relay, before getting blacklisted. - -Relays may also look at recipients' history on the blockchain, looking for past unpaid transactions (reverted by RelayHub without pay), and denying service to contracts with a high failure rate. -If a contract caused this minor loss to a few relays, all relays will stop serving it, so it can't cause further damage. - -This attack doesn't scale because the cost of creating a malicious contract is in the same order of magnitude as the damage it can cause to the network. -Causing enough damage to exhaust the resources of all relays, would be prohibitively expensive. - -The attack can be made even more impractical by setting RelayHub to require a stake from dapps before they can be served, and enforcing an unstaking delay, -so that attackers will have to raise a vast amount of ETH in order to simultaneously create enough malicious contracts and attack relays. -This protection is probably an overkill, since the attack doesn't scale regardless. - -##### Attack: User attempts to rob dapps by registering its own relay and sending expensive transactions to dapps. -If a malicious sender repeatedly abuses a recipient by sending meaningless/reverted transactions and causing the recipient to pay a relay for nothing, -it is the recipient's responsibility to blacklist that sender and have its acceptRelayedCall function return nonzero for that sender. -Collect calls are generally not meant for anonymous senders unknown to the recipient. -Dapps that utilize the gas station networks should have a way to blacklist malicious users in their system and prevent Sybil attacks. - -A simple method that mitigates such Sybil attack, is that the dapp lets users buy credit with a credit card, and credit their account in the dapp contract, -so acceptRelayedCall() only returns zero for users that have enough credit, and deduct the amount paid to the relay from the user's balance, whenever a transaction is relayed for the user. -With this method, the attacker can only burn its own resources, not the dapp's. - -A variation of this method, for free dapps (that don't charge the user, and prefer to pay for their users transactions) is to require a captcha during user creation in their web interface, -or to login with a Google/Facebook account, which limits the rate of the attack to the attacker's ability to open many Google/Facebook accounts. -Only a user that passed that process is given credit in RelayRecipient. The rate of such Sybil attack would be too low to cause any real damage. - -##### Attack: Attacker attempts to reduce network availability by registering many unreliable relays. -Registering a relay requires placing a stake in RelayHub, and the stake can only be withdrawn after the relay is unregistered and a long cooldown period has passed, e.g. a month. - -Each unreliable relay can only cause a couple of seconds delay to senders, once, and then it gets blacklisted by them, as described in the first attack above. -After it caused this minor delay and got blacklisted, the attacker must wait a month before reusing the funds to launch another unreliable relay. -Simultaneously bringing up a number of unreliable relays, large enough to cause a noticeable network delay, would be prohibitively expensive due to the required stake, -and even then, all those relays will get blacklisted within a short time. - -##### Attack: Attacker attempts to replay a relayed transaction. -Transactions include a nonce. RelayHub maintains a nonce (counter) for each sender. Transactions with bad nonces get reverted by RelayHub. Each transaction can only be relayed once. - -##### Attack: User does not execute the raw transaction received from the Relayer, therefore blocking the execution of all further transactions signed by this relayer -The user doesn't really have to execute the raw transaction. It's enough that the user can. The relationship between relay and sender is mutual distrust. The process described above incentivizes the relay to execute the transaction, so the user doesn't need to wait for actual mining to know that the transaction has been executed. - -Once relay returns the signed transaction, which should happen immediately, the relay is incentivized to also execute it on chain, so that it can advance its nonce and serve the next transaction. The user can (but doesn't have to) also execute the transaction. To understand why the attack isn't viable, consider the four possible scenarios after the signed transaction was returned to the sender: - -1. Relay executes the transaction, and the user doesn't. In this scenario the transaction is executed, so no problem. This is the case described in this attack. -2. Relay doesn't execute the transaction, but the user does. Similarly to 1, the transaction is executed, so no problem. -3. Both of them execute the transaction. The transactions are identical in the pending transactions pool, so the transaction gets executed once. No problem. -4. None of them execute the transaction. In this case the transaction doesn't get executed, but the relay is stuck. It can't serve the next transaction with the next nonce, because its nonce hasn't been advanced on-chain. It also can't serve the next transaction with the current nonce, as this can be proven by the user, having two different transactions signed by the same relay, with the same nonce. The user could use this to take the relay's nonce. So the relay is stuck unless it executes the transaction. - -As this matrix shows, the relay is __always__ incentivized to execute the transaction, once it returned it to the user, in order to end up in #1 or #3, and avoid the risk of #4. It's just a way to commit the relay to do its work, without requiring the user to wait for on-chain confirmation. - -## Backwards Compatibility - -The gas stations network is implemented as smart contracts and external entities, and does not require any network changes. - -Dapps adding gas station network support remain backwards compatible with their existing apps/users. The added methods apply on top of the existing ones, so no changes are required for existing apps. - -## Implementation - -A working implementation of the [**gas stations network**](https://github.com/tabookey-dev/tabookey-gasless) is being developed by **TabooKey**. It consists of `RelayHub`, `RelayRecipient`, `web3 hooks`, an implementation of a gas station inside `geth`, and sample dapps using the gas stations network. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1613.md diff --git a/EIPS/eip-1616.md b/EIPS/eip-1616.md index 52107d4a0a95cd..77e12726f4766d 100644 --- a/EIPS/eip-1616.md +++ b/EIPS/eip-1616.md @@ -1,387 +1,7 @@ --- eip: 1616 -title: Attribute Registry Standard -author: 0age (@0age), Santiago Palladino (@spalladino), Leo Arias (@elopio), Alejo Salles (@fiiiu), Stephane Gosselin (@thegostep) -discussions-to: https://github.com/ethereum/EIPs/issues/1616 -status: Stagnant -type: Standards Track category: ERC -created: 2018-11-23 -requires: 165 +status: Moved --- - -## Simple Summary -EIP-1616 provides a basic interface for querying a registry for attribute metadata assigned to Ethereum accounts. - -## Abstract -This EIP contains the following core ideas: -1. Instead of relying directly on the reputation of a claims issuer to assess the veracity of a given claim, trust can be brought up to the level of a registry curator. This registry which we call an "**Attribute Registry**" allows for reduced complexity in implementation since a party needing to verify an attribute can now work with a trusted claims aggregator instead of relying on individual claim providers. -2. Claims are abstracted as standard "attributes" which represent metadata assigned to an account, with claims decoupled from the issuing party. Attributes are registered as a flat `uint256 -> uint256` key-value pair on each account, with the important property that **each attribute type has one canonical value per address**. This property allows for composability of attribute registries and advanced attribute formation. -3. There is a generic method for determining the set of attribute keys or IDs made available by the registry. The standard does not specify requirements or recommendations for how attributes and their values are managed, or what additional metadata may be associated with attributes. It is likely that a standard set of attribute names and metadata schema could be proposed in a separate EIP. - -Potential advanced uses of attribute registries include: -* Encoding complex boolean expressions which combine multiple attributes into a single uint256 key, which is then parsed and evaluated by the registry logic. -* Using values associated with an attribute to query additional on-chain or off-chain metadata. -* Resolving attribute values by calling into separate attribute registries or other contracts, delegating authority without changing the interface of the registry. - -## Motivation -This EIP is motivated by the need for contracts and external accounts to be able to verify information about a given address from a single trusted source **without concerning themselves with the particular details of how the information was obtained**, and to do so in as simple a manner as possible. It is also motivated by the desire to promote broad **cross-compatibility and composability** between attribute registries, a property which is amplified by both the simplicity of the interface as well as by the guarantees on uniqueness provided by the proposed standard. - -Existing EIPs for assigning metadata to an account include EIP-735 and EIP-780, which both allow for multiple claims to be issued on the same address for any given claim topic. This forces verifiers of said metadata to assess the veracity of each claim, taking into account the relative reputation of each claim issuer. It also prescribes a methodology for adding and removing claims, which may not be appropriate for all use cases. - -This EIP proposes a light-weight abstraction layer for a standard account metadata registry interface. This abstraction layer can sit on top of claims registries like EIP-735 and EIP-780 or others as the attribute registry curator selects trusted data sources. - -## Specification -The Attribute Registry interface contains four functions, outlined as follows: -```solidity -/** - * @title EIP-1616 Attribute Registry Standard interface. EIP-165 ID: 0x5f46473f - */ -interface AttributeRegistryInterface { - function hasAttribute(address account, uint256 attributeTypeID) external view returns (bool); - function getAttributeValue(address account, uint256 attributeTypeID) external view returns (uint256); - function countAttributeTypes() external view returns (uint256); - function getAttributeTypeID(uint256 index) external view returns (uint256); -} -``` - -Contracts that comply with the Attribute Registry EIP MUST implement the above interface. - -As an additional requirement, the ERC-165 interface MUST be included: -```solidity -/** - * @title EIP-165 interface. EIP-165 ID: 0x01ffc9a7 - */ -interface EIP-165 { - /** - * @notice EIP-165 support. Attribute Registry interface ID is 0x5f46473f. - * @param _interfaceID The interface identifier, as specified in EIP-165 - * @return True for 0x01ffc9a7 & 0x5f46473f, false for unsupported interfaces. - */ - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} -``` - -The implementation MUST follow the specifications described below. - -### View Functions -The view functions detailed below MUST be implemented. - -#### `hasAttribute` function -```solidity -function hasAttribute(address account, uint256 attributeTypeID) external view returns (bool) -``` - -Check if an attribute has been assigned to a given account on the registry and is currently valid. - -_**NOTE**_: This function MUST return either true or false - i.e. calling this function MUST NOT cause the caller to revert. Implementations that wish to call into another contract during execution of this function MUST catch any `revert` and instead return `false`. - -_**NOTE**_: This function MUST return two equal values when performing two directly consecutive function calls with identical `account` and `attributeTypeID` parameters, regardless of differences in the caller's address, the transaction origin, or other out-of-band information. - - - -#### `getAttributeValue` function -```solidity -function getAttributeValue(address account, uint256 attributeTypeID) external view returns (uint256) -``` - -Retrieve the `uint256` value of an attribute on a given account on the registry, assuming the attribute is currently valid. - -_**NOTE**_: This function MUST revert if a directly preceding or subsequent function call to `hasAttribute` with identical `account` and `attributeTypeID` parameters would return false. - -_**NOTE**_: This function MUST return two equal values when performing two directly consecutive function calls with identical `account` and `attributeTypeID` parameters, regardless of differences in the caller's address, the transaction origin, or other out-of-band information. - -#### `countAttributeTypes` function -```solidity -function countAttributeTypes() external view returns (uint256) -``` - -Retrieve the total number of valid attribute types defined on the registry. Used alongside `getAttributeTypeID` to determine all of the attribute types that are available on the registry. - -_**NOTE**_: This function MUST return a positive integer value - i.e. calling this function MUST NOT cause the caller to revert. - -_**NOTE**_: This function MUST return a value that encompasses all indexes of attribute type IDs whereby a call to `hasAttribute` on some address with an attribute type ID at the given index would return `true`. - -#### `getAttributeTypeID` function -```solidity -function getAttributeTypeID(uint256 index) external view returns (uint256) -``` - -Retrieve an ID of an attribute type defined on the registry by index. Used alongside `countAttributeTypes` to determine all of the attribute types that are available on the registry. - -_**NOTE**_: This function MUST revert if the provided `index` value falls outside of the range of the value returned from a directly preceding or subsequent function call to `countAttributeTypes`. It MUST NOT revert if the provided `index` value falls inside said range. - -_**NOTE**_: This function MUST return an `attributeTypeID` value on *some* index if the same `attributeTypeID` value would cause a given call to `hasAttribute` to return `true` when passed as a parameter. - -## Rationale -This standard extends the applicability of metadata assignment to those use cases that are not adequately represented by EIP-735, EIP-780, or similar proposals. Namely, it enforces the constraint of one attribute value per attribute ID per address, as opposed to one value per ID per address *per issuer*. - -Aside from the prescribed attribute value, attribute properties are deliberately omitted from the standard. While many attribute registries will require additional metadata on attributes at both the instance and the class level, reliable and flexible interoperability between highly variable registry extensions is facilitated more effectively by enforcing a widely-applicable base layer for attributes. - -## Backwards Compatibility -There are no backwards compatibility concerns. - -## Test Cases -Targeted test cases with 100% code coverage can be found at [this repository](https://github.com/0age/AttributeRegistry). See [here](https://github.com/TPL-protocol/tpl-contracts) for tests on a more complex contract that implements the application registry interface. - -## Implementation -The basic implementation that follows can be found at [this repository](https://github.com/0age/AttributeRegistry) (see [here](https://github.com/TPL-protocol/tpl-contracts/blob/master/contracts/BasicJurisdiction.sol#L399) for an example of a more complex implementing contract): - -```solidity -pragma solidity ^0.4.25; - -/** - * @title Attribute Registry interface. EIP-165 ID: 0x5f46473f - */ -interface AttributeRegistryInterface { - /** - * @notice Check if an attribute of the type with ID `attributeTypeID` has - * been assigned to the account at `account` and is currently valid. - * @param account address The account to check for a valid attribute. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return True if the attribute is assigned and valid, false otherwise. - * @dev This function MUST return either true or false - i.e. calling this - * function MUST NOT cause the caller to revert. - */ - function hasAttribute( - address account, - uint256 attributeTypeID - ) external view returns (bool); - - /** - * @notice Retrieve the value of the attribute of the type with ID - * `attributeTypeID` on the account at `account`, assuming it is valid. - * @param account address The account to check for the given attribute value. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return The attribute value if the attribute is valid, reverts otherwise. - * @dev This function MUST revert if a directly preceding or subsequent - * function call to `hasAttribute` with identical `account` and - * `attributeTypeID` parameters would return false. - */ - function getAttributeValue( - address account, - uint256 attributeTypeID - ) external view returns (uint256); - - /** - * @notice Count the number of attribute types defined by the registry. - * @return The number of available attribute types. - * @dev This function MUST return a positive integer value - i.e. calling - * this function MUST NOT cause the caller to revert. - */ - function countAttributeTypes() external view returns (uint256); - - /** - * @notice Get the ID of the attribute type at index `index`. - * @param index uint256 The index of the attribute type in question. - * @return The ID of the attribute type. - * @dev This function MUST revert if the provided `index` value falls outside - * of the range of the value returned from a directly preceding or subsequent - * function call to `countAttributeTypes`. It MUST NOT revert if the provided - * `index` value falls inside said range. - */ - function getAttributeTypeID(uint256 index) external view returns (uint256); -} - - -/** - * @title A simple example of an Attribute Registry implementation. - */ -contract AttributeRegistry is AttributeRegistryInterface { - // This particular implementation just defines two attribute types. - enum Affiliation { Whitehat, Blackhat } - - // Top-level information about attribute types held in a static array. - uint256[2] private _attributeTypeIDs; - - // The number of attributes currently issued tracked in a static array. - uint256[2] private _issuedAttributeCounters; - - // Issued attributes held in a nested mapping by account & attribute type. - mapping(address => mapping(uint256 => bool)) private _issuedAttributes; - - // Issued attribute values held in a nested mapping by account & type. - mapping(address => mapping(uint256 => uint256)) private _issuedAttributeValues; - - /** - * @notice The constructor function, defines the two attribute types available - * on this particular registry. - */ - constructor() public { - // Set the attribute type IDs for whitehats (8008) and blackhats (1337). - _attributeTypeIDs = [8008, 1337]; - } - - /** - * @notice Assign a "whitehat" attribute type to `msg.sender`. - * @dev The function may not be called by accounts with a "blackhat" attribute - * type already assigned. This function is arbitrary and not part of the - * Attribute Registry specification. - */ - function joinWhitehats() external { - // Get the index of the blackhat attribute type on the attribute registry. - uint256 blackhatIndex = uint256(Affiliation.Blackhat); - - // Get the attribute type ID of the blackhat attribute type. - uint256 blackhatAttributeTypeID = _attributeTypeIDs[blackhatIndex]; - - // Do not allow the whitehat attribute to be set if blackhat is already set. - require( - !_issuedAttributes[msg.sender][blackhatAttributeTypeID], - "no blackhats allowed!" - ); - - // Get the index of the whitehat attribute type on the attribute registry. - uint256 whitehatIndex = uint256(Affiliation.Whitehat); - - // Get the attribute type ID of the whitehat attribute type. - uint256 whitehatAttributeTypeID = _attributeTypeIDs[whitehatIndex]; - - // Mark the attribute as issued on the given address. - _issuedAttributes[msg.sender][whitehatAttributeTypeID] = true; - - // Calculate the new number of total whitehat attributes. - uint256 incrementCounter = _issuedAttributeCounters[whitehatIndex] + 1; - - // Set the attribute value to the new total assigned whitehat attributes. - _issuedAttributeValues[msg.sender][whitehatAttributeTypeID] = incrementCounter; - - // Update the value of the counter for total whitehat attributes. - _issuedAttributeCounters[whitehatIndex] = incrementCounter; - } - - /** - * @notice Assign a "blackhat" attribute type to `msg.sender`. - * @dev The function may be called by any account, but assigned "whitehat" - * attributes will be removed. This function is arbitrary and not part of the - * Attribute Registry specification. - */ - function joinBlackhats() external { - // Get the index of the blackhat attribute type on the attribute registry. - uint256 blackhatIndex = uint256(Affiliation.Blackhat); - - // Get the attribute type ID of the blackhat attribute type. - uint256 blackhatAttributeTypeID = _attributeTypeIDs[blackhatIndex]; - - // Mark the attribute as issued on the given address. - _issuedAttributes[msg.sender][blackhatAttributeTypeID] = true; - - // Calculate the new number of total blackhat attributes. - uint256 incrementCounter = _issuedAttributeCounters[blackhatIndex] + 1; - - // Set the attribute value to the new total assigned blackhat attributes. - _issuedAttributeValues[msg.sender][blackhatAttributeTypeID] = incrementCounter; - - // Update the value of the counter for total blackhat attributes. - _issuedAttributeCounters[blackhatIndex] = incrementCounter; - - // Get the index of the whitehat attribute type on the attribute registry. - uint256 whitehatIndex = uint256(Affiliation.Whitehat); - - // Get the attribute type ID of the whitehat attribute type. - uint256 whitehatAttributeTypeID = _attributeTypeIDs[whitehatIndex]; - - // Determine if a whitehat attribute type has been assigned. - if (_issuedAttributes[msg.sender][whitehatAttributeTypeID]) { - // If so, delete the attribute. - delete _issuedAttributes[msg.sender][whitehatAttributeTypeID]; - - // Delete the attribute value as well. - delete _issuedAttributeValues[msg.sender][whitehatAttributeTypeID]; - - // Set the attribute value to the new total assigned whitehat attributes. - uint256 decrementCounter = _issuedAttributeCounters[whitehatIndex] - 1; - - // Update the value of the counter for total whitehat attributes. - _issuedAttributeCounters[whitehatIndex] = decrementCounter; - } - } - - /** - * @notice Get the total number of assigned whitehat and blackhat attributes. - * @return Array with counts of assigned whitehat and blackhat attributes. - * @dev This function is arbitrary and not part of the Attribute Registry - * specification. - */ - function totalHats() external view returns (uint256[2]) { - // Return the array containing counter values. - return _issuedAttributeCounters; - } - - /** - * @notice Check if an attribute of the type with ID `attributeTypeID` has - * been assigned to the account at `account` and is currently valid. - * @param account address The account to check for a valid attribute. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return True if the attribute is assigned and valid, false otherwise. - * @dev This function MUST return either true or false - i.e. calling this - * function MUST NOT cause the caller to revert. - */ - function hasAttribute( - address account, - uint256 attributeTypeID - ) external view returns (bool) { - // Return assignment status of attribute by account and attribute type ID - return _issuedAttributes[account][attributeTypeID]; - } - - /** - * @notice Retrieve the value of the attribute of the type with ID - * `attributeTypeID` on the account at `account`, assuming it is valid. - * @param account address The account to check for the given attribute value. - * @param attributeTypeID uint256 The ID of the attribute type to check for. - * @return The attribute value if the attribute is valid, reverts otherwise. - * @dev This function MUST revert if a directly preceding or subsequent - * function call to `hasAttribute` with identical `account` and - * `attributeTypeID` parameters would return false. - */ - function getAttributeValue( - address account, - uint256 attributeTypeID - ) external view returns (uint256 value) { - // Revert if attribute with given account & attribute type ID is unassigned - require( - _issuedAttributes[account][attributeTypeID], - "could not find a value with the provided account and attribute type ID" - ); - - // Return the attribute value. - return _issuedAttributeValues[account][attributeTypeID]; - } - - /** - * @notice Count the number of attribute types defined by the registry. - * @return The number of available attribute types. - * @dev This function MUST return a positive integer value - i.e. calling - * this function MUST NOT cause the caller to revert. - */ - function countAttributeTypes() external view returns (uint256) { - // Return the length of the attribute type IDs array. - return _attributeTypeIDs.length; - } - - /** - * @notice Get the ID of the attribute type at index `index`. - * @param index uint256 The index of the attribute type in question. - * @return The ID of the attribute type. - * @dev This function MUST revert if the provided `index` value falls outside - * of the range of the value returned from a directly preceding or subsequent - * function call to `countAttributeTypes`. It MUST NOT revert if the provided - * `index` value falls inside said range. - */ - function getAttributeTypeID(uint256 index) external view returns (uint256) { - // Revert if the provided index is out of range. - require( - index < _attributeTypeIDs.length, - "provided index is outside of the range of defined attribute type IDs" - ); - - // Return the attribute type ID at the given index in the array. - return _attributeTypeIDs[index]; - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1616.md diff --git a/EIPS/eip-162.md b/EIPS/eip-162.md index 03764438559841..3c028fa1f8a4f1 100644 --- a/EIPS/eip-162.md +++ b/EIPS/eip-162.md @@ -1,248 +1,7 @@ --- eip: 162 -title: Initial ENS Hash Registrar -author: Maurelian, Nick Johnson , Alex Van de Sande -status: Final -type: Standards Track category: ERC -created: 2016-10-25 +status: Moved --- -## Contents -- Abstract -- Motivations -- Specification - - Initial restrictions - - Name format for hash registration - - Auctioning names - - Deeds - - Deployment and Upgrade process - - Registrar Interface -- Rationale - - Not committing to a permanent registrar at the outset - - Valid names >= 7 characters - - Restricting TLD to `.eth` - - Holding ether as collateral -- Prior work - - - -## Abstract - -This ERC describes the implementation, as deployed to the main ethereum network on 2017-05-04, of a registrar contract to govern the allocation of names in the Ethereum Name Service (ENS). The corresponding source code is [here](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol). - -For more background, refer to [EIP-137](./eip-137.md). - -> Registrars are responsible for allocating domain names to users of the system, and are the only entities capable of updating the ENS; the owner of a node in the ENS registry is its registrar. Registrars may be contracts or externally owned accounts, though it is expected that the root and top-level registrars, at a minimum, will be implemented as contracts. -> -> \- EIP 137 - -A well designed and governed registrar is essential to the success of the ENS described in EIP 137, but is described separately in this document as it is external to the core ENS protocol. - -In order to maximize utility and adoption of a new namespace, the registrar should mitigate speculation and "name squatting", however the best approach for mitigation is unclear. Thus an "initial" registrar is proposed, which implements a simple approach to name allocation. During the initial period, the available namespace will be significantly restricted to the `.eth` top level domain, and subdomain shorter than 7 characters in length disallowed. This specification largely describes @alexvandesande and @arachnid's [hash registrar implementation](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol) in order to facilitate discussion. - -The intent is to replace the Initial Registrar contract with a permanent registrar contract. The Permanent Registrar will increase the available namespace, and incorporate lessons learned from the performance of the Initial Registrar. This upgrade is expected to take place within approximately 2 years of initial deployment. - -## Motivations - -The following factors should be considered in order to optimize for adoption of the ENS, and good governance of the Initial Registrar's namespace. - -**Upgradability:** The Initial Registrar should be safely upgradeable, so that knowledge gained during its deployment can be used to replace it with an improved and permanent registrar. - -**Effective allocation:** Newly released namespaces often create a land grab situation, resulting in many potentially valuable names being purchased but unused, with the hope of re-selling at a profit. This reduces the availability of the most useful names, in turn decreasing the utility of the name service to end users. - -Achieving an effective allocation may or may not require human intervention for dispute resolution and other forms of curation. The Initial Registrar should not aim to create to most effective possible allocation, but instead limit the cost of misallocation in the long term. - -**Security:** The registrar will hold a balance of ether without an explicit limit. It must be designed securely. - -**Simplicity:** The ENS specification itself emphasizes a separation of concerns, allowing the most essential element, the registry to be as simple as possible. The interim registrar in turn should be as simple as possible while still meeting its other design goals. - -**Adoption:** Successful standards become more successful due to network effects. The registrar should consider what strategies will encourage the adoption of the ENS in general, and the namespace it controls in particular. - -## Specification - -### Initial restrictions - -The Initial Registrar is expected to be in service for approximately two years, prior to upgrading. This should be sufficient time to learn, observe, and design an updated system. - -During the initial two year period, the available name space will be restricted to the `.eth` TLD. - -This restriction is enforced by the owner of the ENS root node who should not assign any nodes other than `.eth` to the Initial Registrar. The ENS's root node should be controlled by multiple parties using a multisig contract. - -The Initial Registrar will also prohibit registration of names 6 characters or less in length. - -### Name format for hash registration - -Names submitted to the initial registrar must be hashed using Ethereum's sha3 function. Note that the hashes submitted to the registrar are the hash of the subdomain label being registered, not the namehash as defined in EIP 137. - -For example, in order to register `abcdefg.eth`, one should submit `sha3('abcdefg')`, not `sha3(sha3(0, 'eth'), 'abcdefg')`. - -### Auctioning names - -The registrar will allocate the available names through a Vickrey auction: - -> A Vickrey auction is a type of sealed-bid auction. Bidders submit written bids without knowing the bid of the other people in the auction. The highest bidder wins but the price paid is the second-highest bid. This type of auction... gives bidders an incentive to bid their true value. -> -> \- [Vickrey Auction, Wikipedia](https://en.wikipedia.org/wiki/Vickrey_auction) - -The auction lifecycle of a name has 5 possible states, or Modes. - -1. **Not-yet-available:** The majority of names will be initially unavailable for auction, and will become available some time during the 8 weeks after launch. -2. **Open:** The earliest availability for a name is determined by the most significant byte of its sha3 hash. `0x00` would become available immediately, `0xFF` would become available after 8 weeks, and the availability of other names is distributed accordingly. Once a name is available, it is possible to start an auction on it. -3. **Auction:** Once the auction for a name has begun, there is a 72 hour bidding period. Bidders must submit a payment of ether, along with sealed bids as a hash of `sha3(bytes32 hash, address owner, uint value, bytes32 salt)`. The bidder may obfuscate the true bid value by sending a greater amount of ether. -4. **Reveal:** After the bidding period, a 48 hour reveal period commences. During this time, bidders must reveal the true parameters of their sealed bid. As bids are revealed, ether payments are returned according to the schedule of "refund ratios" outlined in the table below. If no bids are revealed, the name will return to the Open state. -5. **Owned:** After the reveal period has finished, the winning bidder must submit a transaction to finalize the auction, which then calls the ENS's `setSubnodeOwner` function, recording the winning bidder's address as the owner of the hash of the name. - -The following table outlines important parameters which define the Registrar's auction mechanism. - -#### Registrar Parameters - -| Name | Description | Value | -|--------------------|----------------------------------------------------------------------------------------------------|------------| -| totalAuctionLength | The full time period from start of auction to end of the reveal period. | 5 days | -| revealPeriod | The length of the time period during which bidding is no longer allowed, and bids must be revealed. | 48 hours | -| launchLength | The time period during which all names will become available for auction. | 8 weeks | -| minPrice | The minimum amount of ether which must be locked up in exchange for ownership of a name. | 0.01 ether | - -### Deeds - -The Initial Registrar contract does not hold a balance itself. All ether sent to the Registrar will be held in a separate `Deed` contracts. A deed contract is first created and funded when a sealed bid is submitted. After an auction is completed and a hash is registered, the deed for the winning bid is held in exchange for ownership of the hash. Non-winning bids are refunded. - -A deed for an owned name may be transferred to another account by its owner, thus transferring ownership and control of the name. - -After 1 year of registration, the owner of a hash may choose to relinquish ownership and have the value of the deed returned to them. - -Deeds for non-winning bids can be closed by various methods, at which time any ether held will either be returned to the bidder, burnt, or sent to someone else as a reward for actions which help the registrar. - -The following table outlines what portion of the balance held in a deed contract will be returned upon closure, and to whom. The remaining balance will be burnt. - -#### Refund schedule - -| Reason for Deed closure | Refund Recipient | Refund Percentage | -| --- | --- | --- | -| A valid non-winning bid is revealed. | Bidder | 99.5% | -| A bid submitted after the auction period is revealed. | Bidder | 99.5% | -| An otherwise valid bid is revealed on an owned name. 1 | Bidder | 0.5% | -| An expired sealed bid is cancelled. 2 | Canceler | 0.5% | -| A registered hash is reported as invalid. 3 | Reporter | 50% | -| A registered hash is reported as invalid. 3 | Owner | 50% | - -##### Notes: - -1. This incentivizes all bids to be revealed in time. If bids could be revealed late, an extortion attack on the current highest bidder could be made by threatening to reveal a new second highest bid. -2. A bid which remains sealed after more than 2 weeks and 5 days may be cancelled by anyone to collect a small reward. -2. Since names are hashed before auctioning and registration, the Initial Registrar is unable to enforce character length restrictions independently. A reward is therefore provided for reporting invalid names. - -### Deployment and Upgrade process - -The Initial Registrar requires the ENS's address as a constructor, and should be deployed after the ENS. The multisig account owning the root node in the ENS should then set the Initial Registrar's address as owner of the `eth` node. - -The Initial Registrar is expected to be replaced by a Permanent Registrar approximately 2 years after deployment. The following process should be used for the upgrade: -1. The Permanent Registrar contract will be deployed. -2. The multisig account owning the root node in the ENS will assign ownership of the `.eth` node to the Permanent Registrar. -3. Owners of hashes in the Initial Registrar will be responsible for registering their deeds to the Permanent Registrar. A couple options are considered here: - 1. Require owners to transfer their ownership prior to a cutoff date in order to maintain ownership and/or continue name resolution services. - 2. Have the Permanent Registrar query the Initial Registrar for ownership if it is lacking an entry. - -### Planned deactivation - -In order to limit dependence on the Initial Registrar, new auctions will stop after 4 years, and all ether held in deeds after 8 years will become unreachable. - -### Registrar Interface - -`function state(bytes32 _hash) constant returns (Mode)` -- Implements a state machine returning the current state of a name - -`function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint)` -- Returns the following information regarding a registered name: - * state - * deed address - * registration date - * balance of the deed - * highest value bid at auction - -`function getAllowedTime(bytes32 _hash) constant returns (uint timestamp)` -- Returns the time at which the hash will no longer be in the initial `not-yet-available` state. - -`function isAllowed(bytes32 _hash, uint _timestamp) constant returns (bool allowed)` -- Takes a hash and a time, returns true if and only if it has passed the initial `not-yet-available` state. - -`function startAuction(bytes32 _hash);` -- Moves the state of a hash from Open to Auction. Throws if state is not Open. - -`function startAuctions(bytes32[] _hashes);` -- Starts multiple auctions on an array of hashes. This enables someone to open up an auction for a number of dummy hashes when they are only really interested in bidding for one. This will increase the cost for an attacker to simply bid blindly on all new auctions. Dummy auctions that are open but not bid on are closed after a week. - -`function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid);` -- Takes the parameters of a bid, and returns the sealedBid hash value required to participate in the bidding for an auction. This obfuscates the parameters in order to mimic the mechanics of placing a bid in an envelope. - -`function newBid(bytes32 sealedBid);` -- Bids are sent by sending a message to the main contract with a sealedBid hash and an amount of ether. The hash contains information about the bid, including the bidded name hash, the bid value, and a random salt. Bids are not tied to any one auction until they are revealed. The value of the bid itself can be masqueraded by sending more than the value of your actual bid. This is followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable. Since this is an auction, it is expected that most public hashes, like known domains and common dictionary words, will have multiple bidders pushing the price up. - -`function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid)` -- A utility function allowing a call to `startAuctions` followed by `newBid` in a single transaction. - - -`function unsealBid(bytes32 _hash, address _owner, uint _value, bytes32 _salt);` -- Once the bidding period is completed, there is a reveal period during with the properties of a bid are submitted to reveal them. The registrar hashes these properties using the `shaBid()` function above to verify that they match a pre-existing sealed bid. If the unsealedBid is the new best bid, the old best bid is returned to its bidder. - -`function cancelBid(bytes32 seal);` -- Cancels an unrevealed bid according to the rules described in the notes on the refund schedule above. - -`function finalizeAuction(bytes32 _hash);` - -After the registration date has passed, this function can be called to finalize the auction, which then calls the ENS function `setSubnodeOwner()` updating the ENS record to set the winning bidder as owner of the node. - -`function transfer(bytes32 _hash, address newOwner);` -- Update the owner of the ENS node corresponding to the submitted hash to a new owner. This function must be callable only by the current owner. - -`function releaseDeed(bytes32 _hash);` -- After some time, the owner can release the property and get their ether back. - -`function invalidateName(string unhashedName);` -- Since registration is done on the hash of a name, the registrar itself cannot validate names. This function can be used to report a name which is 6 characters long or less. If it has been registered, the submitter will earn 10% of the deed value. We are purposefully handicapping the simplified registrar as a way to force it into being restructured in a few years. - -`function eraseNode(bytes32[] labels)` -- Allows anyone to delete the owner and resolver records for a subdomain of a name that is not currently owned in the registrar. For instance, to zero `foo.bar.eth` on a registrar that owns `.eth`, pass an array containing `[sha3('foo'), sha3('bar')]`. - -`function transferRegistrars(bytes32 _hash) onlyOwner(_hash);` -- Used during the upgrade process to a permanent registrar. If this registrar is no longer the owner of the its root node in the ENS, this function will transfers the deed to the current owner, which should be a new registrar. This function throws if this registrar still owns its root node. - -## Rationale - -### Starting with a temporary registrar - -Anticipating and designing for all the potential issues of name allocation names is unlikely to succeed. This approach chooses not to be concerned with getting it perfect, but allows us to observe and learn with training wheels on, and implement improvements before expanding the available namespace to shorter names or another TLD. - -### Valid names >= 7 characters - -Preserving the shortest, and often most valuable, domain names for the upgraded registrar provides the opportunity to implement processes for dispute resolution (assuming they are found to be necessary). - -### Delayed release of names - -A slower release allows for extra time to identify, and address any issues which may arise after launch. - -### Restricting TLD to `.eth` - -Choosing a single TLD helps to maximize network effects by focusing on one namespace. - -A three letter TLD is a pattern made familiar by it's common usage in internet domain names. This familiarity significantly increases the potential of the ENS to be integrated into pre-existing DNS systems, and reserved as a [special-use domain name](https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml#special-use-domain). A recent precedent for this is the [reservation of the `.onion` domain](https://tools.ietf.org/html/rfc7686). - -### Holding ether as collateral - -This approach is simpler than the familiar model of requiring owners to make recurring payments to retain ownership of a domain name. It also makes the initial registrar a revenue neutral service. - -## Prior work - -This document borrows heavily from several sources: -- [EIP-137](./eip-137.md) outlines the initial implementation of the Registry Contract (ENS.sol) and associated Resolver contracts. -- [ERC-26](https://github.com/ethereum/EIPs/issues/26) was the first ERC to propose a name service at the contract layer -- @alexvandesande's current implementation of the [HashRegistrar](https://github.com/ethereum/ens/blob/mainnet/contracts/HashRegistrarSimplified.sol) - -### Edits: -- 2016-10-26 Added link Alex's design in abstract -- 2016-11-01 change 'Planned deactivation' to h3' -- 2017-03-13 Update timelines for bidding and reveal periods - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-162.md diff --git a/EIPS/eip-1620.md b/EIPS/eip-1620.md index 694c9d6a1cabcf..0b348ff48c4163 100644 --- a/EIPS/eip-1620.md +++ b/EIPS/eip-1620.md @@ -1,296 +1,7 @@ --- eip: 1620 -title: Money Streaming -author: Paul Berg (@PaulRBerg) -discussions-to: https://github.com/ethereum/EIPs/issues/1620 -status: Stagnant -type: Standards Track category: ERC -created: 2018-11-24 +status: Moved --- -## Simple Summary -Money streaming represents the idea of continuous payments over a finite period of time. Block numbers are used as a proxy of time to continuously update balances. - -## Abstract -The following describes a standard whereby time is measured using block numbers and streams are mappings in a master contract. - -1. A provider sets up a money streaming contract. -2. A prospective payer can interact with the contract and start the stream right away by depositing the funds required for the chosen period. -3. The payee is able to withdraw money from the contract based on its ongoing solvency. That is: `payment rate * (current block height - starting block height)` -4. The stream terms (payment rate, length, metadata) can be updated at any time if both parties pledge their signatures. -5. The stream can be stopped at any point in time by any party without on-chain consensus. -6. If the stream period ended and it was not previously stopped by any party, the payee is entitled to withdraw all the deposited funds. - -## Motivation -This standardised interface aims to change the way we think about long-term financial commitments. Thanks to blockchains, payments need not be sent in chunks (e.g. monthly salaries), as there is much less overhead in paying-as-you-go. Money as a function of time would better align incentives in a host of scenarios. - -### Use Cases - -This is just a preliminary list of use cases. There are other spooky ideas interesting to explore, such as time-dependent disincetivisation, but, for brevity, we have not included them here. - -- Salaries -- Subscriptions -- Consultancies -- CDPs -- Rent -- Parking - -### Crowdsales -[RICOs](https://github.com/lukso-network/rico), or Reversible ICOs, were introduced at Devcon4 by @frozeman. The idea is to endow investors with more power and safety guarantees by allowing them to "reverse" the investment based on the evolution of the project. We previously discussed a similar concept called SICOs, or Streamable ICOs, in this research [thread](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928/14?u=paulrberg). - -Instead of investing a lump sum and giving the money away to the project developers, funds are held in a smart contract which allocates money based on the passage of time. Project developers can withdraw funds as the stream stays active, while investors have the power to get back a significant percentage of their initial commitment if the project halts. - -## Specification - -### Structs - -The structure of a `stream` should be as follows: - -- `stream` - - `sender`: the `address` of the entity funding the stream - - `recipient`: the `address` where the money is being delivered to - - `tokenAddress`: the `address` of the ERC20 token used as payment asset - - `balance`: the total funds left in the stream - - `timeframe`: as defined below - - `rate`: as defined below - -```solidity - struct Stream { - address sender; - address recipient; - address tokenAddress; - uint256 balance; - Timeframe timeframe; - Rate rate; - } -``` - -- `timeframe` - - `start`: the starting block number of the stream - - `stop`: the stopping block number of the stream - -```solidity -struct Timeframe { - uint256 start; - uint256 stop; -} -``` - -- `rate` - - `payment`: how much money moves from `sender` to `recipient` - - `interval`: how often `payment` moves from `sender` to `recipient` - -```solidity -struct Rate { - uint256 payment; - uint256 interval; -} -``` - ---- - -### Methods - -#### balanceOf - -Returns available funds for the given stream id and address. - -```solidity -function balanceOf(uint256 _streamId, address _addr) -``` - -#### getStream - -Returns the full stream data, if the id points to a valid stream. - -```solidity -function getStream(uint256 _streamId) returns (address sender, address recipient, address tokenAddress, uint256 balance, uint256 startBlock, uint256 stopBlock, uint256 payment, uint256 interval) -``` - -#### create - -Creates a new stream between `msg.sender` and `_recipient`. - -MUST allow senders to create multiple streams in parallel. SHOULD not accept Ether and only use ERC20-compatible tokens. - -**Triggers Event**: [LogCreate](#logcreate) - -```solidity -function create(address _recipient, address _tokenAddress, uint256 _startBlock, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### withdraw - -Withdraws all or a fraction of the available funds. - -MUST allow only the recipient to perform this action. - -**Triggers Event**: [LogWithdraw](#logwithdraw) - -```solidity -function withdraw(uint256 _streamId, uint256 _funds) -``` - -#### redeem - -Redeems the stream by distributing the funds to the sender and the recipient. - -SHOULD allow any party to redeem the stream. - -**Triggers Event**: [LogRedeem](#logredeem) - -```solidity -function redeem(uint256 _streamId) -``` - -#### confirmUpdate - -Signals one party's willingness to update the stream - -SHOULD allow any party to do this but MUST NOT be executed without consent from all involved parties. - -**Triggers Event**: [LogConfirmUpdate](#logconfirmupdate) - -**Triggers Event**: [LogExecuteUpdate](#logexecuteupdate) when the last involved party calls this function - -```solidity -function update(uint256 _streamId, address _tokenAddress, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### revokeUpdate - -Revokes an update proposed by one of the involved parties. - -MUST allow any party to do this. - -**Triggers Event**: [LogRevokeUpdate](#logrevokeupdate) - -```solidity -function confirmUpdate(uint256 _streamId, address _tokenAddress, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - ---- - -### Events - -#### LogCreate - -MUST be triggered when `create` is successfully called. - -```solidity -event LogCreate(uint256 indexed _streamId, address indexed _sender, address indexed _recipient, address _tokenAddress, uint256 _startBlock, uint256 _stopBlock, uint256 _payment, uint256 _interval) -``` - -#### LogWithdraw - -MUST be triggered when `withdraw` is successfully called. - -```solidity -event LogWithdraw(uint256 indexed _streamId, address indexed _recipient, uint256 _funds) -``` - -#### LogRedeem - -MUST be triggered when `redeem` is successfully called. - -```solidity -event LogRedeem(uint256 indexed _streamId, address indexed _sender, address indexed _recipient, uint256 _senderBalance, uint256 _recipientBalance) -``` - -#### LogConfirmUpdate - -MUST be triggered when `confirmUpdate` is successfully called. - -```solidity -event LogConfirmUpdate(uint256 indexed _streamId, address indexed _confirmer, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval); -``` - -#### LogRevokeUpdate - -MUST be triggered when `revokeUpdate` is successfully called. - -```solidity -event LogRevokeUpdate(uint256 indexed _streamId, address indexed revoker, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval) -``` - -#### LogExecuteUpdate - -MUST be triggered when an update is approved by all involved parties. - -```solidity -event LogExecuteUpdate(uint256 indexed _newStreamId, address indexed _sender, address indexed _recipient, address _newTokenAddress, uint256 _newStopBlock, uint256 _newPayment, uint256 _newInterval) -``` - -## Rationale - -This specification was designed to serve as an entry point to the quirky concept of money as a function of time and it is definitely not set in stone. Several other designs, including payment channels and Plasma chains were also considered, but they were eventually deemed dense in assumptions unnecessary for an initial version. - - - -Block times are a reasonable, trustless proxy for time on the blockchain. Between 2016 and 2018, the Ethereum block time average value [hovered](https://etherscan.io/chart/blocktime) around 14 seconds, excluding the last two quarters of 2017. Mathematically speaking, it would be ideal to have a standard deviation as close to 0 as possible, but that is not how things work in the real world. This has huge implications on the feasibility of this ERC which we shall investigate below. - -### GCD -When setting up a stream, a payer and a payee may want to make the total streaming duration a multiple of the "greatest common denominator" (GCD) of the chain they operate on; that is, the average block time. This is not imperative in the smart contracts per se, but there needs to be an off-chain process to map streams to real world time units in order to create a sound and fair payment mechanism. - -### Block Times -Because there is uncertainty regarding block times, streams may not be settled on the blockchain as initially planned. Let `$d` be the total streaming duration measured in seconds, `$t` the average block time before the stream started and `$t'` the actual average block time over `$d` after the stream started. We distinguish two undesirable scenarios: - -1. `$t` < `$t'`: the payee will get their funds *later* than expected - -2. `$t` > `$t'`: the payee will get their funds *sooner* than expected - -If the combined error delta is smaller than the payment rate (fifth parameter of the `create` method, measured in wei), there is no problem at all. Conversely, we stumble upon trust issues because real-world time frames do not correspond to the stream terms. For instance, if an employee is normally entitled to withdraw all the funds from the stream at the end of the month, but block times cause case 1 from above to occur, the employee is in a financial disadvantage because their continuous effort is not compensated as promised. - -Limiting the problem scope only to Ethereum, we propose two remedies: - -1. Consensus on calling the `update` function to correct the stream terms. This might sound preposterous, but in most cases the stakes are low and stream participants are involved in long-term financial commitments. There is a high disincentive to refuse to cooperate. - -2. Autonomously fix significant error deltas. In theory, we could achieve this using previous blocks' timestamps, "checkpointing" the stream once in a predefined number of blocks. This is still an area of active research because of potentially high overheads in gas costs. - -Nonetheless, it is important to note that this is still a major improvement on the traditional model where absolute trust is required. - -### Sidechains - -It could be more efficient to implement this standard on independent sidechains like [POA Network](https://poa.network) or [xDai](https://medium.com/poa-network/poa-network-partners-with-makerdao-on-xdai-chain-the-first-ever-usd-stable-blockchain-65a078c41e6a) - thanks to their rather predictable nature. Admittedly, security is traded for scalability, but proper cryptoeconomic stakes could alleviate potential problems. - -Furthermore, it is intriguing to explore the prospect of stream-specific sidechains. - -### Oracles - -The proposed specification uses block numbers to proxy time, but this need not be the only method. Albeit it would imply different trust assumptions, oracles could be used to provide a feed of timestamps. Coupled with the aforementioned idea of stream-specific sidechains, oracles could efficiently solve the problems outlined in [Block Times](#block-times). - -### Multi-Hop Streams - -Future or upgraded versions of this standard may describe "multi-hop" streams. If: - -1. There is a stream between A and B -2. There is another stream between B and C - -There could be a way to avoid running two different streams in parallel. That is, a fraction or all of the funds being streamed from A to B could be automatically wired to C. An interesting use case for this is taxes. Instead of manually moving money around, proactively calculating how much you owe and then transfer it, a stream could atomically perform those operations for you. - -## Implementation - -- [ChronosProtocol WIP implementation](https://github.com/ChronosProtocol/monorepo) - -## Additional References -- [Chronos Protocol Ethresear.ch Plasma Proposal](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928?u=paulrberg) -- [Chronos Protocol White Paper](http://chronosprotocol.org/chronos-white-paper.pdf) -- [Flipper: Streaming Salaries @ CryptoLife Hackathon](https://devpost.com/software/flipper-3gvl4b) -- [SICOs or Streamed ICOs](https://ethresear.ch/t/chronos-a-quirky-application-proposal-for-plasma/2928/14?u=paulrberg) -- [RICOs or Reversible ICOs](https://twitter.com/feindura/status/1058057076306518017) -- [Andreas Antonopoulos' Keynote on Bitcoin, Lightning and Money Streaming](https://www.youtube.com/watch?v=gF_ZQ_eijPs) - -## Final Notes - -Many thanks to @mmilton41 for countless brainstorming sessions. We have been doing research on the topic of money streaming for quite a while within the context of @ChronosProtocol. In August this year, we published the first version of our white paper describing a Plasma approach. However, in the meantime, we realised that it would be much more [fun](https://twitter.com/PaulRBerg/status/1056595919116910592) and easier to start small on Ethereum itself and sidechains like [xDai](https://blockscout.com/poa/dai). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1620.md diff --git a/EIPS/eip-1633.md b/EIPS/eip-1633.md index 17461d4dbddb55..d6d4959661f223 100644 --- a/EIPS/eip-1633.md +++ b/EIPS/eip-1633.md @@ -1,174 +1,7 @@ --- eip: 1633 -title: Re-Fungible Token Standard (RFT) -author: Billy Rennekamp (@okwme), Dan Long , Kiryl Yermakou , Nate van der Ende -discussions-to: https://github.com/ethereum/EIPs/issues/1634 -status: Stagnant -type: Standards Track category: ERC -created: 2018-11-18 -requires: 20, 165, 721 +status: Moved --- -## Simple Summary -[ERC-20](./eip-20.md) extension for proportional ownership of an [ERC-721](./eip-721.md) token. - -## Abstract -The intention of this proposal, the Re-Fungible Token Standard, is to extend the ERC-20 Token Standard and utilize ERC-165 Standard Interface Detection in order to represent the shared ownership of an ERC-721 Non-Fungible Token. The ERC-20 Token Standard was modified as little as possible in order to allow this new class of token to operate in all of the ways and locations which are familiar to assets that follow the original ERC-20 specification. While there are many possible variations of this specification that would enable many different capabilities and scenarios for shared ownership, this proposal is focused on the minimal commonalities to enable as much flexibility as possible for various further extensions. This proposal makes it possible to verify, from the contract level or from an external query, whether a fungible token represents a form of shared ownership of a non-fungible token. The inclusion of ERC-165 makes it possible to verify, from the contract level or from an external query, whether a non-fungible token is owned by ERC-20 token representing shared ownership. - -## Motivation -Shared ownership occurs across many industries and for many reasons. As more assets are registered, regulated and/or represented by the ERC-721 Non-Fungible Token Standard there will be more instances where the need for shared ownership of these assets will arise. For example, ARTBLX Inc. is working towards facilitating a protocol for collective ownership of physical, digital and conceptual artworks. The fungible tokens created from this process will have a value attached to the non-fungible tokens which they represent. This will be useful for price discovery of the underlying asset, liquidity for shared owners and as a new class of asset which can be used as collateral for loans or other financial instruments like stable coins. Providing an interface to this special class of fungible tokens is necessary to allow third parties to recognize them as a special class of fungible token and to recognize when a non-fungible token is collectively owned. This might be useful in the case of a wallet who would want to utilize the metadata of the underlying NFT to show additional info next to an RFT, or on an exchange who might want to make that sort of info similarly available, or an NFT marketplace who may want to direct customers to a relevant exchange who wish to purchase shares in a NFT which is owned by an RFT. Anywhere an ERC-20 is applicable it would be useful for a user to know whether that token represents a shared NFT, and what attributes that NFT may have. - -## Specification -At a minimum, third parties need two things: 1) to be able to distinguish re-fungible tokens from other token standards and 2) to determine when a non-fungible token is collectively owned. These two scenarios can be encountered from the perspective of initial contact with the non-fungible token or from the perspective of initial contact with the re-fungible token. - -#### Initial Contact with the Re-Fungible Token - -In order for a third party to confirm which non-fungible token is owned by the re-fungible token there needs to be a pointer from the RFT contract to the NFT contract and the relevant token id. This is possible with two public getters named `parentToken()` and `parentTokenId()`. The first getter returns a variable of type `address` and designates the contract address of the Non-Fungible Token contract. The second getter returns a variable of type `uint256` and designates the token ID of the Non-Fungible Token. With these getters, the identity of the Non-Fungible Token can be determined. Below is an example of the Re-Fungible Token Standard interface that includes these getter functions: - -```solidity -pragma solidity ^0.4.20; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT /* is ERC20, ERC165 */ { - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` - -The validity of this claim can be confirmed from another contract (on-chain) or from interacting with an RPC endpoint (off-chain). Below is an example of the on-chain scenario: - -```solidity -pragma solidity ^0.4.20; - -import './RFT.sol'; -import './ERC721.sol'; - -contract ConfirmRFT { - - function confirmRFT(address _RFT) external view returns(bool) { - address _NFT = RFT(_RFT).parentToken(); // returns address of NFT contract - uint256 _tokenId = RFT(_RFT).parentTokenId(); // returns id of ID of NFT - - return - NFT(_NFT).supportsInterface(0x80ac58cd) && // confirm it is ERC-721 - NFT(_NFT).ownerOf(_tokenId) == _RFT; // confirm the owner of the NFT is the RFT contract address - } - -} -``` - -Below is an off-chain example using an instance of web3.js in javascript: -```javascript -async function confirmRFT(web3) { - - const ERC721ABI = [...] // abi for ERC721 - const RFTABI = [...] // abi for RFT - const RFTAddress = '0x0123456789abcdef0123456789abcdef' // address for the deployed RFT - - const RFTContract = new web3.eth.Contract(RFTABI, RFTAddress) // deployed RFT contract instance - const ERC721Address = await RFTcontract.methods.parentToken().call() // returns address of NFT contract - const ERC721TokenId = await RFTcontract.methods.parentTokenId().call() // returns id of ID of NFT - - const ERC721Contract = new web3.eth.Contract(ERC721ABI, ERC721Address) // deployed ERC721 (as reported by RFT) - const isERC721 = await ERC721Contract.methods.supportsInterface('0x80ac58cd').call() // confirm it is ERC-721 - const ownerOfAddress = await ERC721Contract.methods.ownerOf(ERC721TokenId).call() // get the owner of the NFT - - return ERC721Response.toLowerCase() === RFTAddress.toLowerCase() // confirm the owner of the NFT is the RFT contract -} -``` - -#### Initial Contact with the Non-Fungible Token - -When checking the owner of a specific non-fungible token it's important to be able to determine whether owner is in fact a re-fungible token contract. This is possible by utilizing ERC-165 Standard Interface Detection. In order to comply with that standard a contract must include the following getter function which returns `true` when passed the `bytes4` parameter `0x01ffc9a7`: -``` -function supportsInterface(bytes4 interfaceID) external view returns (bool); -``` -After establishing support for this interface it becomes useful in determining whether the contract adheres to the Re-Fungible Token Standard. To do so the `supportsInterface(bytes4 interfaceID)` getter function must return `true` when passed the `bytes4` parameter `0x5755c3f2` which is the result of `bytes4(keccak256('parentToken()')) ^ bytes4(keccak256('parentTokenId()'))` or `parentToken.selector ^ parentTokenId.selector`. This could be achieved with the following code: -```solidity -pragma solidity ^0.4.20; - -import "./ERC20.sol"; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT is ERC20 /*, ERC165 */ { - - function supportsInterface(bytes4 interfaceID) external view returns(bool) { - return - interfaceID == this.supportsInterface.selector || // ERC165 - interfaceID == this.parentToken.selector || // parentToken() - interfaceID == this.parentTokenId.selector || // parentTokenId() - interfaceID == this.parentToken.selector ^ this.parentTokenId.selector; // RFT - } - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` -The flow of actually checking the status of a non-fungible token owner as a re-fungible token contract can be done from another contract (on-chain) as well as with an RPC endpoint (off-chain). Below is an example of the on-chain scenario: -```solidity -pragma solidity ^0.4.20; - -import './RFT.sol'; -import './ERC721.sol'; - -contract ConfirmRFT { - - function confirmRFT(address _NFT, uint256 _tokenId) external view returns(bool) { - address _RFT = ERC721(_NFT).ownerOf(_tokenId); // get the owner of the NFT - - return - RFT(_RFT).supportsInterface(0x01ffc9a7) && // confirm it supports ERC-165 - RFT(_RFT).supportsInterface(0x5755c3f2) // confirm it is RFT - } - -} -``` -Below is an off-chain example using web3.js in javascript: -```javascript -async function confirmRFT(web3) { - - const ERC721ABI = [...] // abi for ERC721 - const RFTABI = [...] // abi for RFT - const ERC721Address = '0x0123456789abcdef0123456789abcdef' // address for the deployed NFT - const ERC721TokenId = '7' // token Id of the NFT - - const ERC721Contract = new web3.eth.Contract(ERC721ABI, ERC721Address) // deployed ERC721 - const RFTAddress = await ERC721Contract.methods.ownerOf(ERC721TokenId).call() // owner address of the NFT - - - const RFTContract = new web3.eth.Contract(RFTABI, RFTAddress) // deployed RFT contract instance - const isERC165 = await RFTContract.methods.supportsInterface('0x01ffc9a7').call() // confirm it is ERC-165 - return isERC165 && await RFTContract.methods.supportsInterface('0x5755c3f2').call() // confirm it is RFT - -} -``` -## Rationale -Most of the decisions made around the design of this standard were done in the hopes of keeping it as flexible as possible for as many use cases as possible. This includes making the standard 100% backwards compatible with ERC-20 Token Standard and able to interact with any previously deployed or future ERC-721 non-fungible token. This allows for each project to determine their own system for minting, burning and governing their re-fungible tokens depending on their specific use case. - -## Backwards Compatibility -The Re-Fungible Token Standard is 100% backwards compatible with ERC-20 Token Standard. It is a small extension to the original specification and meant to be further extended for more specific use cases. Keeping the standard compatible with ERC-20 is important to allow for this token to benefit from the ecosystem that has grown around supporting the ubiquitous ERC-20 Token Standard. - -The Re-Fungible Token Standard is intended to interact with the ERC-721 Non-Fungible Token Standard. It is kept purposefully agnostic to extensions beyond the standard in order to allow specific projects to design their own token relationships such as governance over, rights to or permissions on each non-fungible token relative to the respective re-fungible token owners. - -## Implementation -```solidity -pragma solidity ^0.4.20; - -/// @dev Note: the ERC-165 identifier for this interface is 0x5755c3f2. -interface RFT /* is ERC20, ERC165 */ { - - function parentToken() external view returns(address _parentToken); - function parentTokenId() external view returns(uint256 _parentTokenId); - -} -``` - -## Security Considerations -TBD - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1633.md diff --git a/EIPS/eip-165.md b/EIPS/eip-165.md index 77e6cbcf3938d3..8cdfd7787845ec 100644 --- a/EIPS/eip-165.md +++ b/EIPS/eip-165.md @@ -1,235 +1,7 @@ --- eip: 165 -title: Standard Interface Detection -author: Christian Reitwießner , Nick Johnson , Fabian Vogelsteller , Jordi Baylina , Konrad Feldmeier , William Entriken -type: Standards Track category: ERC -status: Final -created: 2018-01-23 -requires: 214 +status: Moved --- -## Simple Summary - -Creates a standard method to publish and detect what interfaces a smart contract implements. - -## Abstract - -Herein, we standardize the following: - -1. How interfaces are identified -2. How a contract will publish the interfaces it implements -3. How to detect if a contract implements ERC-165 -4. How to detect if a contract implements any given interface - -## Motivation - -For some "standard interfaces" like [the ERC-20 token interface](./eip-20.md), it is sometimes useful to query whether a contract supports the interface and if yes, which version of the interface, in order to adapt the way in which the contract is to be interacted with. Specifically for ERC-20, a version identifier has already been proposed. This proposal standardizes the concept of interfaces and standardizes the identification (naming) of interfaces. - -## Specification - -### How Interfaces are Identified - -For this standard, an *interface* is a set of [function selectors as defined by the Ethereum ABI](https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector). This a subset of [Solidity's concept of interfaces](https://solidity.readthedocs.io/en/develop/abi-spec.html) and the `interface` keyword definition which also defines return types, mutability and events. - -We define the interface identifier as the XOR of all function selectors in the interface. This code example shows how to calculate an interface identifier: - -```solidity -pragma solidity ^0.4.20; - -interface Solidity101 { - function hello() external pure; - function world(int) external pure; -} - -contract Selector { - function calculateSelector() public pure returns (bytes4) { - Solidity101 i; - return i.hello.selector ^ i.world.selector; - } -} -``` - -Note: interfaces do not permit optional functions, therefore, the interface identity will not include them. - -### How a Contract will Publish the Interfaces it Implements - -A contract that is compliant with ERC-165 shall implement the following interface (referred as `ERC165.sol`): - -```solidity -pragma solidity ^0.4.20; - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The interface identifier for this interface is `0x01ffc9a7`. You can calculate this by running `bytes4(keccak256('supportsInterface(bytes4)'));` or using the `Selector` contract above. - -Therefore the implementing contract will have a `supportsInterface` function that returns: - -- `true` when `interfaceID` is `0x01ffc9a7` (EIP165 interface) -- `false` when `interfaceID` is `0xffffffff` -- `true` for any other `interfaceID` this contract implements -- `false` for any other `interfaceID` - -This function must return a bool and use at most 30,000 gas. - -Implementation note, there are several logical ways to implement this function. Please see the example implementations and the discussion on gas usage. - -### How to Detect if a Contract Implements ERC-165 - -1. The source contract makes a `STATICCALL` to the destination address with input data: `0x01ffc9a701ffc9a700000000000000000000000000000000000000000000000000000000` and gas 30,000. This corresponds to `contract.supportsInterface(0x01ffc9a7)`. -2. If the call fails or return false, the destination contract does not implement ERC-165. -3. If the call returns true, a second call is made with input data `0x01ffc9a7ffffffff00000000000000000000000000000000000000000000000000000000`. -4. If the second call fails or returns true, the destination contract does not implement ERC-165. -5. Otherwise it implements ERC-165. - -### How to Detect if a Contract Implements any Given Interface - -1. If you are not sure if the contract implements ERC-165, use the above procedure to confirm. -2. If it does not implement ERC-165, then you will have to see what methods it uses the old-fashioned way. -3. If it implements ERC-165 then just call `supportsInterface(interfaceID)` to determine if it implements an interface you can use. - -## Rationale - -We tried to keep this specification as simple as possible. This implementation is also compatible with the current Solidity version. - -## Backwards Compatibility - -The mechanism described above (with `0xffffffff`) should work with most of the contracts previous to this standard to determine that they do not implement ERC-165. - -Also [the ENS](./eip-137.md) already implements this EIP. - -## Test Cases - -Following is a contract that detects which interfaces other contracts implement. From @fulldecent and @jbaylina. - -```solidity -pragma solidity ^0.4.20; - -contract ERC165Query { - bytes4 constant InvalidID = 0xffffffff; - bytes4 constant ERC165ID = 0x01ffc9a7; - - function doesContractImplementInterface(address _contract, bytes4 _interfaceId) external view returns (bool) { - uint256 success; - uint256 result; - - (success, result) = noThrowCall(_contract, ERC165ID); - if ((success==0)||(result==0)) { - return false; - } - - (success, result) = noThrowCall(_contract, InvalidID); - if ((success==0)||(result!=0)) { - return false; - } - - (success, result) = noThrowCall(_contract, _interfaceId); - if ((success==1)&&(result==1)) { - return true; - } - return false; - } - - function noThrowCall(address _contract, bytes4 _interfaceId) constant internal returns (uint256 success, uint256 result) { - bytes4 erc165ID = ERC165ID; - - assembly { - let x := mload(0x40) // Find empty storage location using "free memory pointer" - mstore(x, erc165ID) // Place signature at beginning of empty storage - mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature - - success := staticcall( - 30000, // 30k gas - _contract, // To addr - x, // Inputs are stored at location x - 0x24, // Inputs are 36 bytes long - x, // Store output over input (saves space) - 0x20) // Outputs are 32 bytes long - - result := mload(x) // Load the result - } - } -} -``` - -## Implementation - -This approach uses a `view` function implementation of `supportsInterface`. The execution cost is 586 gas for any input. But contract initialization requires storing each interface (`SSTORE` is 20,000 gas). The `ERC165MappingImplementation` contract is generic and reusable. - -```solidity -pragma solidity ^0.4.20; - -import "./ERC165.sol"; - -contract ERC165MappingImplementation is ERC165 { - /// @dev You must not set element 0xffffffff to true - mapping(bytes4 => bool) internal supportedInterfaces; - - function ERC165MappingImplementation() internal { - supportedInterfaces[this.supportsInterface.selector] = true; - } - - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return supportedInterfaces[interfaceID]; - } -} - -interface Simpson { - function is2D() external returns (bool); - function skinColor() external returns (string); -} - -contract Lisa is ERC165MappingImplementation, Simpson { - function Lisa() public { - supportedInterfaces[this.is2D.selector ^ this.skinColor.selector] = true; - } - - function is2D() external returns (bool){} - function skinColor() external returns (string){} -} -``` - -Following is a `pure` function implementation of `supportsInterface`. The worst-case execution cost is 236 gas, but increases linearly with a higher number of supported interfaces. - -```solidity -pragma solidity ^0.4.20; - -import "./ERC165.sol"; - -interface Simpson { - function is2D() external returns (bool); - function skinColor() external returns (string); -} - -contract Homer is ERC165, Simpson { - function supportsInterface(bytes4 interfaceID) external view returns (bool) { - return - interfaceID == this.supportsInterface.selector || // ERC165 - interfaceID == this.is2D.selector - ^ this.skinColor.selector; // Simpson - } - - function is2D() external returns (bool){} - function skinColor() external returns (string){} -} -``` - -With three or more supported interfaces (including ERC165 itself as a required supported interface), the mapping approach (in every case) costs less gas than the pure approach (at worst case). - -## Version history -* PR 1640, finalized 2019-01-23 -- This corrects the noThrowCall test case to use 36 bytes rather than the previous 32 bytes. The previous code was an error that still silently worked in Solidity 0.4.x but which was broken by new behavior introduced in Solidity 0.5.0. This change was discussed at [#1640](https://github.com/ethereum/EIPs/pull/1640). - -* EIP 165, finalized 2018-04-20 -- Original published version. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-165.md diff --git a/EIPS/eip-1706.md b/EIPS/eip-1706.md index b392f65b080662..6c559b96589921 100644 --- a/EIPS/eip-1706.md +++ b/EIPS/eip-1706.md @@ -26,7 +26,7 @@ https://www.reddit.com/r/ethereum/comments/agdqsm/security_alert_ethereum_consta ## Specification -Add the following condition to to the SSTORE opcode gas cost calculation: +Add the following condition to the SSTORE opcode gas cost calculation: * If *gasleft* is less than or equal to 2300, fail the current call frame with 'out of gas' exception. diff --git a/EIPS/eip-1710.md b/EIPS/eip-1710.md index 91503f8d78d9d1..a9b72bb081ae5c 100644 --- a/EIPS/eip-1710.md +++ b/EIPS/eip-1710.md @@ -1,59 +1,7 @@ --- eip: 1710 -title: URL Format for Web3 Browsers -author: Bruno Barbieri (@brunobar79) -discussions-to: https://ethereum-magicians.org/t/standarize-url-format-for-web3-browsers/2422 -status: Stagnant -type: Standards Track category: ERC -created: 2019-01-13 -requires: 155 +status: Moved --- -## Simple Summary - -A standard way of representing web3 browser URLs for decentralized applications. - -## Abstract - -Since most normal web browsers (specifically on mobile devices) can not run decentralized applications correctly because of the lack of web3 support, it is necessary to differentiate them from normal urls, so they can be opened in web3 browsers if available. - -## Motivation - -Lots of dApps that are trying to improve their mobile experience are currently (deep)linking to specific mobile web3 browsers which are currently using their own url scheme. - -In order to make the experience more seamless, dApps should still be able to recommend a specific mobile web3 browser via [deferred deeplinking](https://en.wikipedia.org/wiki/Deferred_deep_linking) but by having a standard url format, if the user already has a web3 browser installed that implements this standard, it will be automatically linked to it. - -There is also a compatibility problem with the current `ethereum:` url scheme described in [EIP-831](./eip-831.md) where any ethereum related app (wallets, identity management, etc) already registered it and because of iOS unpredictable behavior for multiple apps handling a single url scheme, users can end up opening an `ethereum:` link in an app that doesn not include a web3 browser and will not be able to handle the deeplink correctly. - -## Specification - -### Syntax - -Web3 browser URLs contain "dapp" in their schema (protocol) part and are constructed as follows: - - request = "dapp" ":" [chain_id "@"] dapp_url - chain_id = 1*DIGIT - dapp_url = URI - -### Semantics - -`chain_id` is optional and it is a parameter for the browser to automatically select the corresponding chain ID as specified in [EIP-155](./eip-155.md) before opening the dApp. - -`dapp_url` is a valid [RFC3986](https://www.ietf.org/rfc/rfc3986.txt) URI - -This a complete example url: - -`dapp:1@peepeth.com/brunobar79?utm_source=github` - -which will open the web3 browser, select `mainnet` (chain_id = 1) and then navigate to: - -`https://peepeth.com/brunobar79?utm_source=github` - -## Rationale - -The proposed format attempts to solve the problem of vendor specific protocols for web3 browsers, avoiding conflicts with the existing 'ethereum:' URL scheme while also adding an extra feature: `chain_id` which will help dApps to be accessed with the right network preselected, optionally extracting away that complexity from end users. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1710.md diff --git a/EIPS/eip-173.md b/EIPS/eip-173.md index e79033eb5262d3..0e0fb9515c2485 100644 --- a/EIPS/eip-173.md +++ b/EIPS/eip-173.md @@ -1,97 +1,7 @@ --- eip: 173 -title: Contract Ownership Standard -description: A standard interface for ownership of contracts -author: Nick Mudge (@mudgen), Dan Finlay -discussions-to: https://github.com/ethereum/EIPs/issues/173 -type: Standards Track category: ERC -status: Final -created: 2018-06-07 +status: Moved --- -## Abstract - -This specification defines standard functions for owning or controlling a contract. - -An implementation allows reading the current owner (`owner() returns (address)`) and transferring ownership (`transferOwnership(address newOwner)`) along with a standardized event for when ownership is changed (`OwnershipTransferred(address indexed previousOwner, address indexed newOwner)`). - -## Motivation - -Many smart contracts require that they be owned or controlled in some way. For example to withdraw funds or perform administrative actions. It is so common that the contract interface used to handle contract ownership should be standardized to allow compatibility with user interfaces and contracts that manage contracts. - -Here are some examples of kinds of contracts and applications that can benefit from this standard: -1. Exchanges that buy/sell/auction ethereum contracts. This is only widely possible if there is a standard for getting the owner of a contract and transferring ownership. -2. Contract wallets that hold the ownership of contracts and that can transfer the ownership of contracts. -3. Contract registries. It makes sense for some registries to only allow the owners of contracts to add/remove their contracts. A standard must exist for these contract registries to verify that a contract is being submitted by the owner of it before accepting it. -4. User interfaces that show and transfer ownership of contracts. - -## Specification - -Every ERC-173 compliant contract must implement the `ERC173` interface. Contracts should also implement `ERC165` for the ERC-173 interface. - -```solidity - -/// @title ERC-173 Contract Ownership Standard -/// Note: the ERC-165 identifier for this interface is 0x7f5828d0 -interface ERC173 /* is ERC165 */ { - /// @dev This emits when ownership of a contract changes. - event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); - - /// @notice Get the address of the owner - /// @return The address of the owner. - function owner() view external returns(address); - - /// @notice Set the address of the new owner of the contract - /// @dev Set _newOwner to address(0) to renounce any ownership. - /// @param _newOwner The address of the new owner of the contract - function transferOwnership(address _newOwner) external; -} - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -The `owner()` function may be implemented as `pure` or `view`. - -The `transferOwnership(address _newOwner)` function may be implemented as `public` or `external`. - -To renounce any ownership of a contract set `_newOwner` to the zero address: `transferOwnership(address(0))`. If this is done then a contract is no longer owned by anybody. - -The OwnershipTransferred event should be emitted when a contract is created. - -## Rationale - -Key factors influencing the standard: -- Keeping the number of functions in the interface to a minimum to prevent contract bloat. -- Backwards compatibility with existing contracts. -- Simplicity -- Gas efficient - -Several ownership schemes were considered. The scheme chosen in this standard was chosen because of its simplicity, low gas cost and backwards compatibility with existing contracts. - -Here are other schemes that were considered: -1. **Associating an Ethereum Name Service (ENS) domain name with a contract.** A contract's `owner()` function could look up the owner address of a particular ENS name and use that as the owning address of the contract. Using this scheme a contract could be transferred by transferring the ownership of the ENS domain name to a different address. Short comings to this approach are that it is not backwards compatible with existing contracts and requires gas to make external calls to ENS related contracts to get the owner address. -2. **Associating an ERC721-based non-fungible token (NFT) with a contract.** Ownership of a contract could be tied to the ownership of an NFT. The benefit of this approach is that the existing ERC721-based infrastructure could be used to sell/buy/auction contracts. Short comings to this approach are additional complexity and infrastructure required. A contract could be associated with a particular NFT but the NFT would not track that it had ownership of a contract unless it was programmed to track contracts. In addition handling ownership of contracts this way is not backwards compatible. - -This standard does not exclude the above ownership schemes or other schemes from also being implemented in the same contract. For example a contract could implement this standard and also implement the other schemes so that ownership could be managed and transferred in multiple ways. This standard does provide a simple ownership scheme that is backwards compatible, is light-weight and simple to implement, and can be widely adopted and depended on. - -This standard can be (and has been) extended by other standards to add additional ownership functionality. - -## Security Considerations - -If the address returned by `owner()` is an externally owned account then its private key must not be lost or compromised. - -## Backwards Compatibility - -Many existing contracts already implement this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-173.md diff --git a/EIPS/eip-1753.md b/EIPS/eip-1753.md index 09cb027eebd047..f68dacb368cde3 100644 --- a/EIPS/eip-1753.md +++ b/EIPS/eip-1753.md @@ -1,246 +1,7 @@ --- eip: 1753 -title: Smart Contract Interface for Licences -author: Lucas Cullen (@BitcoinBrisbane), Kai Yeung (@CivicKai), Anna Crowley , Caroline Marshall , Katrina Donaghy -status: Stagnant -type: Standards Track category: ERC -created: 2019-02-06 +status: Moved --- -## Abstract - -This Ethereum Improvement Proposal (EIP) proposes an Ethereum standard for the issuance of licences, permits and grants (Licences). - -A Licence is a limited and temporary authority, granted to a natural (e.g. you) or legal person (e.g. a corporation), to do something that would otherwise be unlawful pursuant to a legal framework. A public Licence is granted by the government, directly (e.g. by the New South Wales Department of Primary Industries, Australia) or indirectly (e.g. by an agent operating under the government’s authority), and derives its authority from legislation, though this is often practically achieved via delegated legislation such as regulations. This can be contrasted to a private licence – for example, the licence you grant to a visitor who comes onto your property. - -A Licence has the following properties: - -* granted personally to the licencee (Licencee), though it may be transferrable to another person or company; -* conferring a temporary right to the Licencee to own, use or do something that would otherwise be prohibited, without conferring any property interest in the underlying thing. For example, you may be granted a licence to visit a national park without acquiring any ownership in or over the park itself; -* allowing the government authority responsible for the Licence to amend, revoke, renew, suspend or deny the issuance of the Licence, or to impose conditions or penalties for non-compliance; and -* usually issued only after the payment of a fee or the meeting of some criteria. - -Additionally, a Licence may be granted in respect of certain information. For example, a Licence may be issued in respect of a vehicle registration number and attaching to that specific registered vehicle. - -## Motivation - -Governments are responsible for the issuance and management of Licences. However, maintaining and sharing this data can be complicated and inefficient. The granting of Licences usually requires the filing of paper-based application forms, manual oversight of applicable legislation and data entry into registries, as well as the issuance of paper based Licences. If individuals wish to sight information on Licence registries, they often need to be present at the government office and complete further paper-based enquiry forms in order to access that data (if available publicly). - -This EIP seeks to define a standard that will allow for the granting and/or management of Licences via Ethereum smart contracts. The motivation is, in essence, to address the inefficiencies inherent in current licencing systems. - -## Specification - -### Methods - -**NOTES**: - - The following specifications use syntax from Solidity `0.4.17` (or above) - - Callers MUST handle `false` from `returns (bool success)`. Callers MUST NOT assume that `false` is never returned! - - -#### name - -Returns the name of the permit - e.g. `"MyPermit"`. - -``` js -function name() public view returns (string); -``` - -#### totalSupply - -Returns the total permit supply. - -``` js -function totalSupply() public view returns (uint256); -``` - -#### grantAuthority - -Adds an ethereum address to a white list of addresses that have authority to modify a permit. - -``` js -function grantAuthority(address who) public; -``` - -#### revokeAuthority - -Removes an ethereum address from a white list of addresses that have authority to modify a permit. - -``` js -function revokeAuthority(address who) public; -``` - -#### hasAuthority - -Checks to see if the address has authority to grant or revoke permits. - -``` js -function hasAuthority(address who) public view; -``` - -#### issue - -Issues an ethereum address a permit between the specified date range. - -``` js -function issue(address who, uint256 validFrom, uint256 validTo) public; -``` - -#### revoke - -Revokes a permit from an ethereum address. - -``` js -function revoke(address who) public; -``` - -#### hasValid - -Checks to see if an ethereum address has a valid permit. - -``` js -function hasValid(address who) external view returns (bool); -``` - -#### purchase - -Allows a user to self procure a licence. - -``` js -function purchase(uint256 validFrom, uint256 validTo) external payable; -``` - -## Rationale - -The use of smart contracts to apply for, renew, suspend and revoke Licences will free up much needed government resources and allow for the more efficient management of Licences. The EIP also seeks to improve the end user experience of the Licence system. In an era of open government, there is also an increased expectation that individuals will be able to easily access Licence registries, and that the process will be transparent and fair. - -By creating an EIP, we hope to increase the use of Ethereum based and issued Licences, which will address these issues. - -The Ethereum blockchain is adaptable to various Licences and government authorities. It will also be easily translatable into other languages and can be used by other governmental authorities across the world. Moreover, a blockchain will more effectively protect the privacy of Licence-holders’ data, particularly at a time of an ever-increasing volume of government data breaches. - -The EIP has been developed following the review of a number of licensing regulations at the national and state level in Australia. The review allowed the identification of the common licence requirements and criteria for incorporation into the EIP. We have included these in the proposed standard but seek feedback on whether these criteria are sufficient and universal. - -## Test Cases - -A real world example of a Licence is a permit required to camp in a national park in Australia (e.g. Kakadu national park in the Northern Territory of Australia) under the Environment Protection and Biodiversity Conservation Regulations 2000 (Cth) (EPBC Act) and the Environment Protection and Biodiversity Conservation Regulations 2000 (the Regulations). Pursuant to the EPBC Act and the Regulations, the Director of National Parks oversees a camping permit system, which is intended to help regulate certain activities in National Parks. Permits allowing access to National Parks can be issued to legal or natural persons if the applicant has met certain conditions. - -The current digital portal and application form to camp at Kakadu National Park (the Application) can be accessed at: https://www.environment.gov.au/system/files/resources/b3481ed3-164b-4e72-a9f8-91fc987d90e7/files/kakadu-camping-permit-form-19jan2015-pdf.pdf - -The user must provide the following details when making an Application: - -* The full name and contact details of each person to whom the permit is to be issued; - -* If the applicant is a company or other incorporated body: - -o the name, business address and postal address of the company or incorporated body; - -o if the applicant is a company— - -* the full name of each of the directors of the company; - -* the full name and contact details of the person completing the application form; - -* the ACN or ABN of the company or other incorporated body (if applicable); - -* Details of the proposed camping purpose (e.g. private camping, school group, etc.); - -* A start date and duration for the camping (up to the maximum duration allowed by law); - -* Number of campers (up to the maximum allowed by law); - -* All other required information not essential to the issuance of the Licence (e.g. any particular medical needs of the campers); and - -* Fees payable depending on the site, duration and number of campers. - -The Regulations also set out a number of conditions that must be met by licensees when the permit has been issued. The Regulations allow the Director of National Parks to cancel, renew or transfer the licence. The above workflow could be better performed by way of a smart contract. - -The key criteria required as part of this process form part of the proposed Ethereum standard. We have checked this approach by also considering the issuance of a Commercial Fishing Licence under Part 8 “Licensing and other commercial fisheries management” of the Fisheries Management (General) Regulation 2010 (NSW) (Fisheries Regulations) made pursuant to the Fisheries Management Act 1994 (NSW) (Fisheries Act). - -## Implementation - -The issuance and ownership of a Licence can be digitally represented on the Ethereum blockchain. - -Smart contracts can be used to embed regulatory requirements with respect to the relevant Licence in the blockchain. The Licence would be available electronically in the form of a token. This might be practically represented by a QR code, for example, displaying the current Licence information. The digital representation of the Licence would be stored in a digital wallet, typically an application on a smartphone or tablet computer. The proposed standard allows issuing authorities or regulators to amend, revoke or deny Licences from time to time, with the result of their determinations reflected in the Licence token in near real-time. Licence holders will therefore be notified almost instantly of any amendments, revocations or issues involving their Licence. - -## Interface - -### Solidity Example -```solidity -interface EIP1753 { - - function grantAuthority(address who) external; - function revokeAuthority(address who) external; - function hasAuthority(address who) external view returns (bool); - - function issue(address who, uint256 from, uint256 to) external; - function revoke(address who) external; - - function hasValid(address who) external view returns (bool); - function purchase(uint256 validFrom, uint256 validTo) external payable; -} - -pragma solidity ^0.5.3; - -contract EIP is EIP1753 { - - string public name = "Kakadu National Park Camping Permit"; - uint256 public totalSupply; - - address private _owner; - mapping(address => bool) private _authorities; - mapping(address => Permit) private _holders; - - struct Permit { - address issuer; - uint256 validFrom; - uint256 validTo; - } - - constructor() public { - _owner = msg.sender; - } - - function grantAuthority(address who) public onlyOwner() { - _authorities[who] = true; - } - - function revokeAuthority(address who) public onlyOwner() { - delete _authorities[who]; - } - - function hasAuthority(address who) public view returns (bool) { - return _authorities[who] == true; - } - - function issue(address who, uint256 start, uint256 end) public onlyAuthority() { - _holders[who] = Permit(_owner, start, end); - totalSupply += 1; - } - - function revoke(address who) public onlyAuthority() { - delete _holders[who]; - } - - function hasValid(address who) external view returns (bool) { - return _holders[who].validFrom > now && _holders[who].validTo < now; - } - - function purchase(uint256 validFrom, uint256 validTo) external payable { - require(msg.value == 1 ether, "Incorrect fee"); - issue(msg.sender, validFrom, validTo); - } - - modifier onlyOwner() { - require(msg.sender == _owner, "Only owner can perform this function"); - _; - } - - modifier onlyAuthority() { - require(hasAuthority(msg.sender), "Only an authority can perform this function"); - _; - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1753.md diff --git a/EIPS/eip-1761.md b/EIPS/eip-1761.md index 141836829d66a0..8715be483c4f7f 100644 --- a/EIPS/eip-1761.md +++ b/EIPS/eip-1761.md @@ -1,175 +1,7 @@ --- eip: 1761 -title: Scoped Approval Interface -author: Witek Radomski , Andrew Cooke , James Therien , Eric Binet -type: Standards Track category: ERC -status: Stagnant -created: 2019-02-18 -discussions-to: https://github.com/ethereum/EIPs/issues/1761 -requires: 165 +status: Moved --- -## Simple Summary - -A standard interface to permit restricted approval in token contracts by defining "scopes" of one or more Token IDs. - -## Abstract - -This interface is designed for use with token contracts that have an "ID" domain, such as ERC-1155 or ERC-721. This enables restricted approval of one or more Token IDs to a specific "scope". When considering a smart contract managing tokens from multiple different domains, it makes sense to limit approvals to those domains. Scoped approval is a generalization of this idea. Implementors can define scopes as needed. - -Sample use cases for scopes: - -* A company may represent its fleet of vehicles on the blockchain and it could create a scope for each regional office. -* Game developers could share an [ERC-1155](./eip-1155.md) contract where each developer manages tokens under a specified scope. -* Tokens of different value could be split into separate scopes. High-value tokens could be kept in smaller separate scopes while low-value tokens might be kept in a shared scope. Users would approve the entire low-value token scope to a third-party smart contract, exchange, or other application without concern about losing their high-value tokens in the event of a problem. - -## Motivation - -It may be desired to restrict approval in some applications. Restricted approval can prevent losses in cases where users do not audit the contracts they're approving. No standard API is supplied to manage scopes as this is implementation specific. Some implementations may opt to offer a fixed number of scopes, or assign a specific set of scopes to certain types. Other implementations may open up scope configuration to its users and offer methods to create scopes and assign IDs to them. - -# Specification - -```solidity -pragma solidity ^0.5.2; - -/** - Note: The ERC-165 identifier for this interface is 0x30168307. -*/ -interface ScopedApproval { - /** - @dev MUST emit when approval changes for scope. - */ - event ApprovalForScope(address indexed _owner, address indexed _operator, bytes32 indexed _scope, bool _approved); - - /** - @dev MUST emit when the token IDs are added to the scope. - By default, IDs are in no scope. - The range is inclusive: _idStart, _idEnd, and all IDs in between have been added to the scope. - _idStart must be lower than or equal to _idEnd. - */ - event IdsAddedToScope(uint256 indexed _idStart, uint256 indexed _idEnd, bytes32 indexed _scope); - - /** - @dev MUST emit when the token IDs are removed from the scope. - The range is inclusive: _idStart, _idEnd, and all IDs in between have been removed from the scope. - _idStart must be lower than or equal to _idEnd. - */ - event IdsRemovedFromScope(uint256 indexed _idStart, uint256 indexed _idEnd, bytes32 indexed _scope); - - /** @dev MUST emit when a scope URI is set or changes. - URIs are defined in RFC 3986. - The URI MUST point a JSON file that conforms to the "Scope Metadata JSON Schema". - */ - event ScopeURI(string _value, bytes32 indexed _scope); - - /** - @notice Returns the number of scopes that contain _id. - @param _id The token ID - @return The number of scopes containing the ID - */ - function scopeCountForId(uint256 _id) public view returns (uint32); - - /** - @notice Returns a scope that contains _id. - @param _id The token ID - @param _scopeIndex The scope index to query (valid values are 0 to scopeCountForId(_id)-1) - @return The Nth scope containing the ID - */ - function scopeForId(uint256 _id, uint32 _scopeIndex) public view returns (bytes32); - - /** - @notice Returns a URI that can be queried to get scope metadata. This URI should return a JSON document containing, at least the scope name and description. Although supplying a URI for every scope is recommended, returning an empty string "" is accepted for scopes without a URI. - @param _scope The queried scope - @return The URI describing this scope. - */ - function scopeUri(bytes32 _scope) public view returns (string memory); - - /** - @notice Enable or disable approval for a third party ("operator") to manage the caller's tokens in the specified scope. - @dev MUST emit the ApprovalForScope event on success. - @param _operator Address to add to the set of authorized operators - @param _scope Approval scope (can be identified by calling scopeForId) - @param _approved True if the operator is approved, false to revoke approval - */ - function setApprovalForScope(address _operator, bytes32 _scope, bool _approved) external; - - /** - @notice Queries the approval status of an operator for a given owner, within the specified scope. - @param _owner The owner of the Tokens - @param _operator Address of authorized operator - @param _scope Scope to test for approval (can be identified by calling scopeForId) - @return True if the operator is approved, false otherwise - */ - function isApprovedForScope(address _owner, address _operator, bytes32 _scope) public view returns (bool); -} -``` - -## Scope Metadata JSON Schema - -This schema allows for localization. `{id}` and `{locale}` should be replaced with the appropriate values by clients. - -```json -{ - "title": "Scope Metadata", - "type": "object", - "required": ["name"], - "properties": { - "name": { - "type": "string", - "description": "Identifies the scope in a human-readable way.", - }, - "description": { - "type": "string", - "description": "Describes the scope to allow users to make informed approval decisions.", - }, - "localization": { - "type": "object", - "required": ["uri", "default", "locales"], - "properties": { - "uri": { - "type": "string", - "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request." - }, - "default": { - "type": "string", - "description": "The locale of the default data within the base JSON" - }, - "locales": { - "type": "array", - "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)." - } - } - } - } -} -``` - -### Localization - -Metadata localization should be standardized to increase presentation uniformity across all languages. As such, a simple overlay method is proposed to enable localization. If the metadata JSON file contains a `localization` attribute, its content may be used to provide localized values for fields that need it. The `localization` attribute should be a sub-object with three attributes: `uri`, `default` and `locales`. If the string `{locale}` exists in any URI, it MUST be replaced with the chosen locale by all client software. - -## Rationale - -The initial design was proposed as an extension to ERC-1155: [Discussion Thread - Comment 1](https://github.com/ethereum/EIPs/issues/1155#issuecomment-459505728). After some discussion: [Comment 2](https://github.com/ethereum/EIPs/issues/1155#issuecomment-460603439) and suggestions by the community to implement this approval mechanism in an external contract [Comment 3](https://github.com/ethereum/EIPs/issues/1155#issuecomment-461758755), it was decided that as an interface standard, this design would allow many different token standards such as ERC-721 and ERC-1155 to implement scoped approvals without forcing the system into all implementations of the tokens. - -### Metadata JSON - -The Scope Metadata JSON Schema was added in order to support human-readable scope names and descriptions in more than one language. - -## References - -**Standards** -- [ERC-1155 Multi Token Standard](./eip-1155.md) -- [ERC-165 Standard Interface Detection](./eip-165.md) -- [JSON Schema](https://json-schema.org/) - -**Implementations** -- [Enjin Coin](https://enjincoin.io) ([github](https://github.com/enjin)) - -**Articles & Discussions** -- [GitHub - Original Discussion Thread](https://github.com/ethereum/EIPs/issues/1761) -- [GitHub - ERC-1155 Discussion Thread](https://github.com/ethereum/EIPs/issues/1155) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1761.md diff --git a/EIPS/eip-1775.md b/EIPS/eip-1775.md index 3ee41df430a617..efc42dbbf536aa 100644 --- a/EIPS/eip-1775.md +++ b/EIPS/eip-1775.md @@ -1,196 +1,7 @@ --- eip: 1775 -title: App Keys, application specific wallet accounts -author: Vincent Eli (@Bunjin), Dan Finlay (@DanFinlay) -discussions-to: https://ethereum-magicians.org/t/eip-erc-app-keys-application-specific-wallet-accounts/2742 -status: Stagnant -type: Standards Track category: ERC -created: 2019-02-20 +status: Moved --- -## Simple Summary - -Among others cryptographic applications, scalability and privacy solutions for ethereum blockchain require that an user performs a significant amount of signing operations. It may also require her to watch some state and be ready to sign data automatically (e.g. sign a state or contest a withdraw). The way wallets currently implement accounts poses several obstacles to the development of a complete web3.0 experience both in terms of UX, security and privacy. - -This proposal describes a standard and api for a new type of wallet accounts that are derived specifically for a each given application. We propose to call them `app keys`. They allow to isolate the accounts used for each application, thus potentially increasing privacy. They also allow to give more control to the applications developers over account management and signing delegation. For these app keys, wallets can have a more permissive level of security (e.g. not requesting user's confirmation) while keeping main accounts secure. Finally wallets can also implement a different behavior such as allowing to sign transactions without broadcasting them. - -This new accounts type can allow to significantly improve UX and permit new designs for applications of the crypto permissionned web. - -## Abstract -In a wallet, an user often holds most of her funds in her main accounts. These accounts require a significant level of security and should not be delegated in any way, this significantly impacts the design of cryptographic applications if a user has to manually confirm every action. Also often an user uses the same accounts across apps, which is a privacy and potentially also a security issue. - -We introduce here a new account type, app keys, which permits signing delegation and accounts isolation across applications for privacy and security. - -In this EIP, we provide a proposal on how to uniquely identify and authenticate each application, how to derive a master account (or app key) unique for the domain from an user private key (her root private key or any other private key of an account derived or not from her root one). This EIP aims at becoming a standard on how to derive keys specific to each application that can be regenerated from scratch without further input from the user if she restores her wallet and uses again the application for which this key was derived. -These app keys can then be endowed a different set of permissions (through the requestPermission model introduced in [EIP-2255](./eip-2255.md)). This will potentially allow an user to partly trust some apps to perform some crypto operations on their behalf without compromising any security with respect to her main accounts. - -## Motivation -Wallets developers have agreed on an HD derivation path for ethereum accounts using BIP32, BIP44, SLIP44, [(see the discussion here)](https://github.com/ethereum/EIPs/issues/84). Web3 wallets have implemented in a roughly similar way the rpc eth api. [EIP-1102](./eip-1102.md) introduced privacy through non automatic opt-in of a wallet account into an app increasing privacy. - -However several limitations remain in order to allow for proper design and UX for crypto permissioned apps. - -Most of GUI based current wallets don't allow to: -* being able to automatically and effortlessly use different keys / accounts for each apps, -* being able to sign some app's action without prompting the user with the same level of security as sending funds from their main accounts, -* being able to use throwable keys to improve anonymity, -* effortlessly signing transactions for an app without broadcasting these while still being able to perform other transaction signing as usual from their main accounts, -* All this while being fully restorable using the user's mnemonic or hardware wallet and the HD Path determined uniquely by the app's ens name. - -We try to overcome these limitations by introducing a new account's type, app keys, made to be used along side the existing main accounts. - -These new app keys can permit to give more power and flexibility to the crypto apps developers. This can allow to improve a lot the UX of crypto dapps and to create new designs that were not possible before leveraging the ability to create and handle many accounts, to presign messages and broadcast them later. These features were not compatible with the level of security we were requesting for main accounts that hold most of an user's funds. - - -## Specification - -### Applications - -An app is a website (or other) that would like to request from a wallet to access a cryptographic key specifically derived for this usage. It can be any form of cryptography/identity relying application, Ethereum based but not only. - -Once connected to a wallet, an application can request to access an account derived exclusively for that application using the following algorithm. - -### Private App Key generation algorithm - -We now propose an algorithm to generate application keys that: -- are uniquely defined, with respect to the account that the user selected to generate these keys, -- and thus can be isolated when changing the user account, allowing persona management (see next section), -- are specific to each application, -- can be fully restored from the user master seed mnemonic and the applications' names. - -#### Using different accounts as personas - -We allow the user to span a different set of application keys by changing the account selected to generate each key. Thus from the same master seed mnemonic, an user can use each of her account index to generate an alternative set of application keys. One can describe this as using different personas. -This would allow potentially an user to fully isolate her interaction with a given app across personas. One can use this for instance to create a personal and business profile for a given's domain both backup up from the same mnemonic, using 2 different accounts to generate these. The app or domain, will not be aware that it is the same person and mnemonic behind both. -If an application interacts with several main accounts of an user, one of these accounts, a master account can be used as persona and the others as auxiliary accounts. - -This EIP is agnostic about the way one generates the private keys used to span different app keys spaces. However for compatibility purposes and for clean disambiguation between personas and cryptocurrency accounts, a new EIP, distinct from this one but to be used alongside, will be proposed soon introducing clean persona generation and management. - -#### Applications' Unique Identifiers - -Each application is uniquely defined and authenticated by its origin, a domain string. It can be a Domain Name Service (DNS) name or, in the future, an Ethereum Name Service (ENS) name or IPFS hash. - -For Ipfs or swam origins, but we could probably use the ipfs or swarm addresses as origin or we could require those to be pointed at through an ENS entry and use the ENS address as origin, although this would mean that the content it refers to could change. It would thus allow for different security and updatibility models. - -We will probably require for protocol prefixes when using an ENS domain to point to an IPFS address: -`ens://ipfs.snap.eth` - - -#### Private App Key generation algorithm - -Using the domain name of an application, we generate a private key for each application (and per main account) : - -`const appKeyPrivKey = keccak256(privKey + originString)` - -where `+` is concatenation, `privKey` is the private key of the user's account selected to span the application key and `originString` represents the origin url from which the permission call to access the application key is originated from. - -This is exposed as an RPC method to allow any domain to request its own app key associated with the current requested account (if available): - -``` -const appKey = await provider.send({ - method: 'wallet_getAppKeyForAccount', - params: [address1] -}); -``` - -See here for an implementation: -https://github.com/MetaMask/eth-simple-keyring/blob/master/index.js#L169 - -#### App keys and Hierarchical Deterministic keys - -The app keys generated using the algorithm described in the previous section will not be BIP32 compliant. Therefore apps will not be able to create several app keys or use non-hardening and extended public keys techniques directly. They get a single private key (per origin, per persona). -Yet they can use this as initial entropy to span a new HD tree and generate addresses that can be either hardened or not. Thus we should not be losing use cases. - -## Rationale - -### Sharing application keys across domains: -While this does not explicit cover cases of sharing these app keys between pages on its own, this need can be met by composition: - -Since a domain would get a unique key per persona, and because domains can intercommunicate, one domain (app) could request another domain (signer) to perform its cryptographic operation on some data, with its appKey as a seed, potentially allowing new signing strategies to be added as easily as new websites. - -This could also pass it to domains that are loading specific signing strategies. This may sound dangerous at first, but if a domain represents a static hash of a trusted cryptographic function implementation, it could be as safe as calling any audited internal dependency. - -### Privacy and the funding trail - -If all an application needs to do with its keys is to sign messages and it does not require funding, then this EIP allows for privacy through the use of distinct keys for each application with a simple deterministic standard compatible across wallets. - -However if these application keys require funding, there can be trail and the use of app keys would not fully solve the privacy problem there. - -Mixers or anonymous ways of funding an ethereum address (ring signatures) along with this proposal would guarantee privacy. - -Even if privacy is not solved fully without this anonymous funding method, we still need a way to easily create and restore different accounts/addresses for each application - -## Backwards Compatibility -From a wallet point of view, there does not seem to be compatibility issues since these are separate accounts from those that were used previously by wallets and they are supposed to be used along-side in synergy. - -However, for applications that associated in some way their users to their main accounts may want to reflect on if and how they would like to leverage the power offered by `app keys` to migrate to them and leverage on the new app designs they permit. - -## Implementation - -Here is an early implementation of app keys for standard (non HW) MetaMask accounts. -https://github.com/MetaMask/eth-simple-keyring/blob/6d12bd9d73adcccbe0b0c7e32a99d279085e2934/index.js#L139-L152 - -See here for a fork of MetaMask that implements app keys along side plugins: -https://github.com/MetaMask/metamask-snaps-beta -https://github.com/MetaMask/metamask-snaps-beta/wiki/Plugin-API - -## Example use cases - -* signing transactions without broadcasting them -https://github.com/MetaMask/metamask-extension/issues/3475 - -* token contract -https://github.com/ethereum/EIPs/issues/85 - -* default account for dapps -https://ethereum-magicians.org/t/default-accounts-for-dapps/904 - -* non wallet/crypto accounts -[EIP1581: Non-wallet usage of keys derived from BIP32 trees](./eip-1581.md) - -* state channel application - -* privacy solution - -* non custodian cross cryptocurrency exchange... - -## Acknowledgements -MetaMask team, Christian Lundkvist, Counterfactual team, Liam Horne, Erik Bryn, Richard Moore, Jeff Coleman. - - -## References - -### HD and mnemonics -#### BIPs -* [BIP32: Hierarchical Deterministic Wallets:](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) - -* [BIP39: Mnemonic code for generating deterministic keys:](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) - -* [SLIP44: Registered coin types for BIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) - - -#### Derivation path for eth -* [Issue 84](https://github.com/ethereum/EIPs/issues/84) - -* [Issue 85](https://github.com/ethereum/EIPs/issues/85) - -* [EIP600 Ethereum purpose allocation for Deterministic Wallets](./eip-600.md) - - -* [EIP601 Ethereum hierarchy for deterministic wallets](./eip-601.md) - - -### Previous proposals and discussions related to app keys -* [Meta: we should value privacy more](https://ethereum-magicians.org/t/meta-we-should-value-privacy-more/2475) - -* [EIP1102: Opt-in account exposure](./eip-1102.md) - -* [EIP1581: Non-wallet usage of keys derived from BIP-32 trees](./eip-1581.md) - -* [EIP1581: discussion](https://ethereum-magicians.org/t/non-wallet-usage-of-keys-derived-from-bip-32-trees/1817/4) - -* [SLIP13: Authentication using deterministic hierarchy](https://github.com/satoshilabs/slips/blob/master/slip-0013.md) - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1775.md diff --git a/EIPS/eip-181.md b/EIPS/eip-181.md index 3c7a2311de824c..5d88a64419342c 100644 --- a/EIPS/eip-181.md +++ b/EIPS/eip-181.md @@ -1,209 +1,7 @@ --- eip: 181 -title: ENS support for reverse resolution of Ethereum addresses -author: Nick Johnson -status: Final -type: Standards Track category: ERC -created: 2016-12-01 +status: Moved --- -# Abstract -This EIP specifies a TLD, registrar, and resolver interface for reverse resolution of Ethereum addresses using ENS. This permits associating a human-readable name with any Ethereum blockchain address. Resolvers can be certain that the reverse record was published by the owner of the Ethereum address in question. - -# Motivation -While name services are mostly used for forward resolution - going from human-readable identifiers to machine-readable ones - there are many use-cases in which reverse resolution is useful as well: - - - Applications that allow users to monitor accounts benefit from showing the name of an account instead of its address, even if it was originally added by address. - - Attaching metadata such as descriptive information to an address allows retrieving this information regardless of how the address was originally discovered. - - Anyone can configure a name to resolve to an address, regardless of ownership of that address. Reverse records allow the owner of an address to claim a name as authoritative for that address. - -# Specification -Reverse ENS records are stored in the ENS hierarchy in the same fashion as regular records, under a reserved domain, `addr.reverse`. To generate the ENS name for a given account's reverse records, convert the account to hexadecimal representation in lower-case, and append `addr.reverse`. For instance, the ENS registry's address at `0x112234455c3a32fd11230c42e7bccd4a84e02010` has any reverse records stored at `112234455c3a32fd11230c42e7bccd4a84e02010.addr.reverse`. - -Note that this means that contracts wanting to do dynamic reverse resolution of addresses will need to perform hex encoding in the contract. - -## Registrar -The owner of the `addr.reverse` domain will be a registrar that permits the caller to take ownership of -the reverse record for their own address. It provides the following methods: - -### function claim(address owner) returns (bytes32 node) - -When called by account `x`, instructs the ENS registry to transfer ownership of the name `hex(x) + '.addr.reverse'` to the provided address, and return the namehash of the ENS record thus transferred. - -Allowing the caller to specify an owner other than themselves for the relevant node facilitates contracts that need accurate reverse ENS entries delegating this to their creators with a minimum of code inside their constructor: - - reverseRegistrar.claim(msg.sender) - -### function claimWithResolver(address owner, address resolver) returns (bytes32 node) - -When called by account `x`, instructs the ENS registry to set the resolver of the name `hex(x) + '.addr.reverse'` to the specified resolver, then transfer ownership of the name to the provided address, and return the namehash of the ENS record thus transferred. This method facilitates setting up a custom resolver and owner in fewer transactions than would be required if calling `claim`. - -### function setName(string name) returns (bytes32 node) - -When called by account `x`, sets the resolver for the name `hex(x) + '.addr.reverse'` to a default resolver, and sets the name record on that name to the specified name. This method facilitates setting up simple reverse records for users in a single transaction. - -## Resolver interface -A new resolver interface is defined, consisting of the following method: - - function name(bytes32 node) constant returns (string); - -Resolvers that implement this interface must return a valid ENS name for the requested node, or the empty string if no name is defined for the requested node. - -The interface ID of this interface is 0x691f3431. - -Future EIPs may specify more record types appropriate to reverse ENS records. - -# Appendix 1: Registrar implementation - -This registrar, written in Solidity, implements the specifications outlined above. - - pragma solidity ^0.4.10; - - import "./AbstractENS.sol"; - - contract Resolver { - function setName(bytes32 node, string name) public; - } - - /** - * @dev Provides a default implementation of a resolver for reverse records, - * which permits only the owner to update it. - */ - contract DefaultReverseResolver is Resolver { - AbstractENS public ens; - mapping(bytes32=>string) public name; - - /** - * @dev Constructor - * @param ensAddr The address of the ENS registry. - */ - function DefaultReverseResolver(AbstractENS ensAddr) { - ens = ensAddr; - } - - /** - * @dev Only permits calls by the reverse registrar. - * @param node The node permission is required for. - */ - modifier owner_only(bytes32 node) { - require(msg.sender == ens.owner(node)); - _; - } - - /** - * @dev Sets the name for a node. - * @param node The node to update. - * @param _name The name to set. - */ - function setName(bytes32 node, string _name) public owner_only(node) { - name[node] = _name; - } - } - - contract ReverseRegistrar { - // namehash('addr.reverse') - bytes32 constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; - - AbstractENS public ens; - Resolver public defaultResolver; - - /** - * @dev Constructor - * @param ensAddr The address of the ENS registry. - * @param resolverAddr The address of the default reverse resolver. - */ - function ReverseRegistrar(AbstractENS ensAddr, Resolver resolverAddr) { - ens = ensAddr; - defaultResolver = resolverAddr; - } - - /** - * @dev Transfers ownership of the reverse ENS record associated with the - * calling account. - * @param owner The address to set as the owner of the reverse record in ENS. - * @return The ENS node hash of the reverse record. - */ - function claim(address owner) returns (bytes32 node) { - return claimWithResolver(owner, 0); - } - - /** - * @dev Transfers ownership of the reverse ENS record associated with the - * calling account. - * @param owner The address to set as the owner of the reverse record in ENS. - * @param resolver The address of the resolver to set; 0 to leave unchanged. - * @return The ENS node hash of the reverse record. - */ - function claimWithResolver(address owner, address resolver) returns (bytes32 node) { - var label = sha3HexAddress(msg.sender); - node = sha3(ADDR_REVERSE_NODE, label); - var currentOwner = ens.owner(node); - - // Update the resolver if required - if(resolver != 0 && resolver != ens.resolver(node)) { - // Transfer the name to us first if it's not already - if(currentOwner != address(this)) { - ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, this); - currentOwner = address(this); - } - ens.setResolver(node, resolver); - } - - // Update the owner if required - if(currentOwner != owner) { - ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner); - } - - return node; - } - - /** - * @dev Sets the `name()` record for the reverse ENS record associated with - * the calling account. First updates the resolver to the default reverse - * resolver if necessary. - * @param name The name to set for this address. - * @return The ENS node hash of the reverse record. - */ - function setName(string name) returns (bytes32 node) { - node = claimWithResolver(this, defaultResolver); - defaultResolver.setName(node, name); - return node; - } - - /** - * @dev Returns the node hash for a given account's reverse records. - * @param addr The address to hash - * @return The ENS node hash. - */ - function node(address addr) constant returns (bytes32 ret) { - return sha3(ADDR_REVERSE_NODE, sha3HexAddress(addr)); - } - - /** - * @dev An optimised function to compute the sha3 of the lower-case - * hexadecimal representation of an Ethereum address. - * @param addr The address to hash - * @return The SHA3 hash of the lower-case hexadecimal encoding of the - * input address. - */ - function sha3HexAddress(address addr) private returns (bytes32 ret) { - addr; ret; // Stop warning us about unused variables - assembly { - let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000 - let i := 40 - loop: - i := sub(i, 1) - mstore8(i, byte(and(addr, 0xf), lookup)) - addr := div(addr, 0x10) - i := sub(i, 1) - mstore8(i, byte(and(addr, 0xf), lookup)) - addr := div(addr, 0x10) - jumpi(loop, i) - ret := sha3(0, 40) - } - } - } - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-181.md diff --git a/EIPS/eip-1812.md b/EIPS/eip-1812.md index 8ff5f0759d7e79..dd5985dacff9c5 100644 --- a/EIPS/eip-1812.md +++ b/EIPS/eip-1812.md @@ -1,442 +1,7 @@ --- eip: 1812 -title: Ethereum Verifiable Claims -author: Pelle Braendgaard (@pelle) -discussions-to: https://ethereum-magicians.org/t/erc-1812-ethereum-verifiable-claims/2814 -status: Stagnant -type: Standards Track category: ERC -created: 2019-03-03 -requires: 712 +status: Moved --- -# Ethereum Verifiable Claims - -## Simple Summary - -Reusable Verifiable Claims using [EIP 712 Signed Typed Data](./eip-712.md). - -## Abstract -A new method for Off-Chain Verifiable Claims built on [EIP-712](./eip-712.md). These Claims can be issued by any user with a EIP 712 compatible web3 provider. Claims can be stored off chain and verified on-chain by Solidity Smart Contracts, State Channel Implementations or off-chain libraries. - -## Motivation -Reusable Off-Chain Verifiable Claims provide an important piece of integrating smart contracts with real world organizational requirements such as meeting regulatory requirements such as KYC, GDPR, Accredited Investor rules etc. - -[ERC-735](https://github.com/ethereum/EIPs/issues/735) and [ERC-780](https://github.com/ethereum/EIPs/issues/780) provide methods of making claims that live on chain. This is useful for some particular use cases, where some claim about an address must be verified on chain. - -In most cases though it is both dangerous and in some cases illegal (according to EU GDPR rules for example) to record Identity Claims containing Personal Identifying Information (PII) on an immutable public database such as the Ethereum blockchain. - -The W3C [Verifiable Claims Data Model and Representations](https://www.w3.org/TR/verifiable-claims-data-model/) as well as uPorts [Verification Message Spec](https://developer.uport.me/messages/verification) are proposed off-chain solutions. - -While built on industry standards such as [JSON-LD](https://json-ld.org) and [JWT](https://jwt.io) neither of them are easy to integrate with the Ethereum ecosystem. - -[EIP-712](./eip-712.md) introduces a new method of signing off chain Identity data. This provides both a data format based on Solidity ABI encoding that can easily be parsed on-chain an a new JSON-RPC call that is easily supported by existing Ethereum wallets and Web3 clients. - -This format allows reusable off-chain Verifiable Claims to be cheaply issued to users, who can present them when needed. - -## Prior Art -Verified Identity Claims such as those proposed by [uPort](https://developer.uport.me/messages/verification) and [W3C Verifiable Claims Working Group](https://www.w3.org/2017/vc/WG/) form an important part of building up reusable identity claims. - -[ERC-735](https://github.com/ethereum/EIPs/issues/735) and [ERC-780](https://github.com/ethereum/EIPs/issues/780) provide on-chain storage and lookups of Verifiable Claims. - -## Specification -### Claims -Claims can be generalized like this: - -> Issuer makes the claim that Subject is something or has some attribute and value. - -Claims should be deterministic, in that the same claim signed multiple times by the same signer. - -### Claims data structure -Each claim should be typed based on its specific use case, which EIP 712 lets us do effortlessly. But there are 3 minimal attributes required of the claims structure. - -* `subject` the subject of the claim as an `address` (who the claim is about) -* `validFrom` the time in seconds encoded as a `uint256` of start of validity of claim. In most cases this would be the time of issuance, but some claims may be valid in the future or past. -* `validTo` the time in seconds encoded as a `uint256` of when the validity of the claim expires. If you intend for the claim not to expire use `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`. - -The basic minimal claim data structure as a Solidity struct: - -```solidity -struct [CLAIM TYPE] { - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -The CLAIM TYPE is the actual name of the claim. While not required, in most cases use the taxonomy developed by [schema.org](https://schema.org/docs/full.html) which is also commonly used in other Verifiable Claims formats. - -Example claim that issuer knows a subject: - -```solidity -struct Know { - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -### Presenting a Verifiable Claim -#### Verifying Contract -When defining Verifiable Claims formats a Verifying Contract should be created with a public `verify()` view function. This makes it very easy for other smart contracts to verify a claim correctly. - -It also provides a convenient interface for web3 and state channel apps to verify claims securely. - -```solidity -function verifyIssuer(Know memory claim, uint8 v, bytes32 r, bytes32 s) public returns (address) { - bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR, - hash(claim) - ) - ); - require( - (claim.validFrom >= block.timestamp) && (block.timestamp < claim.validTo) -, "invalid issuance timestamps"); - return ecrecover(digest, v, r, s); -} -``` - -#### Calling a SmartContract function -Verifiable Claims can be presented to a solidity function call as it’s struct together with the `v`, `r` and `s` signature components. - -```solidity -function vouch(Know memory claim, uint8 v, bytes32 r, bytes32 s) public returns (bool) { - address issuer = verifier.verifyIssuer(claim, v, r, s); - require(issuer !== '0x0'); - knows[issuer][claim.subject] = block.number; - return true; -} -``` - -#### Embedding a Verifiable Claim in another Signed Typed Data structure -The Claim struct should be embedded in another struct together with the `v`, `r` and `s` signature parameters. - -```solidity -struct Know { - address subject; - uint256 validFrom; - uint256 validTo; -} - -struct VerifiableReference { - Know delegate; - uint8 v; - bytes32 r; - bytes32 s; -} - -struct Introduction { - address recipient; - VerifiableReference issuer; -} -``` - -Each Verifiable Claim should be individually verified together with the parent Signed Typed Data structure. - -Verifiable Claims issued to different EIP 712 Domains can be embedded within each other. - -#### State Channels -This proposal will not show how to use Eth Verifiable Claims as part of a specific State Channel method. - -Any State Channel based on EIP712 should be able to include the embeddable Verifiable Claims as part of its protocol. This could be useful for exchanging private Identity Claims between the parties for regulatory reasons, while ultimately not posting them to the blockchain on conclusion of a channel. - -### Key Delegation -In most simple cases the issuer of a Claim is the signer of the data. There are cases however where signing should be delegated to an intermediary key. - -KeyDelegation can be used to implement off chain signing for smart contract based addresses, server side key rotation as well as employee permissions in complex business use cases. - -#### ERC1056 Signing Delegation - -[ERC-1056](./eip-1056.md) provides a method for addresses to assign delegate signers. One of the primary use cases for this is that a smart contract can allow a key pair to sign on its behalf for a certain period. It also allows server based issuance tools to institute key rotation. - -To support this an additional `issuer` attribute can be added to the Claim Type struct. In this case the verification code should lookup the EthereumDIDRegistry to see if the signer of the data is an allowed signing delegate for the `issuer` - -The following is the minimal struct for a Claim containing an issuer: - -```solidity -struct [CLAIM TYPE] { - address subject; - address issuer; - uint256 validFrom; - uint256 validTo; -} -``` - -If the `issuer` is specified in the struct In addition to performing the standard ERC712 verification the verification code MUST also verify that the signing address is a valid `veriKey` delegate for the address specified in the issuer. - -```solidity -registry.validDelegate(issuer, 'veriKey', recoveredAddress) -``` - - -#### Embedded Delegation Proof -There may be applications, in particularly where organizations want to allow delegates to issue claims about specific domains and types. - -For this purpose instead of the `issuer` we allow a special claim to be embedded following this same format: - -```solidity -struct Delegate { - address issuer; - address subject; - uint256 validFrom; - uint256 validTo; -} - -struct VerifiableDelegate { - Delegate delegate; - uint8 v; - bytes32 r; - bytes32 s; -} - - -struct [CLAIM TYPE] { - address subject; - VerifiedDelegate issuer; - uint256 validFrom; - uint256 validTo; -} -``` - -Delegates should be created for specific EIP 712 Domains and not be reused across Domains. - -Implementers of new EIP 712 Domains can add further data to the `Delegate` struct to allow finer grained application specific rules to it. - -### Claim Types -#### Binary Claims -A Binary claim is something that doesn’t have a particular value. It either is issued or not. - -Examples: -* subject is a Person -* subject is my owner (eg. Linking an ethereum account to an owner identity) - -Example: - -```solidity -struct Person { - address issuer; - address subject; - uint256 validFrom; - uint256 validTo; -} -``` - -This is exactly the same as the minimal claim above with the CLAIM TYPE set to [Person](https://schema.org/Person). - -### Value Claims -Value claims can be used to make a claim about the subject containing a specific readable value. - -**WARNING**: Be very careful about using Value Claims as part of Smart Contract transactions. Identity Claims containing values could be a GDPR violation for the business or developer encouraging a user to post it to a public blockchain. - -Examples: -* subject’s name is Alice -* subjects average account balance is 1234555 - -Each value should use the `value` field to indicate the value. - -A Name Claim - -```solidity -struct Name { - address issuer; - address subject; - string name; - uint256 validFrom; - uint256 validTo; -} -``` - -Average Balance - -```solidity -struct AverageBalance { - address issuer; - address subject; - uint256 value; - uint256 validFrom; - uint256 validTo; -} -``` - -### Hashed Claims -Hashed claims can be used to make a claim about the subject containing the hash of a claim value. Hashes should use ethereum standard `keccak256` hashing function. - -**WARNING**: Be very careful about using Hashed Claims as part of Smart Contract transactions. Identity Claims containing hashes of known values could be a GDPR violation for the business or developer encouraging a user to post it to a public blockchain. - -Examples: -- [ ] hash of subject’s name is `keccak256(“Alice Torres”)` -- [ ] hash of subject’s email is `keccak256(“alice@example.com”)` - -Each value should use the `keccak256 ` field to indicate the hashed value. Question. The choice of using this name is that we can easily add support for future algorithms as well as maybe zkSnark proofs. - -A Name Claim - -```solidity -struct Name { - address issuer; - address subject; - bytes32 keccak256; - uint256 validFrom; - uint256 validTo; -} -``` - -Email Claim - -```solidity -struct Email { - address issuer; - address subject; - bytes32 keccak256; - uint256 validFrom; - uint256 validTo; -} -``` - -### EIP 712 Domain -The EIP 712 Domain specifies what kind of message that is to be signed and is used to differentiate between signed data types. The content MUST contain the following: - -```solidity -{ - name: "EIP1???Claim", - version: 1, - chainId: 1, // for mainnet - verifyingContract: 0x // TBD - salt: ... -} -``` - -#### Full Combined format for EIP 712 signing: - -Following the EIP 712 standard we can combine the Claim Type with the EIP 712 Domain and the claim itself (in the `message`) attribute. - -Eg: -```solidity - { - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Email": [ - { - "name": "subject", - "type": "address" - }, - { - "name": "keccak256", - "type": "bytes32" - }, - { - "name": "validFrom", - "type": "uint256" - }, - { - "name": "validTo", - "type": "uint256" - } - ] - }, - "primaryType": "Email", - "domain": { - "name": "EIP1??? Claim", - "version": "1", - "chainId": 1, - "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" - }, - "message": { - "subject": "0x5792e817336f41de1d8f54feab4bc200624a1d9d", - "value": "9c8465d9ae0b0bc167dee7f62880034f59313100a638dcc86a901956ea52e280", - "validFrom": "0x0000000000000000000000000000000000000000000000000001644b74c2a0", - "validTo": "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - } - } -``` - - -### Revocation -Both Issuers and Subjects should be allowed to revoke Verifiable Claims. Revocations can be handled through a simple on-chain registry. - -The ultimate rules of who should be able to revoke a claim is determined by the Verifying contract. - -The `digest` used for revocation is the EIP712 Signed Typed Data digest. - -```solidity -contract RevocationRegistry { - mapping (bytes32 => mapping (address => uint)) public revocations; - - function revoke(bytes32 digest) public returns (bool) { - revocations[digest][msg.sender] = block.number; - return true; - } - - function revoked(address party, bytes32 digest) public view returns (bool) { - return revocations[digest][party] > 0; - } -} -``` - -A verifying contract can query the Revocation Registry as such: - -```solidity -bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR, - hash(claim) - ) -); -require(valid(claim.validFrom, claim.validTo), "invalid issuance timestamps"); -address issuer = ecrecover(digest, v, r, s); -require(!revocations.revoked(issuer, digest), "claim was revoked by issuer"); -require(!revocations.revoked(claim.subject, digest), "claim was revoked by subject"); -``` - -### Creation of Verifiable Claims Domains - -Creating specific is Verifiable Claims Domains is out of the scope of this EIP. The Example Code has a few examples. - -EIP’s or another process could be used to standardize specific important Domains that are universally useful across the Ethereum world. - -## Rationale -Signed Typed Data provides a strong foundation for Verifiable Claims that can be used in many different kinds of applications built on both Layer 1 and Layer 2 of Ethereum. - -### Rationale for using not using a single EIP 712 Domain -EIP712 supports complex types and domains in itself, that we believe are perfect building blocks for building Verifiable Claims for specific purposes. - -The Type and Domain of a Claim is itself an important part of a claim and ensures that Verifiable Claims are used for the specific purposes required and not misused. - -EIP712 Domains also allow rapid experimentation, allowing taxonomies to be built up by the community. - -## Test Cases -There is a repo with a few example verifiers and consuming smart contracts written in Solidity: - -**Example Verifiers** -* [Verifier for very simple IdVerification Verifiable Claims containing minimal Personal Data](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/IdentityClaimsVerifier.sol) -* [Verifier for OwnershipProofs signed by a users wallet](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/OwnershipProofVerifier.sol) - -**Example Smart Contracts** -* [KYCCoin.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/KYCCoin.sol) - Example Token allows reusable IdVerification claims issued by trusted verifiers and users to whitelist their own addresses using OwnershipProofs -* [ConsortiumAgreement.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/ConsortiumAgreements.sol) - Example Consortium Agreement smart contract. Consortium Members can issue Delegated Claims to employees or servers to interact on their behalf. - -**Shared Registries** -* [RevocationRegistry.sol](https://github.com/uport-project/eip712-claims-experiments/blob/master/contracts/RevocationRegistry.sol) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1812.md diff --git a/EIPS/eip-1820.md b/EIPS/eip-1820.md index 67db3067b2cda4..a3f2b2cc2b848f 100644 --- a/EIPS/eip-1820.md +++ b/EIPS/eip-1820.md @@ -1,926 +1,7 @@ --- eip: 1820 -title: Pseudo-introspection Registry Contract -author: Jordi Baylina , Jacques Dafflon -discussions-to: https://github.com/ethereum/EIPs/pull/1820 -status: Final -type: Standards Track category: ERC -requires: 165, 214 -created: 2019-03-04 +status: Moved --- -> :information_source: **[ERC-1820] has superseded [ERC-820].** :information_source: -> [ERC-1820] fixes the incompatibility in the [ERC-165] logic which was introduced by the Solidity 0.5 update. -> Have a look at the [official announcement][erc1820-annoucement], and the comments about the [bug][erc820-bug] and the [fix][erc820-fix]. -> Apart from this fix, [ERC-1820] is functionally equivalent to [ERC-820]. -> -> :warning: [ERC-1820] MUST be used in lieu of [ERC-820]. :warning: - -## Simple Summary - -This standard defines a universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. - -This standard keeps backward compatibility with [ERC-165]. - -## Abstract - -This standard defines a registry where smart contracts and regular accounts can publish which functionality they implement---either directly or through a proxy contract. - -Anyone can query this registry to ask if a specific address implements a given interface and which smart contract handles its implementation. - -This registry MAY be deployed on any chain and shares the same address on all chains. - -Interfaces with zeroes (`0`) as the last 28 bytes are considered [ERC-165] interfaces, -and this registry SHALL forward the call to the contract to see if it implements the interface. - -This contract also acts as an [ERC-165] cache to reduce gas consumption. - -## Motivation - -There have been different approaches to define pseudo-introspection in Ethereum. -The first is [ERC-165] which has the limitation that it cannot be used by regular accounts. -The second attempt is [ERC-672] which uses reverse [ENS]. Using reverse [ENS] has two issues. -First, it is unnecessarily complicated, and second, [ENS] is still a centralized contract controlled by a multisig. -This multisig theoretically would be able to modify the system. - -This standard is much simpler than [ERC-672], and it is *fully* decentralized. - -This standard also provides a *unique* address for all chains. -Thus solving the problem of resolving the correct registry address for different chains. - -## Specification - -### [ERC-1820] Registry Smart Contract - -> This is an exact copy of the code of the [ERC1820 registry smart contract]. - -``` solidity -/* ERC1820 Pseudo-introspection Registry Contract - * This standard defines a universal registry smart contract where any address (contract or regular account) can - * register which interface it supports and which smart contract is responsible for its implementation. - * - * Written in 2019 by Jordi Baylina and Jacques Dafflon - * - * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to - * this software to the public domain worldwide. This software is distributed without any warranty. - * - * You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see - * . - * - * ███████╗██████╗ ██████╗ ██╗ █████╗ ██████╗ ██████╗ - * ██╔════╝██╔══██╗██╔════╝███║██╔══██╗╚════██╗██╔═████╗ - * █████╗ ██████╔╝██║ ╚██║╚█████╔╝ █████╔╝██║██╔██║ - * ██╔══╝ ██╔══██╗██║ ██║██╔══██╗██╔═══╝ ████╔╝██║ - * ███████╗██║ ██║╚██████╗ ██║╚█████╔╝███████╗╚██████╔╝ - * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ ╚═════╝ - * - * ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ - * ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝ - * ██████╔╝█████╗ ██║ ███╗██║███████╗ ██║ ██████╔╝ ╚████╔╝ - * ██╔══██╗██╔══╝ ██║ ██║██║╚════██║ ██║ ██╔══██╗ ╚██╔╝ - * ██║ ██║███████╗╚██████╔╝██║███████║ ██║ ██║ ██║ ██║ - * ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ - * - */ -pragma solidity 0.5.3; -// IV is value needed to have a vanity address starting with '0x1820'. -// IV: 53759 - -/// @dev The interface a contract MUST implement if it is the implementer of -/// some (other) interface for any address other than itself. -interface ERC1820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not. - /// @param interfaceHash keccak256 hash of the name of the interface - /// @param addr Address for which the contract will implement the interface - /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); -} - - -/// @title ERC1820 Pseudo-introspection Registry Contract -/// @author Jordi Baylina and Jacques Dafflon -/// @notice This contract is the official implementation of the ERC1820 Registry. -/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-1820 -contract ERC1820Registry { - /// @notice ERC165 Invalid ID. - bytes4 constant internal INVALID_ID = 0xffffffff; - /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`). - bytes4 constant internal ERC165ID = 0x01ffc9a7; - /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address. - bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); - - /// @notice mapping from addresses and interface hashes to their implementers. - mapping(address => mapping(bytes32 => address)) internal interfaces; - /// @notice mapping from addresses to their manager. - mapping(address => address) internal managers; - /// @notice flag for each address and erc165 interface to indicate if it is cached. - mapping(address => mapping(bytes4 => bool)) internal erc165Cached; - - /// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'. - event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); - /// @notice Indicates 'newManager' is the address of the new manager for 'addr'. - event ManagerChanged(address indexed addr, address indexed newManager); - - /// @notice Query if an address implements an interface and through which contract. - /// @param _addr Address being queried for the implementer of an interface. - /// (If '_addr' is the zero address then 'msg.sender' is assumed.) - /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. - /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. - /// @return The address of the contract which implements the interface '_interfaceHash' for '_addr' - /// or '0' if '_addr' did not register an implementer for this interface. - function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) { - address addr = _addr == address(0) ? msg.sender : _addr; - if (isERC165Interface(_interfaceHash)) { - bytes4 erc165InterfaceHash = bytes4(_interfaceHash); - return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0); - } - return interfaces[addr][_interfaceHash]; - } - - /// @notice Sets the contract which implements a specific interface for an address. - /// Only the manager defined for that address can set it. - /// (Each address is the manager for itself until it sets a new manager.) - /// @param _addr Address for which to set the interface. - /// (If '_addr' is the zero address then 'msg.sender' is assumed.) - /// @param _interfaceHash Keccak256 hash of the name of the interface as a string. - /// E.g., 'web3.utils.keccak256("ERC777TokensRecipient")' for the 'ERC777TokensRecipient' interface. - /// @param _implementer Contract address implementing '_interfaceHash' for '_addr'. - function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external { - address addr = _addr == address(0) ? msg.sender : _addr; - require(getManager(addr) == msg.sender, "Not the manager"); - - require(!isERC165Interface(_interfaceHash), "Must not be an ERC165 hash"); - if (_implementer != address(0) && _implementer != msg.sender) { - require( - ERC1820ImplementerInterface(_implementer) - .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC, - "Does not implement the interface" - ); - } - interfaces[addr][_interfaceHash] = _implementer; - emit InterfaceImplementerSet(addr, _interfaceHash, _implementer); - } - - /// @notice Sets '_newManager' as manager for '_addr'. - /// The new manager will be able to call 'setInterfaceImplementer' for '_addr'. - /// @param _addr Address for which to set the new manager. - /// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.) - function setManager(address _addr, address _newManager) external { - require(getManager(_addr) == msg.sender, "Not the manager"); - managers[_addr] = _newManager == _addr ? address(0) : _newManager; - emit ManagerChanged(_addr, _newManager); - } - - /// @notice Get the manager of an address. - /// @param _addr Address for which to return the manager. - /// @return Address of the manager for a given address. - function getManager(address _addr) public view returns(address) { - // By default the manager of an address is the same address - if (managers[_addr] == address(0)) { - return _addr; - } else { - return managers[_addr]; - } - } - - /// @notice Compute the keccak256 hash of an interface given its name. - /// @param _interfaceName Name of the interface. - /// @return The keccak256 hash of an interface name. - function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) { - return keccak256(abi.encodePacked(_interfaceName)); - } - - /* --- ERC165 Related Functions --- */ - /* --- Developed in collaboration with William Entriken. --- */ - - /// @notice Updates the cache with whether the contract implements an ERC165 interface or not. - /// @param _contract Address of the contract for which to update the cache. - /// @param _interfaceId ERC165 interface for which to update the cache. - function updateERC165Cache(address _contract, bytes4 _interfaceId) external { - interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache( - _contract, _interfaceId) ? _contract : address(0); - erc165Cached[_contract][_interfaceId] = true; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not. - // If the result is not cached a direct lookup on the contract address is performed. - // If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling - // 'updateERC165Cache' with the contract address. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return True if '_contract' implements '_interfaceId', false otherwise. - function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) { - if (!erc165Cached[_contract][_interfaceId]) { - return implementsERC165InterfaceNoCache(_contract, _interfaceId); - } - return interfaces[_contract][_interfaceId] == _contract; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return True if '_contract' implements '_interfaceId', false otherwise. - function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) { - uint256 success; - uint256 result; - - (success, result) = noThrowCall(_contract, ERC165ID); - if (success == 0 || result == 0) { - return false; - } - - (success, result) = noThrowCall(_contract, INVALID_ID); - if (success == 0 || result != 0) { - return false; - } - - (success, result) = noThrowCall(_contract, _interfaceId); - if (success == 1 && result == 1) { - return true; - } - return false; - } - - /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not. - /// @param _interfaceHash The hash to check. - /// @return True if '_interfaceHash' is an ERC165 interface (ending with 28 zeroes), false otherwise. - function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) { - return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; - } - - /// @dev Make a call on a contract without throwing if the function does not exist. - function noThrowCall(address _contract, bytes4 _interfaceId) - internal view returns (uint256 success, uint256 result) - { - bytes4 erc165ID = ERC165ID; - - assembly { - let x := mload(0x40) // Find empty storage location using "free memory pointer" - mstore(x, erc165ID) // Place signature at beginning of empty storage - mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature - - success := staticcall( - 30000, // 30k gas - _contract, // To addr - x, // Inputs are stored at location x - 0x24, // Inputs are 36 (4 + 32) bytes long - x, // Store output over input (saves space) - 0x20 // Outputs are 32 bytes long - ) - - result := mload(x) // Load the result - } - } -} - -``` - -### Deployment Transaction - -Below is the raw transaction which MUST be used to deploy the smart contract on any chain. - -``` -0xf90a388085174876e800830c35008080b909e5608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c00291ba01820182018201820182018201820182018201820182018201820182018201820a01820182018201820182018201820182018201820182018201820182018201820 -``` - -The strings of `1820`'s at the end of the transaction are the `r` and `s` of the signature. -From this deterministic pattern (generated by a human), anyone can deduce that no one knows the private key for the deployment account. - -### Deployment Method - -This contract is going to be deployed using the keyless deployment method---also known as [Nick]'s method---which relies on a single-use address. -(See [Nick's article] for more details). This method works as follows: - -1. Generate a transaction which deploys the contract from a new random account. - - This transaction MUST NOT use [EIP-155] in order to work on any chain. - - This transaction MUST have a relatively high gas price to be deployed on any chain. In this case, it is going to be 100 Gwei. - -2. Set the `v`, `r`, `s` of the transaction signature to the following values: - - ``` - v: 27, - r: 0x1820182018201820182018201820182018201820182018201820182018201820' - s: 0x1820182018201820182018201820182018201820182018201820182018201820' - ``` - - Those `r` and `s` values---made of a repeating pattern of `1820`'s---are predictable "random numbers" generated deterministically by a human. - -3. We recover the sender of this transaction, i.e., the single-use deployment account. - - > Thus we obtain an account that can broadcast that transaction, but we also have the warranty that nobody knows the private key of that account. - -4. Send exactly 0.08 ether to this single-use deployment account. - -5. Broadcast the deployment transaction. - -This operation can be done on any chain, guaranteeing that the contract address is always the same and nobody can use that address with a different contract. - - -### Single-use Registry Deployment Account - -``` -0xa990077c3205cbDf861e17Fa532eeB069cE9fF96 -``` - -This account is generated by reverse engineering it from its signature for the transaction. -This way no one knows the private key, but it is known that it is the valid signer of the deployment transaction. - -> To deploy the registry, 0.08 ether MUST be sent to this account *first*. - -### Registry Contract Address - -``` -0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 -``` - -The contract has the address above for every chain on which it is deployed. - -
-Raw metadata of ./contracts/ERC1820Registry.sol -
-{
-        "compiler": {
-          "version": "0.5.3+commit.10d17f24"
-        },
-        "language": "Solidity",
-        "output": {
-          "abi": [
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceHash",
-                  "type": "bytes32"
-                },
-                {
-                  "name": "_implementer",
-                  "type": "address"
-                }
-              ],
-              "name": "setInterfaceImplementer",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                }
-              ],
-              "name": "getManager",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "address"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_newManager",
-                  "type": "address"
-                }
-              ],
-              "name": "setManager",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_interfaceName",
-                  "type": "string"
-                }
-              ],
-              "name": "interfaceHash",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bytes32"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "pure",
-              "type": "function"
-            },
-            {
-              "constant": false,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "updateERC165Cache",
-              "outputs": [],
-              "payable": false,
-              "stateMutability": "nonpayable",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_addr",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceHash",
-                  "type": "bytes32"
-                }
-              ],
-              "name": "getInterfaceImplementer",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "address"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "implementsERC165InterfaceNoCache",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bool"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "constant": true,
-              "inputs": [
-                {
-                  "name": "_contract",
-                  "type": "address"
-                },
-                {
-                  "name": "_interfaceId",
-                  "type": "bytes4"
-                }
-              ],
-              "name": "implementsERC165Interface",
-              "outputs": [
-                {
-                  "name": "",
-                  "type": "bool"
-                }
-              ],
-              "payable": false,
-              "stateMutability": "view",
-              "type": "function"
-            },
-            {
-              "anonymous": false,
-              "inputs": [
-                {
-                  "indexed": true,
-                  "name": "addr",
-                  "type": "address"
-                },
-                {
-                  "indexed": true,
-                  "name": "interfaceHash",
-                  "type": "bytes32"
-                },
-                {
-                  "indexed": true,
-                  "name": "implementer",
-                  "type": "address"
-                }
-              ],
-              "name": "InterfaceImplementerSet",
-              "type": "event"
-            },
-            {
-              "anonymous": false,
-              "inputs": [
-                {
-                  "indexed": true,
-                  "name": "addr",
-                  "type": "address"
-                },
-                {
-                  "indexed": true,
-                  "name": "newManager",
-                  "type": "address"
-                }
-              ],
-              "name": "ManagerChanged",
-              "type": "event"
-            }
-          ],
-          "devdoc": {
-            "author": "Jordi Baylina and Jacques Dafflon",
-            "methods": {
-              "getInterfaceImplementer(address,bytes32)": {
-                "params": {
-                  "_addr": "Address being queried for the implementer of an interface. (If '_addr' is the zero address then 'msg.sender' is assumed.)",
-                  "_interfaceHash": "Keccak256 hash of the name of the interface as a string. E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface."
-                },
-                "return": "The address of the contract which implements the interface '_interfaceHash' for '_addr' or '0' if '_addr' did not register an implementer for this interface."
-              },
-              "getManager(address)": {
-                "params": {
-                  "_addr": "Address for which to return the manager."
-                },
-                "return": "Address of the manager for a given address."
-              },
-              "implementsERC165Interface(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract to check.",
-                  "_interfaceId": "ERC165 interface to check."
-                },
-                "return": "True if '_contract' implements '_interfaceId', false otherwise."
-              },
-              "implementsERC165InterfaceNoCache(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract to check.",
-                  "_interfaceId": "ERC165 interface to check."
-                },
-                "return": "True if '_contract' implements '_interfaceId', false otherwise."
-              },
-              "interfaceHash(string)": {
-                "params": {
-                  "_interfaceName": "Name of the interface."
-                },
-                "return": "The keccak256 hash of an interface name."
-              },
-              "setInterfaceImplementer(address,bytes32,address)": {
-                "params": {
-                  "_addr": "Address for which to set the interface. (If '_addr' is the zero address then 'msg.sender' is assumed.)",
-                  "_implementer": "Contract address implementing '_interfaceHash' for '_addr'.",
-                  "_interfaceHash": "Keccak256 hash of the name of the interface as a string. E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface."
-                }
-              },
-              "setManager(address,address)": {
-                "params": {
-                  "_addr": "Address for which to set the new manager.",
-                  "_newManager": "Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.)"
-                }
-              },
-              "updateERC165Cache(address,bytes4)": {
-                "params": {
-                  "_contract": "Address of the contract for which to update the cache.",
-                  "_interfaceId": "ERC165 interface for which to update the cache."
-                }
-              }
-            },
-            "title": "ERC1820 Pseudo-introspection Registry Contract"
-          },
-          "userdoc": {
-            "methods": {
-              "getInterfaceImplementer(address,bytes32)": {
-                "notice": "Query if an address implements an interface and through which contract."
-              },
-              "getManager(address)": {
-                "notice": "Get the manager of an address."
-              },
-              "implementsERC165InterfaceNoCache(address,bytes4)": {
-                "notice": "Checks whether a contract implements an ERC165 interface or not without using nor updating the cache."
-              },
-              "interfaceHash(string)": {
-                "notice": "Compute the keccak256 hash of an interface given its name."
-              },
-              "setInterfaceImplementer(address,bytes32,address)": {
-                "notice": "Sets the contract which implements a specific interface for an address. Only the manager defined for that address can set it. (Each address is the manager for itself until it sets a new manager.)"
-              },
-              "setManager(address,address)": {
-                "notice": "Sets '_newManager' as manager for '_addr'. The new manager will be able to call 'setInterfaceImplementer' for '_addr'."
-              },
-              "updateERC165Cache(address,bytes4)": {
-                "notice": "Updates the cache with whether the contract implements an ERC165 interface or not."
-              }
-            },
-            "notice": "This contract is the official implementation of the ERC1820 Registry.For more details, see https://eips.ethereum.org/EIPS/eip-1820"
-          }
-        },
-        "settings": {
-          "compilationTarget": {
-            "./contracts/ERC1820Registry.sol": "ERC1820Registry"
-          },
-          "evmVersion": "byzantium",
-          "libraries": {},
-          "optimizer": {
-            "enabled": true,
-            "runs": 200
-          },
-          "remappings": []
-        },
-        "sources": {
-          "./contracts/ERC1820Registry.sol": {
-            "content": "/* ERC1820 Pseudo-introspection Registry Contract\n * This standard defines a universal registry smart contract where any address (contract or regular account) can\n * register which interface it supports and which smart contract is responsible for its implementation.\n *\n * Written in 2019 by Jordi Baylina and Jacques Dafflon\n *\n * To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to\n * this software to the public domain worldwide. This software is distributed without any warranty.\n *\n * You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see\n * .\n *\n *    ███████╗██████╗  ██████╗ ██╗ █████╗ ██████╗  ██████╗\n *    ██╔════╝██╔══██╗██╔════╝███║██╔══██╗╚════██╗██╔═████╗\n *    █████╗  ██████╔╝██║     ╚██║╚█████╔╝ █████╔╝██║██╔██║\n *    ██╔══╝  ██╔══██╗██║      ██║██╔══██╗██╔═══╝ ████╔╝██║\n *    ███████╗██║  ██║╚██████╗ ██║╚█████╔╝███████╗╚██████╔╝\n *    ╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ ╚═════╝\n *\n *    ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗   ██╗\n *    ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝\n *    ██████╔╝█████╗  ██║  ███╗██║███████╗   ██║   ██████╔╝ ╚████╔╝\n *    ██╔══██╗██╔══╝  ██║   ██║██║╚════██║   ██║   ██╔══██╗  ╚██╔╝\n *    ██║  ██║███████╗╚██████╔╝██║███████║   ██║   ██║  ██║   ██║\n *    ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝\n *\n */\npragma solidity 0.5.3;\n// IV is value needed to have a vanity address starting with '0x1820'.\n// IV: 53759\n\n/// @dev The interface a contract MUST implement if it is the implementer of\n/// some (other) interface for any address other than itself.\ninterface ERC1820ImplementerInterface {\n    /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not.\n    /// @param interfaceHash keccak256 hash of the name of the interface\n    /// @param addr Address for which the contract will implement the interface\n    /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'.\n    function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);\n}\n\n\n/// @title ERC1820 Pseudo-introspection Registry Contract\n/// @author Jordi Baylina and Jacques Dafflon\n/// @notice This contract is the official implementation of the ERC1820 Registry.\n/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-1820\ncontract ERC1820Registry {\n    /// @notice ERC165 Invalid ID.\n    bytes4 constant internal INVALID_ID = 0xffffffff;\n    /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).\n    bytes4 constant internal ERC165ID = 0x01ffc9a7;\n    /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.\n    bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked(\"ERC1820_ACCEPT_MAGIC\"));\n\n    /// @notice mapping from addresses and interface hashes to their implementers.\n    mapping(address => mapping(bytes32 => address)) internal interfaces;\n    /// @notice mapping from addresses to their manager.\n    mapping(address => address) internal managers;\n    /// @notice flag for each address and erc165 interface to indicate if it is cached.\n    mapping(address => mapping(bytes4 => bool)) internal erc165Cached;\n\n    /// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'.\n    event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);\n    /// @notice Indicates 'newManager' is the address of the new manager for 'addr'.\n    event ManagerChanged(address indexed addr, address indexed newManager);\n\n    /// @notice Query if an address implements an interface and through which contract.\n    /// @param _addr Address being queried for the implementer of an interface.\n    /// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n    /// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n    /// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n    /// @return The address of the contract which implements the interface '_interfaceHash' for '_addr'\n    /// or '0' if '_addr' did not register an implementer for this interface.\n    function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {\n        address addr = _addr == address(0) ? msg.sender : _addr;\n        if (isERC165Interface(_interfaceHash)) {\n            bytes4 erc165InterfaceHash = bytes4(_interfaceHash);\n            return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0);\n        }\n        return interfaces[addr][_interfaceHash];\n    }\n\n    /// @notice Sets the contract which implements a specific interface for an address.\n    /// Only the manager defined for that address can set it.\n    /// (Each address is the manager for itself until it sets a new manager.)\n    /// @param _addr Address for which to set the interface.\n    /// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n    /// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n    /// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n    /// @param _implementer Contract address implementing '_interfaceHash' for '_addr'.\n    function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {\n        address addr = _addr == address(0) ? msg.sender : _addr;\n        require(getManager(addr) == msg.sender, \"Not the manager\");\n\n        require(!isERC165Interface(_interfaceHash), \"Must not be an ERC165 hash\");\n        if (_implementer != address(0) && _implementer != msg.sender) {\n            require(\n                ERC1820ImplementerInterface(_implementer)\n                    .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC,\n                \"Does not implement the interface\"\n            );\n        }\n        interfaces[addr][_interfaceHash] = _implementer;\n        emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);\n    }\n\n    /// @notice Sets '_newManager' as manager for '_addr'.\n    /// The new manager will be able to call 'setInterfaceImplementer' for '_addr'.\n    /// @param _addr Address for which to set the new manager.\n    /// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.)\n    function setManager(address _addr, address _newManager) external {\n        require(getManager(_addr) == msg.sender, \"Not the manager\");\n        managers[_addr] = _newManager == _addr ? address(0) : _newManager;\n        emit ManagerChanged(_addr, _newManager);\n    }\n\n    /// @notice Get the manager of an address.\n    /// @param _addr Address for which to return the manager.\n    /// @return Address of the manager for a given address.\n    function getManager(address _addr) public view returns(address) {\n        // By default the manager of an address is the same address\n        if (managers[_addr] == address(0)) {\n            return _addr;\n        } else {\n            return managers[_addr];\n        }\n    }\n\n    /// @notice Compute the keccak256 hash of an interface given its name.\n    /// @param _interfaceName Name of the interface.\n    /// @return The keccak256 hash of an interface name.\n    function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) {\n        return keccak256(abi.encodePacked(_interfaceName));\n    }\n\n    /* --- ERC165 Related Functions --- */\n    /* --- Developed in collaboration with William Entriken. --- */\n\n    /// @notice Updates the cache with whether the contract implements an ERC165 interface or not.\n    /// @param _contract Address of the contract for which to update the cache.\n    /// @param _interfaceId ERC165 interface for which to update the cache.\n    function updateERC165Cache(address _contract, bytes4 _interfaceId) external {\n        interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(\n            _contract, _interfaceId) ? _contract : address(0);\n        erc165Cached[_contract][_interfaceId] = true;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not.\n    //  If the result is not cached a direct lookup on the contract address is performed.\n    //  If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling\n    //  'updateERC165Cache' with the contract address.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return True if '_contract' implements '_interfaceId', false otherwise.\n    function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        if (!erc165Cached[_contract][_interfaceId]) {\n            return implementsERC165InterfaceNoCache(_contract, _interfaceId);\n        }\n        return interfaces[_contract][_interfaceId] == _contract;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return True if '_contract' implements '_interfaceId', false otherwise.\n    function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        uint256 success;\n        uint256 result;\n\n        (success, result) = noThrowCall(_contract, ERC165ID);\n        if (success == 0 || result == 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, INVALID_ID);\n        if (success == 0 || result != 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, _interfaceId);\n        if (success == 1 && result == 1) {\n            return true;\n        }\n        return false;\n    }\n\n    /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not.\n    /// @param _interfaceHash The hash to check.\n    /// @return True if '_interfaceHash' is an ERC165 interface (ending with 28 zeroes), false otherwise.\n    function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {\n        return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;\n    }\n\n    /// @dev Make a call on a contract without throwing if the function does not exist.\n    function noThrowCall(address _contract, bytes4 _interfaceId)\n        internal view returns (uint256 success, uint256 result)\n    {\n        bytes4 erc165ID = ERC165ID;\n\n        assembly {\n            let x := mload(0x40)               // Find empty storage location using \"free memory pointer\"\n            mstore(x, erc165ID)                // Place signature at beginning of empty storage\n            mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature\n\n            success := staticcall(\n                30000,                         // 30k gas\n                _contract,                     // To addr\n                x,                             // Inputs are stored at location x\n                0x24,                          // Inputs are 36 (4 + 32) bytes long\n                x,                             // Store output over input (saves space)\n                0x20                           // Outputs are 32 bytes long\n            )\n\n            result := mload(x)                 // Load the result\n        }\n    }\n}\n",
-            "keccak256": "0x64025ecebddb6e126a5075c1fd6c01de2840492668e2909cef7157040a9d1945"
-          }
-        },
-        "version": 1
-      }
-
-
- -### Interface Name - -Any interface name is hashed using `keccak256` and sent to `getInterfaceImplementer()`. - -If the interface is part of a standard, it is best practice to explicitly state the interface name and link to this published [ERC-1820] such that other people don't have to come here to look up these rules. - -For convenience, the registry provides a function to compute the hash on-chain: - -``` solidity -function interfaceHash(string _interfaceName) public pure returns(bytes32) -``` - -Compute the keccak256 hash of an interface given its name. - -> **identifier:** `65ba36c1` -> **parameters** -> `_interfaceName`: Name of the interface. -> **returns:** The `keccak256` hash of an interface name. - -#### **Approved ERCs** - -If the interface is part of an approved ERC, it MUST be named `ERC###XXXXX` where `###` is the number of the ERC and XXXXX should be the name of the interface in CamelCase. -The meaning of this interface SHOULD be defined in the specified ERC. - -Examples: - -- `keccak256("ERC20Token")` -- `keccak256("ERC777Token")` -- `keccak256("ERC777TokensSender")` -- `keccak256("ERC777TokensRecipient")` - -#### **[ERC-165] Compatible Interfaces** - -> The compatibility with [ERC-165], including the [ERC165 Cache], has been designed and developed with [William Entriken]. - -Any interface where the last 28 bytes are zeroes (`0`) SHALL be considered an [ERC-165] interface. - -**[ERC-165] Lookup** - -Anyone can explicitly check if a contract implements an [ERC-165] interface using the registry by calling one of the two functions below: - -``` solidity -function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC-165] interface or not. - -If the result is not cached a direct lookup on the contract address is performed. - -*NOTE*: If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling `updateERC165Cache` with the contract address. -(See [ERC165 Cache] for more details.) - -> **identifier:** `f712f3e8` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC-165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, `false` otherwise. - -``` solidity -function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC-165] interface or not without using nor updating the cache. - -> **identifier:** `b7056765` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC-165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, false otherwise. - -**[ERC-165] Cache** - -Whether a contract implements an [ERC-165] interface or not can be cached manually to save gas. - -If a contract dynamically changes its interface and relies on the [ERC-165] cache of the [ERC-1820] registry, the cache MUST be updated manually---there is no automatic cache invalidation or cache update. -Ideally the contract SHOULD automatically update the cache when changing its interface. -However anyone MAY update the cache on the contract's behalf. - -The cache update MUST be done using the `updateERC165Cache` function: - -``` solidity -function updateERC165Cache(address _contract, bytes4 _interfaceId) external -``` - -> **identifier:** `a41e7d51` -> **parameters** -> `_contract`: Address of the contract for which to update the cache. -> `_interfaceId`: [ERC-165] interface for which to update the cache. - -#### **Private User-defined Interfaces** - -This scheme is extensible. -You MAY make up your own interface name and raise awareness to get other people to implement it and then check for those implementations. -Have fun but please, you MUST not conflict with the reserved designations above. - -### Set An Interface For An Address - -For any address to set a contract as the interface implementation, it must call the following function of the [ERC-1820] registry: - -``` solidity -function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external -``` - -Sets the contract which implements a specific interface for an address. - -Only the `manager` defined for that address can set it. -(Each address is the manager for itself, see the [manager] section for more details.) - -*NOTE*: If `_addr` and `_implementer` are two different addresses, then: - -- The `_implementer` MUST implement the `ERC1820ImplementerInterface` (detailed below). -- Calling `canImplementInterfaceForAddress` on `_implementer` with the given `_addr` and `_interfaceHash` MUST return the `ERC1820_ACCEPT_MAGIC` value. - -*NOTE*: The `_interfaceHash` MUST NOT be an [ERC-165] interface---it MUST NOT end with 28 zeroes (`0`). - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. -This default value simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `29965a1d` -> **parameters** -> `_addr`: Address for which to set the interface. (If `_addr` is the zero address then `msg.sender` is assumed.) -> `_interfaceHash`: Keccak256 hash of the name of the interface as a string, for example `web3.utils.keccak256('ERC777TokensRecipient')` for the ERC777TokensRecipient interface. -> `_implementer`: Contract implementing `_interfaceHash` for `_addr`. - -### Get An Implementation Of An Interface For An Address - -Anyone MAY query the [ERC-1820] Registry to obtain the address of a contract implementing an interface on behalf of some address using the `getInterfaceImplementer` function. - -``` solidity -function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) -``` - -Query if an address implements an interface and through which contract. - -*NOTE*: If the last 28 bytes of the `_interfaceHash` are zeroes (`0`), then the first 4 bytes are considered an [ERC-165] interface and the registry SHALL forward the call to the contract at `_addr` to see if it implements the [ERC-165] interface (the first 4 bytes of `_interfaceHash`). -The registry SHALL also cache [ERC-165] queries to reduce gas consumption. Anyone MAY call the `erc165UpdateCache` function to update whether a contract implements an interface or not. - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. -This default value is consistent with the behavior of the `setInterfaceImplementer` function and simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `aabbb8ca` -> **parameters** -> `_addr`: Address being queried for the implementer of an interface. (If `_addr` is the zero address then `msg.sender` is assumed.) -> `_interfaceHash`: keccak256 hash of the name of the interface as a string. E.g. `web3.utils.keccak256('ERC777Token')` -> **returns:** The address of the contract which implements the interface `_interfaceHash` for `_addr` or `0` if `_addr` did not register an implementer for this interface. - - -### Interface Implementation (`ERC1820ImplementerInterface`) - -``` solidity -interface ERC1820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not. - /// @param interfaceHash keccak256 hash of the name of the interface - /// @param addr Address for which the contract will implement the interface - /// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); -} -``` - -Any contract being registered as the implementation of an interface for a given address MUST implement said interface. -In addition if it implements an interface on behalf of a different address, the contract MUST implement the `ERC1820ImplementerInterface` shown above. - -``` solidity -function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32) -``` - -Indicates whether a contract implements an interface (`interfaceHash`) for a given address (`addr`). - -If a contract implements the interface (`interfaceHash`) for a given address (`addr`), it MUST return `ERC1820_ACCEPT_MAGIC` when called with the `addr` and the `interfaceHash`. -If it does not implement the `interfaceHash` for a given address (`addr`), it MUST NOT return `ERC1820_ACCEPT_MAGIC`. - -> **identifier:** `f0083250` -> **parameters** -> `interfaceHash`: Hash of the interface which is implemented -> `addr`: Address for which the interface is implemented -> **returns:** `ERC1820_ACCEPT_MAGIC` only if the contract implements `ìnterfaceHash` for the address `addr`. - -The special value `ERC1820_ACCEPT_MAGIC` is defined as the `keccka256` hash of the string `"ERC1820_ACCEPT_MAGIC"`. - -``` solidity -bytes32 constant internal ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); -``` - -> The reason to return `ERC1820_ACCEPT_MAGIC` instead of a boolean is to prevent cases where a contract fails to implement the `canImplementInterfaceForAddress` but implements a fallback function which does not throw. In this case, since `canImplementInterfaceForAddress` does not exist, the fallback function is called instead, executed without throwing and returns `1`. Thus making it appear as if `canImplementInterfaceForAddress` returned `true`. - -### Manager - -The manager of an address (regular account or a contract) is the only entity allowed to register implementations of interfaces for the address. -By default, any address is its own manager. - -The manager can transfer its role to another address by calling `setManager` on the registry contract with the address for which to transfer the manager and the address of the new manager. - -**`setManager` Function** - -``` solidity -function setManager(address _addr, address _newManager) external -``` - -Sets `_newManager` as manager for `_addr`. - -The new manager will be able to call `setInterfaceImplementer` for `_addr`. - -If `_newManager` is `0x0`, the manager is reset to `_addr` itself as the manager. - -> **identifier:** `5df8122f` -> **parameters** -> `_addr`: Address for which to set the new manager. -> `_newManager`: The address of the new manager for `_addr`. (Pass `0x0` to reset the manager to `_addr`.) - -**`getManager` Function** - -``` solidity -function getManager(address _addr) public view returns(address) -``` - -Get the manager of an address. - -> **identifier:** `3d584063` -> **parameters** -> `_addr`: Address for which to return the manager. -> **returns:** Address of the manager for a given address. - -## Rationale - -This standards offers a way for any type of address (externally owned and contracts) to implement an interface and potentially delegate the implementation of the interface to a proxy contract. -This delegation to a proxy contract is necessary for externally owned accounts and useful to avoid redeploying existing contracts such as multisigs and DAOs. - -The registry can also act as a [ERC-165] cache in order to save gas when looking up if a contract implements a specific [ERC-165] interface. -This cache is intentionally kept simple, without automatic cache update or invalidation. -Anyone can easily and safely update the cache for any interface and any contract by calling the `updateERC165Cache` function. - -The registry is deployed using a keyless deployment method relying on a single-use deployment address to ensure no one controls the registry, thereby ensuring trust. - -## Backward Compatibility - -This standard is backward compatible with [ERC-165], as both methods MAY be implemented without conflicting with each other. - -## Test Cases - -Please check the [0xjac/ERC1820] repository for the full test suite. - -## Implementation - -The implementation is available in the repo: [0xjac/ERC1820]. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[EIP-155]: ./eip-155.md -[ERC-165]: ./eip-165.md -[ERC-672]: https://github.com/ethereum/EIPs/issues/672 -[ERC-820]: ./eip-820.md -[ERC-1820]: ./eip-1820.md -[ERC1820 registry smart contract]: https://github.com/0xjac/ERC1820/blob/master/contracts/ERC1820Registry.sol -[erc1820-annoucement]: https://github.com/ethereum/EIPs/issues/820#issuecomment-464109166 -[erc820-bug]: https://github.com/ethereum/EIPs/issues/820#issuecomment-452465748 -[erc820-fix]: https://github.com/ethereum/EIPs/issues/820#issuecomment-454021564 -[manager]: #manager -[lookup]: #get-an-implementation-of-an-interface-for-an-address -[ERC165 Cache]: #erc165-cache -[Nick's article]: https://medium.com/@weka/how-to-send-ether-to-11-440-people-187e332566b7 -[0xjac/ERC1820]: https://github.com/0xjac/ERC1820 -[Nick]: https://github.com/Arachnid/ -[William Entriken]: https://github.com/fulldecent -[ENS]: https://ens.domains/ +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1820.md diff --git a/EIPS/eip-1822.md b/EIPS/eip-1822.md index 9289266297ba7a..8c50fb12544d8c 100644 --- a/EIPS/eip-1822.md +++ b/EIPS/eip-1822.md @@ -1,349 +1,7 @@ --- eip: 1822 -title: Universal Upgradeable Proxy Standard (UUPS) -author: Gabriel Barros , Patrick Gallagher -discussions-to: https://ethereum-magicians.org/t/eip-1822-universal-upgradeable-proxy-standard-uups -status: Stagnant -type: Standards Track category: ERC -created: 2019-03-04 +status: Moved --- -## Table of contents - - - -- [Table of contents](#table-of-contents) -- [Simple Summary](#simple-summary) -- [Abstract](#abstract) -- [Motivation](#motivation) -- [Terminology](#terminology) -- [Specification](#specification) - - [Proxy Contract](#proxy-contract) - - [Functions](#functions) - - [`fallback`](#fallback) - - [`constructor`](#constructor) - - [Proxiable Contract](#proxiable-contract) - - [Functions](#functions-1) - - [`proxiable`](#proxiable) - - [`updateCodeAddress`](#updatecodeaddress) -- [Pitfalls when using a proxy](#pitfalls-when-using-a-proxy) - - [Separating Variables from Logic](#separating-variables-from-logic) - - [Restricting dangerous functions](#restricting-dangerous-functions) -- [Examples](#examples) - - [Owned](#owned) - - [ERC-20 Token](#erc-20-token) - - [Proxy Contract](#proxy-contract-1) - - [Token Logic Contract](#token-logic-contract) -- [References](#references) -- [Copyright](#copyright) - - -## Simple Summary - -Standard upgradeable proxy contract. - -## Abstract - -The following describes a standard for proxy contracts which is universally compatible with all contracts, and does not create incompatibility between the proxy and business-logic contracts. This is achieved by utilizing a unique storage position in the proxy contract to store the Logic Contract's address. A compatibility check ensures successful upgrades. Upgrading can be performed unlimited times, or as determined by custom logic. In addition, a method for selecting from multiple constructors is provided, which does not inhibit the ability to verify bytecode. - -## Motivation - -- Improve upon existing proxy implementations to improve developer experience for deploying and maintaining Proxy and Logic Contracts. - -- Standardize and improve the methods for verifying the bytecode used by the Proxy Contract. - -## Terminology - -- `delegatecall()` - Function in contract **A** which allows an external contract **B** (delegating) to modify **A**'s storage (see diagram below, [Solidity docs](https://solidity.readthedocs.io/en/v0.5.3/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries)) -- **Proxy Contract** - The contract **A** which stores data, but uses the logic of external contract **B** by way of `delegatecall()`. -- **Logic Contract** - The contract **B** which contains the logic used by Proxy Contract **A** -- **Proxiable Contract** - Inherited in Logic Contract **B** to provide the upgrade functionality - -

diagram

- -## Specification - -The Proxy Contract proposed here should be deployed _as is_, and used as a drop-in replacement for any existing methods of lifecycle management of contracts. In addition to the Proxy Contract, we propose the Proxiable Contract interface/base which establishes a pattern for the upgrade which does not interfere with existing business rules. The logic for allowing upgrades can be implemented as needed. - -### Proxy Contract - -#### Functions - -##### `fallback` - -The proposed fallback function follows the common pattern seen in other Proxy Contract implementations such as [Zeppelin][1] or [Gnosis][2]. - -However, rather than forcing use of a variable, the address of the Logic Contract is stored at the defined storage position `keccak256("PROXIABLE")`. This eliminates the possibility of collision between variables in the Proxy and Logic Contracts, thus providing "universal" compatibility with any Logic Contract. - -```javascript -function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } -} -``` - -#### `constructor` - -The proposed constructor accepts any number of arguments of any type, and thus is compatible with any Logic Contract constructor function. - -In addition, the arbitrary nature of the Proxy Contract's constructor provides the ability to select from one or more constructor functions available in the Logic Contract source code (e.g., `constructor1`, `constructor2`, ... etc. ). Note that if multiple constructors are included in the Logic Contract, a check should be included to prohibit calling a constructor again post-initialization. - -It's worth noting that the added functionality of supporting multiple constructors does not inhibit verification of the Proxy Contract's bytecode, since the initialization tx call data (input) can be decoded by first using the Proxy Contract ABI, and then using the Logic Contract ABI. - -The contract below shows the proposed implementation of the Proxy Contract. - -```javascript -contract Proxy { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - constructor(bytes memory constructData, address contractLogic) public { - // save the code address - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, contractLogic) - } - (bool success, bytes memory _ ) = contractLogic.delegatecall(constructData); // solium-disable-line - require(success, "Construction failed"); - } - - function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } - } -} -``` - -### Proxiable Contract - -The Proxiable Contract is included in the Logic Contract, and provides the functions needed to perform an upgrade. The compatibility check `proxiable` prevents irreparable updates during an upgrade. - -> :warning: Warning: `updateCodeAddress` and `proxiable` must be present in the Logic Contract. Failure to include these may prevent upgrades, and could allow the Proxy Contract to become entirely unusable. See below [Restricting dangerous functions](#restricting-dangerous-functions) - -#### Functions - -##### `proxiable` - -Compatibility check to ensure the new Logic Contract implements the Universal Upgradeable Proxy Standard. Note that in order to support future implementations, the `bytes32` comparison could be changed e.g., `keccak256("PROXIABLE-ERC1822-v1")`. - -##### `updateCodeAddress` - -Stores the Logic Contract's address at storage `keccak256("PROXIABLE")` in the Proxy Contract. - -The contract below shows the proposed implementation of the Proxiable Contract. - -```javascript -contract Proxiable { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - - function updateCodeAddress(address newAddress) internal { - require( - bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), - "Not compatible" - ); - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) - } - } - function proxiableUUID() public pure returns (bytes32) { - return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; - } -} -``` - -## Pitfalls when using a proxy - -The following common best practices should be employed for all Logic Contracts when using a proxy contract. - -### Separating Variables from Logic - -Careful consideration should be made when designing a new Logic Contract to prevent incompatibility with the existing storage of the Proxy Contract after an upgrade. Specifically, the order in which variables are instantiated in the new contract should not be modified, and any new variables should be added after all existing variables from the previous Logic Contract - -To facilitate this practice, we recommend utilizing a single "base" contract which holds all variables, and which is inherited in subsequent logic contract(s). This practice greatly reduces the chances of accidentally reordering variables or overwriting them in storage. - -### Restricting dangerous functions - -The compatibility check in the Proxiable Contract is a safety mechanism to prevent upgrading to a Logic Contract which does not implement the Universal Upgradeable Proxy Standard. However, as occurred in the parity wallet hack, it is still possible to perform irreparable damage to the Logic Contract itself. - -In order to prevent damage to the Logic Contract, we recommend restricting permissions for any potentially damaging functions to `onlyOwner`, and giving away ownership of the Logic Contract immediately upon deployment to a null address (e.g., address(1)). Potentially damaging functions include native functions such as `SELFDESTRUCT`, as well functions whose code may originate externally such as `CALLCODE`, and `delegatecall()`. In the [ERC-20 Token](#erc-20-token) example below, a `LibraryLock` contract is used to prevent destruction of the logic contract. - -## Examples - -### Owned - -In this example, we show the standard ownership example, and restrict the `updateCodeAddress` to only the owner. - -```javascript -contract Owned is Proxiable { - // ensures no one can manipulate this contract once it is deployed - address public owner = address(1); - - function constructor1() public{ - // ensures this can be called only once per *proxy* contract deployed - require(owner == address(0)); - owner = msg.sender; - } - - function updateCode(address newCode) onlyOwner public { - updateCodeAddress(newCode); - } - - modifier onlyOwner() { - require(msg.sender == owner, "Only owner is allowed to perform this action"); - _; - } -} -``` - -### ERC-20 Token - -#### Proxy Contract - -```javascript -pragma solidity ^0.5.1; - -contract Proxy { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - constructor(bytes memory constructData, address contractLogic) public { - // save the code address - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, contractLogic) - } - (bool success, bytes memory _ ) = contractLogic.delegatecall(constructData); // solium-disable-line - require(success, "Construction failed"); - } - - function() external payable { - assembly { // solium-disable-line - let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) - calldatacopy(0x0, 0x0, calldatasize) - let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) - let retSz := returndatasize - returndatacopy(0, 0, retSz) - switch success - case 0 { - revert(0, retSz) - } - default { - return(0, retSz) - } - } - } -} -``` - -#### Token Logic Contract - -``` javascript - -contract Proxiable { - // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" - - function updateCodeAddress(address newAddress) internal { - require( - bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), - "Not compatible" - ); - assembly { // solium-disable-line - sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) - } - } - function proxiableUUID() public pure returns (bytes32) { - return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; - } -} - - -contract Owned { - - address owner; - - function setOwner(address _owner) internal { - owner = _owner; - } - modifier onlyOwner() { - require(msg.sender == owner, "Only owner is allowed to perform this action"); - _; - } -} - -contract LibraryLockDataLayout { - bool public initialized = false; -} - -contract LibraryLock is LibraryLockDataLayout { - // Ensures no one can manipulate the Logic Contract once it is deployed. - // PARITY WALLET HACK PREVENTION - - modifier delegatedOnly() { - require(initialized == true, "The library is locked. No direct 'call' is allowed"); - _; - } - function initialize() internal { - initialized = true; - } -} - -contract ERC20DataLayout is LibraryLockDataLayout { - uint256 public totalSupply; - mapping(address=>uint256) public tokens; -} - -contract ERC20 { - // ... - function transfer(address to, uint256 amount) public { - require(tokens[msg.sender] >= amount, "Not enough funds for transfer"); - tokens[to] += amount; - tokens[msg.sender] -= amount; - } -} - -contract MyToken is ERC20DataLayout, ERC20, Owned, Proxiable, LibraryLock { - - function constructor1(uint256 _initialSupply) public { - totalSupply = _initialSupply; - tokens[msg.sender] = _initialSupply; - initialize(); - setOwner(msg.sender); - } - function updateCode(address newCode) public onlyOwner delegatedOnly { - updateCodeAddress(newCode); - } - function transfer(address to, uint256 amount) public delegatedOnly { - ERC20.transfer(to, amount); - } -} -``` - -## References - -- ["Escape-hatch" proxy Medium Post](https://medium.com/terminaldotco/escape-hatch-proxy-efb681de108d) - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - -[1]: https://github.com/maraoz/solidity-proxy/blob/master/contracts/Dispatcher.sol -[2]: https://blog.gnosis.pm/solidity-delegateproxy-contracts-e09957d0f201 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1822.md diff --git a/EIPS/eip-1844.md b/EIPS/eip-1844.md index a80e696c7b20cb..2025c3e05acae0 100644 --- a/EIPS/eip-1844.md +++ b/EIPS/eip-1844.md @@ -1,64 +1,7 @@ --- eip: 1844 -title: ENS Interface Discovery -author: Nick Johnson (@arachnid) -discussions-to: https://ethereum-magicians.org/t/ens-interface-discovery/2924 -status: Stagnant -type: Standards Track category: ERC -created: 2019-03-15 -requires: 137, 165 +status: Moved --- -## Simple Summary -Defines a method of associating contract interfaces with ENS names and addresses, and of discovering those interfaces. - -## Abstract -This EIP specifies a method for exposing interfaces associated with an ENS name or an address (typically a contract address) and allowing applications to discover those interfaces and interact with them. Interfaces can be implemented either by the target contract (if any) or by any other contract. - -## Motivation -EIP 165 supports interface discovery - determining if the contract at a given address supports a requested interface. However, in many cases it's useful to be able to discover functionality associated with a name or an address that is implemented by other contracts. - -For example, a token contract may not itself provide any kind of 'atomic swap' functionality, but there may be associated contracts that do. With ENS interface discovery, the token contract can expose this metadata, informing applications where they can find that functionality. - -## Specification -A new profile for ENS resolvers is defined, consisting of the following method: - -```solidity -function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address); -``` - -The EIP-165 interface ID of this interface is `0xb8f2bbb4`. - -Given an ENS name hash `node` and an EIP-165 `interfaceID`, this function returns the address of an appropriate implementer of that interface. If there is no interface matching that interface ID for that node, 0 is returned. - -The address returned by `interfaceImplementer` MUST refer to a smart contract. - -The smart contract at the returned address SHOULD implement EIP-165. - -Resolvers implementing this interface MAY utilise a fallback strategy: If no matching interface was explicitly provided by the user, query the contract returned by `addr()`, returning its address if the requested interface is supported by that contract, and 0 otherwise. If they do this, they MUST ensure they return 0, rather than reverting, if the target contract reverts. - -This field may be used with both forward resolution and reverse resolution. - -## Rationale - -A naive approach to this problem would involve adding this method directly to the target contract. However, doing this has several shortcomings: - - 1. Each contract must maintain its own list of interface implementations. - 2. Modifying this list requires access controls, which the contract may not have previously required. - 3. Support for this must be designed in when the contract is written, and cannot be retrofitted afterwards. - 4. Only one canonical list of interfaces can be supported. - -Using ENS resolvers instead mitigates these shortcomings, making it possible for anyone to associate interfaces with a name, even for contracts not previously built with this in mind. - -## Backwards Compatibility -There are no backwards compatibility issues. - -## Test Cases -TBD - -## Implementation -The PublicResolver in the [ensdomains/resolvers](https://github.com/ensdomains/resolvers/) repository implements this interface. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1844.md diff --git a/EIPS/eip-1898.md b/EIPS/eip-1898.md index 0bb8bc4d7c5ae6..f295164a93a90f 100644 --- a/EIPS/eip-1898.md +++ b/EIPS/eip-1898.md @@ -4,7 +4,7 @@ title: Add `blockHash` to defaultBlock methods description: Add `blockHash` option to JSON-RPC methods that currently support defaultBlock parameter. author: Charles Cooper (@charles-cooper) discussions-to: https://ethereum-magicians.org/t/eip-1898-add-blockhash-option-to-json-rpc-methods-that-currently-support-defaultblock-parameter/11757 -status: Review +status: Stagnant type: Standards Track category: Interface created: 2019-04-01 diff --git a/EIPS/eip-190.md b/EIPS/eip-190.md index bf909700db3f26..1afed0d966ea7c 100644 --- a/EIPS/eip-190.md +++ b/EIPS/eip-190.md @@ -1,96 +1,7 @@ --- eip: 190 -title: Ethereum Smart Contract Packaging Standard -author: Piper Merriam (@pipermerriam), Tim Coulter (@tcoulter), Denis Erfurt (@mhhf), RJ Catalano (@VoR0220), Iuri Matias (@iurimatias) -status: Final -type: Standards Track category: ERC -created: 2017-01-10 +status: Moved --- -# Abstract - -This ERC proposes a specification for Ethereum smart contract packages. - -The specification was collaboratively developed by the following Ethereum development framework maintainers. - -* Tim Coulter (Truffle) -* Denis Erfurt (Dapple) -* Piper Merriam (Populus) -* RJ Catalano (Eris PM) -* Iuri Matias (Embark) - -# Motivation - -Packaging is a core piece of modern software development which is missing from the Ethereum ecosystem. The lack of packaging limits the ability for developers to reuse code which negatively affects productivity and security. - -A key example of this is the ERC20 standard. There are a few well audited reusable token contracts available but most developers end up writing their own because of the difficulty in finding and reusing existing code. - -A packaging standard should have the following positive effects on the ecosystem: - -* Greater overall productivity caused by the ability to reuse existing code. -* Increased security caused by the ability to reuse existing well audited implementations of common patterns (ERC20, crowdfunding, etc). - -Smart contract packaging should also have a direct positive effect on the end user. Wallet software will be able to consume a released package and generate an interface for interacting with any deployed contracts included within that package. With the advent of [ENS](./eip-137.md) all of the pieces will be in place for a wallet to take a human readable name and present the user with an interface for interacting with the underlying application. - - -# Specification - -The full specification for this standard is maintained separately in the repository [epm/epm-spec](https://github.com/ethpm/epm-spec). - -This EIP refers to the `1.0.0` version of the specification: [https://github.com/ethpm/epm-spec/tree/v1.0.0](https://github.com/ethpm/epm-spec/tree/v1.0.0) - -The specification contains details for a single document referred to as a *"Release Lockfile"*. - -* Release Lockfile Specification: [https://github.com/ethpm/epm-spec/blob/v1.0.0/release-lockfile.spec.md](https://github.com/ethpm/epm-spec/blob/v1.0.0/release-lockfile.spec.md). -* JSON Schema for Release Lockfile: [https://github.com/ethpm/epm-spec/blob/v1.0.0/spec/release-lockfile.spec.json](https://github.com/ethpm/epm-spec/blob/v1.0.0/spec/release-lockfile.spec.json) - -> These documents have not been inlined into this ERC to ensure that there is a single source of truth for the specification. - - -# Use Cases - -This specification covers the following types of smart contract packages. - -1. Packages with contracts intended to be used as base contract such as the common `owned` pattern. -2. Packages with contracts that are ready to use as-is such as an ERC20 token contract. -3. Packages with deployed contracts such as libraries or services. - -Full explanations and examples of these use cases can be found in the [`README.md`](https://github.com/ethpm/epm-spec/blob/v1.0.0/README.md#use-cases) from the `epm/epm-spec` repository. - - -# Package Managers - -The *Release Lockfile* is intended for consumption by package management software. Specific care was made to ensure that all of the following functionality can be implemented by package managers. - - -## Deterministic builds - -Ensures that a package will always resolve to the same set of dependencies and source files. Both source files and dependencies are content addressed to ensure that the referenced resources cannot change. - - -## Bytecode verification - -Contains the appropriate information for a package manager to inspect a deployed contract and verify that its bytecode matches the bytecode that results from compilation and linking of the package source code. - - -## Multi-chain deploys - -Supports deployments across multiple chains, allowing a package to define addresses on both the public mainnet and testnet. - - -## Trusted packages - -Allows for packages which exclude source code or other elements which would be needed for verification of the contract bytecode. This allows for minimalistic packages to be created for special situations where the package manager will not be performing verification. - - -# Framework support and integration - -Support for ERC190 is either implemented or in progress for the following: - -* [Truffle](https://truffleframework.com/) -* [Populus](https://populus.readthedocs.io/en/latest/) -* [Dapple](https://dapple.readthedocs.io/en/master/) -* [Eris PM](https://github.com/eris-ltd/eris-cli) -* [Embark](https://github.com/iurimatias/embark-framework) -* [Browser Solidity](https://github.com/ethereum/remix-ide/issues/386) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-190.md diff --git a/EIPS/eip-1900.md b/EIPS/eip-1900.md index a11b794dbc3a40..0cc739bb3846ef 100644 --- a/EIPS/eip-1900.md +++ b/EIPS/eip-1900.md @@ -1,276 +1,7 @@ --- eip: 1900 -title: dType - Decentralized Type System for EVM -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/1882 -status: Stagnant -type: Standards Track category: ERC -created: 2019-03-28 +status: Moved --- -## Simple Summary - -The EVM and related languages such as Solidity need consensus on an extensible Type System in order to further evolve into the Singleton Operating System (The World Computer). - -## Abstract - -We are proposing a decentralized Type System for Ethereum, to introduce data definition (and therefore ABI) consistency. This ERC focuses on defining an on-chain Type Registry (named `dType`) and a common interface for creating types, based on `struct`s. - - -## Motivation - -In order to build a network of interoperable protocols on Ethereum, we need data standardization, to ensure a smooth flow of on-chain information. Off-chain, the Type Registry will allow a better analysis of blockchain data (e.g. for blockchain explorers) and creation of smart contract development tools for easily using existing types in a new smart contract. - -However, this is only the first phase. As defined in this document and in the future proposals that will be based on this one, we are proposing something more: a decentralized Type System with Data Storage - [ERC-2158](https://github.com/ethereum/EIPs/pull/2158). In addition, developers can create libraries of `pure` functions that know how to interact and modify the data entries - [dType Functions Extension](https://github.com/ethereum/EIPs/issues/1921). This will effectively create the base for a general functional programming system on Ethereum, where developers can use previously created building blocks. - -To summarize: - -* We would like to have a good decentralized medium for integrating all Ethereum data, and relationships between the different types of data. Also, a way to address the behavior related to each data type. -* Functional programming becomes easier. Functions like `map`, `reduce`, `filter`, are implemented by each type library. -* Solidity development tools could be transparently extended to include the created types (For example in IDEs like Remix). At a later point, the EVM itself can have precompiled support for these types. -* The system can be easily extended to types pertaining to other languages. (With type definitions in the source (Swarm stored source code in the respective language)) -* The dType database should be part of the System Registry for the Operating System of The World Computer - - -## Specification - -The Type Registry can have a governance protocol for its CRUD operations. However, this, and other permission guards are not covered in this proposal. - -### Type Definition and Metadata - -The dType registry should support the registration of Solidity's elementary and complex types. In addition, it should also support contract events definitions. In this EIP, the focus will be on describing the minimal on-chain type definition and metadata needed for registering Solidity user-defined types. - -#### Type Definition: TypeLibrary - -A type definition consists of a type library containing: -- the nominal `struct` used to define the type -- additional functions: - - `isInstanceOf`: checks whether a given variable is an instance of the defined type. Additional rules can be defined for each type fields, e.g. having a specific range for a `uint16 amount`. - - provide HOFs such as `map`, `filter`, `reduce` - - `structureBytes` and `destructureBytes`: provide type structuring and destructuring. This can be useful for low-level calls or assembly code, when importing contract interfaces is not an efficient option. It can also be used for type checking. - -A simple example is: - -```solidity -pragma solidity ^0.5.0; -pragma experimental ABIEncoderV2; - -library myBalanceLib { - - struct myBalance { - string accountName; - uint256 amount; - } - - function structureBytes(bytes memory data) pure public returns(myBalance memory balance) - - function destructureBytes(myBalance memory balance) pure public returns(bytes memory data) - - function isInstanceOf(myBalance memory balance) pure public returns(bool isInstance) - - function map( - address callbackAddr, - bytes4 callbackSig, - myBalance[] memory balanceArr - ) - view - internal - returns (myBalance[] memory result) -} -``` - -Types can also use existing types in their composition. However, this will always result in a directed acyclic graph. - -```solidity -library myTokenLib { - using myBalanceLib for myBalanceLib.myBalance; - - struct myToken { - address token; - myBalanceLib.myBalance; - } -} -``` - -#### Type Metadata: dType Registry - -Type metadata will be registered on-chain, in the dType registry contract. This consists of: -- `name` - the type's name, as it would be used in Solidity; it can be stored as a `string` or encoded as `bytes`. The name can have a human-readable part and a version number. -- `typeChoice` - used for storing additional ABI data that differentiate how types are handled on and off chain. It is defined as an `enum` with the following options: `BaseType`, `PayableFunction`, `StateFunction`, `ViewFunction`, `PureFunction`, `Event` -- `contractAddress` - the Ethereum `address` of the `TypeRootContract`. For this proposal, we can consider the Type Library address as the `TypeRootContract`. Future EIPs will make it more flexible and propose additional TypeStorage contracts that will modify the scope of `contractAddress` - [ERC-2158](https://github.com/ethereum/EIPs/pull/2158). -- `source` - a `bytes32` Swarm hash where the source code of the type library and contracts can be found; in future EIPs, where dType will be extended to support other languages (e.g. JavaScript, Rust), the file identified by the Swarm hash will contain the type definitions in that language. -- `types` - metadata for subtypes: the first depth level internal components. This is an array of objects (`structs`), with the following fields: - - `name` - the subtype name, of type `string`, similar to the above `name` definition - - `label` - the subtype label - - `dimensions` - `string[]` used for storing array dimensions. E.g.: - - `[]` -> `TypeA` - - `[""]` -> `TypeA[]` - - `["2"]` -> `TypeA[2]` - - `["",""]` -> `TypeA[][]` - - `["2","3"]` -> `TypeA[2][3]` - -Examples of metadata, for simple, value types: -```javascript -{ - "contractAddress": "0x0000000000000000000000000000000000000000", - "typeChoice": 0, - "source": "0x0000000000000000000000000000000000000000000000000000000000000000", - "name": "uint256", - "types": [] -} - -{ - "contractAddress": "0x0000000000000000000000000000000000000000", - "typeChoice": 0, - "source": "0x0000000000000000000000000000000000000000000000000000000000000000", - "name": "string", - "types": [] -} -``` - -Composed types can be defined as: -```javascript -{ - "contractAddress": "0x105631C6CdDBa84D12Fa916f0045B1F97eC9C268", - "typeChoice": 0, - "source": , - "name": "myBalance", - "types": [ - {"name": "string", "label": "accountName", dimensions: []}, - {"name": "uint256", "label": "amount", dimensions: []} - ] -} -``` - -Composed types can be further composed: -```javascript -{ - "contractAddress": "0x91E3737f15e9b182EdD44D45d943cF248b3a3BF9", - "typeChoice": 0, - "source": , - "name": "myToken", - "types": [ - {"name": "address", "label": "token", dimensions: []}, - {"name": "myBalance", "label": "balance", dimensions: []} - ] -} -``` - -`myToken` type will have the final data format: `(address,(string,uint256))` and a labeled format: `(address token, (string accountName, uint256 amount))`. - -##### dType Registry Data Structures and Interface - -To store this metadata, the dType registry will have the following data structures: - -```solidity -enum TypeChoices { - BaseType, - PayableFunction, - StateFunction, - ViewFunction, - PureFunction, - Event -} - -struct dTypes { - string name; - string label; - string[] dimensions; -} - -struct dType { - TypeChoices typeChoice; - address contractAddress; - bytes32 source; - string name; - dTypes[] types; -} - -``` - -For storage, we propose a pattern which isolates the type metadata from additional storage-specific data and allows CRUD operations on records. - -```solidity -// key: identifier -mapping(bytes32 => Type) public typeStruct; - -// array of identifiers -bytes32[] public typeIndex; - -struct Type { - dType data; - uint256 index; -} -``` - -Note that we are proposing to define the type's primary identifier, `identifier`, as `keccak256(abi.encodePacked(name))`. If the system is extended to other programming languages, we can define `identifier` as `keccak256(abi.encodePacked(language, name))`. -Initially, single word English names can be disallowed, avoiding name squatting. - - -The dType registry interface is: - -```solidity -import './dTypeLib.sol'; -interface dType { - event LogNew(bytes32 indexed identifier, uint256 indexed index); - event LogUpdate(bytes32 indexed identifier, uint256 indexed index); - event LogRemove(bytes32 indexed identifier, uint256 indexed index); - - function insert(dTypeLib.dType calldata data) external returns (bytes32 identifier); - - function remove(bytes32 identifier) external returns(uint256 index); - - function count() external view returns(uint256 counter); - - function getTypeIdentifier(string memory name) pure external returns (bytes32 identifier); - - function getByIdentifier(bytes32 identifier) view external returns(dTypeLib.dType memory dtype); - - function get(string memory name) view external returns(dTypeLib.dType memory dtype); - - function isRegistered(bytes32 identifier) view external returns(bool registered); -} -``` - -**Notes:** - -To ensure backward compatibility, we suggest that updating types should not be supported. - -The `remove` function can also be removed from the interface, to ensure immutability. One reason for keeping it would be clearing up storage for types that are not in use or have been made obsolete. However, this can have undesired effects and should be accompanied by a solid permissions system, testing and governance process. This part will be updated when enough feedback has been received. - -## Rationale - -The Type Registry must store the minimum amount of information for rebuilding the type ABI definition. This allows us to: -* support on-chain interoperability -* decode blockchain side effects off-chain (useful for block explorers) -* allow off-chain tools to cache and search through the collection (e.g. editor plugin for writing typed smart contracts) - -There is one advantage that has become clear with the emergence of global operating systems, like Ethereum: we can have a global type system through which the system’s parts can interoperate. Projects should agree on standardizing types and a type registry, continuously working on improving them, instead of creating encapsulated projects, each with their own types. - -The effort of having consensus on new types being added or removing unused ones is left to the governance system. - -After the basis of such a system is specified, we can move forward to building a static type checking system at compile time, based on the type definitions and rules stored in the dType registry. - -The Type Library must express the behavior strictly pertinent to its defined type. Additional behavior, required by various project's business logic can be added later, through libraries containing functions that handle the respective type. These can also be registered in dType, but will be detailed in a future ERC. - -This is an approach that will separate definitions from stored data and behavior, allowing for easier and more secure fine-grained upgrades. - -## Backwards Compatibility - -This proposal does not affect extant Ethereum standards or implementations. It uses the present experimental version of ABIEncoderV2. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/tree/master/contracts/contracts. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -A video demo of the current implementation (a more extended version of this proposal) can be seen at https://youtu.be/pcqi4yWBDuQ. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1900.md diff --git a/EIPS/eip-1901.md b/EIPS/eip-1901.md index ad873a408ec2ee..7585b479f73a02 100644 --- a/EIPS/eip-1901.md +++ b/EIPS/eip-1901.md @@ -16,7 +16,7 @@ This is a proposal to add [OpenRPC](https://github.com/open-rpc/spec) support to The OpenRPC Document and generated Documentation that specifies all the methods an EVM-based blockchain should implement can be found [here](https://github.com/etclabscore/ethereum-json-rpc-specification). -This was first proposed [here as an ECIP](https://github.com/etclabscore/ECIPs/blob/master/ECIPs/ECIP-1053.md), but the benefits of this kind of tooling is apparent across Bitcoin, Ethereum Classic, Ethereum and other JSON-RPC accessible blockchains. +This was first proposed [here as an ECIP](https://github.com/etclabscore/ECIPs/blob/master/ECIPs/ecip-1053.md), but the benefits of this kind of tooling is apparent across Bitcoin, Ethereum Classic, Ethereum and other JSON-RPC accessible blockchains. ## Motivation diff --git a/EIPS/eip-191.md b/EIPS/eip-191.md index 9a166d62af91f7..69a96210719f60 100644 --- a/EIPS/eip-191.md +++ b/EIPS/eip-191.md @@ -1,108 +1,7 @@ --- eip: 191 -title: Signed Data Standard -author: Martin Holst Swende (@holiman), Nick Johnson -discussions-to: https://github.com/ethereum/EIPs/issues/191 -status: Final -type: Standards Track category: ERC -created: 2016-01-20 +status: Moved --- -# Abstract - -This ERC proposes a specification about how to handle signed data in Ethereum contracts. - -# Motivation - -Several multisignature wallet implementations have been created which accepts `presigned` transactions. A `presigned` transaction is a chunk of binary `signed_data`, along with signature (`r`, `s` and `v`). The interpretation of the `signed_data` has not been specified, leading to several problems: - -* Standard Ethereum transactions can be submitted as `signed_data`. An Ethereum transaction can be unpacked, into the following components: `RLP` (hereby called `RLPdata`), `r`, `s` and `v`. If there are no syntactical constraints on `signed_data`, this means that `RLPdata` can be used as a syntactically valid `presigned` transaction. -* Multisignature wallets have also had the problem that a `presigned` transaction has not been tied to a particular `validator`, i.e a specific wallet. Example: - 1. Users `A`, `B` and `C` have the `2/3`-wallet `X` - 2. Users `A`, `B` and `D` have the `2/3`-wallet `Y` - 3. User `A` and `B` submit `presigned` transactions to `X`. - 4. Attacker can now reuse their presigned transactions to `X`, and submit to `Y`. - -## Specification - -We propose the following format for `signed_data` - -``` -0x19 <1 byte version> . -``` - -The initial `0x19` byte is intended to ensure that the `signed_data` is not valid RLP. - -> For a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. - -That means that any `signed_data` cannot be one RLP-structure, but a 1-byte `RLP` payload followed by something else. Thus, any EIP-191 `signed_data` can never be an Ethereum transaction. - -Additionally, `0x19` has been chosen because since ethereum/go-ethereum#2940 , the following is prepended before hashing in personal_sign: - -``` -"\x19Ethereum Signed Message:\n" + len(message). -``` - -Using `0x19` thus makes it possible to extend the scheme by defining a version `0x45` (`E`) to handle these kinds of signatures. - -### Registry of version bytes - -| Version byte | EIP | Description -| ------------ | -------------- | ----------- -| `0x00` | [191][eip-191] | Data with intended validator -| `0x01` | [712][eip-712] | Structured data -| `0x45` | [191][eip-191] | `personal_sign` messages - -#### Version `0x00` - -``` -0x19 <0x00> -``` - -The version `0x00` has `` for the version specific data. In the case of a Multisig wallet that perform an execution based on a passed signature, the validator address is the address of the Multisig itself. The data to sign could be any arbitrary data. - -#### Version `0x01` - -The version `0x01` is for structured data as defined in [EIP-712] - -#### Version `0x45` (E) - -``` -0x19 <0x45 (E)> -``` - -The version `0x45` (E) has `` for the version-specific data. The data to sign can be any arbitrary data. - -> NB: The `E` in `Ethereum Signed Message` refers to the version byte 0x45. The character `E` is `0x45` in hexadecimal which makes the remainder, `thereum Signed Message:\n + len(message)`, the version-specific data. - -[EIP-191]: ./eip-191.md -[EIP-712]: ./eip-712.md - -### Example - -The following snippets has been written in Solidity 0.8.0. - -#### Version `0x00` - -```solidity -function signatureBasedExecution(address target, uint256 nonce, bytes memory payload, uint8 v, bytes32 r, bytes32 s) public payable { - - // Arguments when calculating hash to validate - // 1: byte(0x19) - the initial 0x19 byte - // 2: byte(0) - the version byte - // 3: address(this) - the validator address - // 4-6 : Application specific data - - bytes32 hash = keccak256(abi.encodePacked(byte(0x19), byte(0), address(this), msg.value, nonce, payload)); - - // recovering the signer from the hash and the signature - addressRecovered = ecrecover(hash, v, r, s); - - // logic of the wallet - // if (addressRecovered == owner) executeOnTarget(target, payload); -} -``` -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-191.md diff --git a/EIPS/eip-1921.md b/EIPS/eip-1921.md index 9a671313f46a92..ee46bc42861c18 100644 --- a/EIPS/eip-1921.md +++ b/EIPS/eip-1921.md @@ -1,141 +1,7 @@ --- eip: 1921 -title: dType Functions Extension -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/1921 -status: Stagnant -type: Standards Track category: ERC -created: 2019-04-06 -requires: 1900 +status: Moved --- -## Simple Summary -In the context of dType, the Decentralized Type System described in [EIP-1900](./eip-1900.md), we are proposing to add support for registering functions (with a preference for `pure` and `view`) in the dType Registry. - -## Abstract - -This proposal is part of a series of EIPs focused on expanding the concept of a Decentralized Type System, as explained in [EIP-1900](./eip-1900.md). -The current EIP specifies the data definitions and interfaces needed to support registering individual smart contract functions, as entries in the dType Registry. - -## Motivation - -In order to evolve the EVM into a Singleton Operating System, we need a way to register, find and address contract functions that we want to run in an automated way. -This implies having access to all the data needed to run the function inside the EVM. - -Aside from the above motivation, there are also near future benefits for this proposal. Having a globally available, non-custodial functions registry, will democratize the development of tools, such as those targeting: blockchain data analysis (e.g. block explorers), smart contract IDEs, security analysis of smart contracts. - -Registering new smart contract functions can be done through the same consensus mechanism as [EIP-1900](./eip-1900.md) mentions, in order to avoid burdening the chain state with redundant or improper records. - - -## Specification - -This specification targets `pure` and `view` functions. - -For each function, we can store: -* `name` - type `string` unique function name, as defined in EIP-1900; required -* `types` - the type data and label of each input, as defined in EIP-1900; required -* `outputs` - the type data and label of each output; required -* `contractAddress` - type `address` - smart contract where the function resides, as defined in EIP-1900; optional for interfaces -* `source` - type `bytes32` - reference to an external file containing the function source code, as defined in EIP-1900; optional - -Therefore, this proposal adds `outputs` to the EIP-1900 type registration definition. - -An example of a function registration object for the dType registry is: - -``` -{ - "name": "setStaked", - "types": [ - {"name": "TypeA", "label": "typeA", "relation":0, "dimensions":[]} - ], - "typeChoice": 4, - "contractAddress":
, - "source": , - "outputs": [ - {"name": "TypeB", "label": "typeB", "relation":0, "dimensions":[]} - ] -} -``` - -The above object will be passed to `.insert({...})` - -An additional `setOutputs` function is proposed for the dType registry: - -``` -function setOutputs( - bytes32 identifier, - dTypes[] memory outputs -) - public -``` - -- `identifier` - type `bytes32`, the type's identifier, as defined in EIP-1900 -- `outputs` - type `dTypes`, as defined in EIP-1900 - -### Implementation Suggestions - - -In the dType registry implementation, `outputs` can be stored in a `mapping`: - -``` -mapping(bytes32 => dTypes[]) public outputs; -``` - -## Rationale - - -The suggestion to treat each `pure` or `view` function as a separate entity instead of having a contract-based approach allows us to: -* have a global context of readily available functions -* scale designs through functional programming patterns rather than contract-encapsulated logic (which can be successfully used to scale development efforts independently) -* bidirectionally connect functions with the types they use, making automation easier -* cherry-pick functions from already deployed contracts if the other contract functions do not pass community consensus -* have scope-restricted improvements - instead of redeploying entire contracts, we can just redeploy the new function versions that we want to be added to the registry -* enable fine-grained auditing of individual functions, for the common good -* enable testing directly on a production chain, without state side-effects - -The proposal to store the minimum ABI information on-chain, for each function, allows us to: -* enable on-chain automation (e.g. function chaining and composition) -* be backward compatible in case the function signature format changes (e.g. from `bytes4` to `bytes32`): multiple signature calculation functions can be registered with dType. Examples: - -``` -function getSignatureBytes4(bytes32 identifier) - view - public - returns (bytes4 signature) - -function getSignatureBytes32(bytes32 identifier) - view - public - returns (bytes32 signature) -``` - -- `identifier` - the type's identifier, as defined in EIP-1900 -- `signature` - the function's signature - - -Concerns about this design might be: -* redundancy of storing `contractAddress` for each function that is part of the same contract - -We think that state/storage cost will be compensated through DRYness across the chain, due to reusing types and functions that have already been registered and are now easy to find. Other state/storage cost calculations will be added once the specification and implementation are closer to be finalized. - - -Note that the input and output types are based on types that have already been registered. This lowers the amount of ABI information needed to be stored for each function and enables developers to aggregate and find functions that use the same types for their I/O. This can be a powerful tool for interoperability and smart contract composition. - - -## Backwards Compatibility - -This proposal does not affect extant Ethereum standards or implementations. Registering functions for existing contract deployments should be fully supported. - -## Test Cases - -Will be added. - - -## Implementation - -In-work implementation examples can be found at https://github.com/pipeos-one/dType. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1921.md diff --git a/EIPS/eip-1922.md b/EIPS/eip-1922.md index 2ab2ed7c8a05b1..9bce442d20f524 100644 --- a/EIPS/eip-1922.md +++ b/EIPS/eip-1922.md @@ -1,207 +1,7 @@ --- eip: 1922 -title: zk-SNARK Verifier Standard -author: Michael Connor , Chaitanya Konda , Duncan Westland -discussions-to: https://github.com/ethereum/EIPs/issues/1922 -type: Standards Track category: ERC -status: Stagnant -created: 2018-09-14 -requires: 165, 196, 197 +status: Moved --- -## Simple Summary - -A standard interface for "Verifier" contracts which verify zk-SNARKs. - -## Abstract -The following standard allows for the implementation of a standard contract API for the verification of zk-SNARKs ("Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge"), also known as "proofs", "arguments", or "commitments". - -This standard provides basic functionality to load all necessary parameters for the verification of any zk-SNARK into a verifier contract, so that the proof may ultimately return a `true` or `false` response; corresponding to whether it has been verified or not verified. - -## Motivation -zk-SNARKs are a promising area of interest for the Ethereum community. Key applications of zk-SNARKs include: -- Private transactions -- Private computations -- Improved transaction scaling through proofs of "bundled" transactions - -A standard interface for verifying all zk-SNARKs will allow applications to more easily implement private transactions, private contracts, and scaling solutions; and to extract and interpret the limited information which gets emitted during zk-SNARK verifications. - -This standard was initially proposed by EY, and was inspired in particular by the requirements of businesses wishing to keep their agreements, transactions, and supply chain activities confidential—all whilst still benefiting from the commonly cited strengths of blockchains and smart contracts. - -:warning: TODO: Explain the benefits to and perspective of a consumer of information. I.e. the thing that interfaces with the standard verifier. - -## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -Terminology in this specification is used consistently with libsnark, as provided in that project's README. - -* Adhering Contract — A Verifier contract which adheres to this specification. -* Arithmetic circuit: An abstraction of logical statements into addition and multiplication gates. -* Public Inputs: often denoted as a vector 'x' in zk-SNARKs literature, and denoted `inputs` in this interface. An arithmetic circuit can be thought of as taking two parameters; the Public Inputs, 'x', and a secret 'witness', 'w'. This interface standardises functions which can load the `inputs` into an Adhering Contract. -* Proof: A 'prover' who wants to 'prove' knowledge of some secret witness 'w' (which satisfies an arithmetic circuit), generates a `proof` from: the circuit's Proving Key; their secret witness 'w'; and its corresponding Public Inputs 'x'. Together, a pair `(proof, inputs)` of satisfying `inputs` and their corresponding `proof` forms a zk-SNARK. -* Verification Key: A 'trusted setup' calculation creates both a public 'Proving Key' and a public 'Verification Key' from an arithmetic circuit. This interface does not provide a method for loading a Verification Key onto the blockchain. An Adhering Contract SHALL be able to accept arguments of knowledge (`(proof, inputs)` pairs) for at least one Verification Key. We shall call such Verification Keys 'in-scope' Verification Keys. An Adhering Contract MUST be able to interpret unambiguously a unique `verificationKeyId` for each of its 'in-scope' Verification Keys. - -**Every ERC-XXXX compliant verifier contract must implement the `ERCXXXX` and `ERC165` interfaces** (subject to "caveats" below): - - -```solidity -pragma solidity ^0.5.6; - -/// @title EIP-XXXX zk-SNARK Verifier Standard -/// @dev See https://github.com/EYBlockchain/zksnark-verifier-standard -/// Note: the ERC-165 identifier for this interface is 0xXXXXXXXX. -/// ⚠️ TODO: Calculate interface identifier -interface EIPXXXX /* is ERC165 */ { - /// @notice Checks the arguments of Proof, through elliptic curve - /// pairing functions. - /// @dev - /// MUST return `true` if Proof passes all checks (i.e. the Proof is - /// valid). - /// MUST return `false` if the Proof does not pass all checks (i.e. if the - /// Proof is invalid). - /// @param proof A zk-SNARK. - /// @param inputs Public inputs which accompany Proof. - /// @param verificationKeyId A unique identifier (known to this verifier - /// contract) for the Verification Key to which Proof corresponds. - /// @return result The result of the verification calculation. True - /// if Proof is valid; false otherwise. - function verify(uint256[] calldata proof, uint256[] calldata inputs, bytes32 verificationKeyId) external returns (bool result); -} -``` -### Interface -``` solidity -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - -### Taxonomy - -⚠️ TODO: Add a specific reference to libsnark here, explaining the choice of variable names. - -:warning: TODO: Explain how _C_ may not necessarily be a satisfiable arithmetic circuit of logical statements. As current, this is a limitation to certain kinds of SNARKS. Whereas the source references also mention polynomials, and other applications. - -_C_ — A satisfiable arithmetic circuit abstraction of logical statements. - -_lambda​_ - A random number, generated at the 'setup' phase - commonly referred to as 'toxic waste', because knowledge of _lambda​_ would allow an untrustworthy party to create 'false' proofs which would verify as 'true'. _lambda​_ must be destroyed. - -_pk​_ - The proving key for a particular circuit _C​_. - -_vk_ - The verification key for a particular circuit _C_. - -Both _pk​_ and _vk​_ are generated as a pair by some function _G​_: -_(pk, vk) = G(lambda, C)​_ - -Note: _C_ can be represented unambiguously by either of _pk_ or _vk_. In zk-SNARK constructions, _vk_ is much smaller in size than _pk_, so as to enable succinct verification on-chain. Hence, _vk_ is the representative of _C_ that is 'known' to the contract. Therefore, we can identify each circuit uniquely through some `verificationKeyId`, where `verificationKeyId` serves as a more succinct mapping to _vk_. - -_w_ - A 'private witness' string. A private argument to the circuit _C_ known only to the prover, which, when combined with the `inputs` argument _x_, comprises an argument of knowledge which satisfies the circuit _C_. - -_x_ or `inputs` - A vector of 'Public Inputs'. A public argument to the circuit _C_ which, when combined with the private witness string _w_, comprises an argument of knowledge which satisfies the circuit _C_. - -_pi_ or `proof` - an encoded vector of values which represents the 'prover's' 'argument of knowledge' of values _w_ and _x_ which satisfy the circuit _C_. -_pi = P(pk, x, w)_. - -The ultimate purpose of a Verifier contract, as specified in this EIP, is to verify a proof (of the form _pi​_) through some verification function _V​_. - -_V(vk, x, pi) = 1_, if there exists a _w_ s.t. _C(x,w)=1_. -_V(vk, x, pi) = 0_, otherwise. - -The `verify()` function of this specification serves the purpose of _V​_; returning either `true` (the proof has been verified to satisfy the arithmetic circuit) or `false` (the proof has not been verified). - -### Functions - -#### `verify` -The `verify` function forms the crux this standard. The parameters are intended to be as generic as possible, to allow for verification of any zk-SNARK: - -- `proof` - Specified as `uint256[]`. - `uint256` is the most appropriate type for elliptic curve operations over a finite field. Indeed, this type is used in the predominant 'Pairing library' implementation of zk-SNARKs by Christian Reitweissner. - A one-dimensional dynamic array has been chosen for several reasons: - - Dynamic: There are several possible methods for producing a zk-SNARK proof, including PGHR13, G16, GM17, and future methods might be developed in future. Although each method may produce differently sized proof objects, a dynamic array allows for these differing sizes. - - Array: An array has been chosen over a 'struct' object, because it is currently easier to pass dynamic arrays between functions in Solidity. Any proof 'struct' can be 'flattened' to an array and passed to the `verify` function. Interpretation of that flattened array is the responsibility of the implemented body of the function. Example implementations demonstrate that this can be achieved. - - One-dimensional: A one-dimensional array has been chosen over multi-dimensional array, because it is currently easier to work with one-dimensional arrays in Solidity. Any proof can be 'flattened' to a one-dimensional array and passed to the `verify` function. Interpretation of that flattened array is the responsibility of the implemented body of the Adhering Contract. Example implementations demonstrate that this can be achieved. - -- `inputs` - Specified as `uint256[]`. - `uint256` is the most appropriate type for elliptic curve operations over a finite field. Indeed, this type is used in the predominant 'Pairing library' implementation of zk-SNARKs by Christian Reitweissner. - The number of inputs will vary in size, depending on the number of 'public inputs' of the arithmetic circuit being verified against. In a similar vein to the `proof` parameter, a one-dimensional dynamic array is general enough to cope with any set of inputs to a zk-SNARK. - -- `verificationKeyId` - A verification key (referencing a particular arithmetic circuit) only needs to be stored on-chain once. Any proof (relating to the underlying arithmetic circuit) can then be verified against that verification key. Given this, it would be unnecessary (from a 'gas cost' point of view) to pass a duplicate of the full verification key to the `verify` function every time a new `(proof, inputs)` pair is passed in. We do however need to tell the Adhering Verifier Contract which verification key corresponds to the `(proof, inputs)` pair being passed in. A `verificationKeyId` serves this purpose - it uniquely represents a verification key as a `bytes32` id. A method for uniquely assigning a `verificationKeyId` to a verification key is the responsibility of the implemented body of the Adhering Contract. - - -## Backwards Compatibility -- At the time this EIP was first proposed, there was one implementation on the Ethereum main net - deployed by [EY](https://www.ey.com). This was compiled with Solidity 0.4.24 for compatibility with [Truffle](https://github.com/trufflesuite/truffle) but otherwise compatible with this standard, which is presented at the latest current version of Solidity. -- Dr Christian Reitwiessner's excellent [example](https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d) of a Verifier contract and elliptic curve pairing library has been instrumental in the Ethereum community's experimentation and development of zk-SNARK protocols. Many of the naming conventions of this EIP have been kept consistent with his example. -- Existing zk-SNARK compilers such as [ZoKrates](https://github.com/Zokrates/ZoKrates), which produce 'Verifier.sol' contracts, do not currently produce Verifier contracts which adhere to this EIP specification. - - :warning: TODO: Provide a converter contract or technique which allows ZoKrates verifier.sol contracts to adhere with this EIP. - - -## Test Cases - -Truffle tests of example implementations are included in the test case repository. - -⚠️ TODO: Reference specific test cases because there are many currently in the repository. - - -## Implementations -Detailed example implementations and Truffle tests of these example implementations are included in this repository. - -:warning: TODO: Update referenced verifier implementations so that they are ready-to-deploy or reference deployed versions of those implementations. At current, the referenced code specifically states "DO NOT USE THIS IN PRODUCTION". - -:warning: TODO: Provide reference to an implementation which interrogates a standard verifier contract that implements this standard. - - -## References - -:warning: TODO: Update references and confirm that each reference is cited (parenthetical documentation not necessary) in the text. - -**Standards** - -1. ERC-20 Token Standard. ./eip-20.md - -1. ERC-165 Standard Interface Detection. ./eip-165.md -1. ERC-173 Contract Ownership Standard (DRAFT). ./eip-173.md -1. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. ./eip-196.md -1. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. ./eip-197.md -1. Ethereum Name Service (ENS). https://ens.domains -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -##### Educational material: zk-SNARKs -1. Zcash. What are zk-SNARKs? https://z.cash/technology/zksnarks.html -1. Vitalik Buterin. zk-SNARKs: Under the Hood. https://medium.com/@VitalikButerin/zk-snarks-under-the-hood-b33151a013f6 -1. Christian Reitweissner. zk-SNARKs in a Nutshell. https://blog.ethereum.org/2016/12/05/zksnarks-in-a-nutshell/ -1. Ben-Sasson, Chiesa, Tromer, et. al. Succinct Non-Interactive Zero Knowledge for a von Neumann Architecture. https://eprint.iacr.org/2013/879.pdf - -##### Notable applications of zk-SNARKs - 1. EY. Implementation of a business agreement through Token Commitment transactions on the Ethereum mainnet. https://github.com/EYBlockchain/ZKPChallenge - 1. Zcash. https://z.cash - 1. Zcash. How Transactions Between Shielded Addresses Work. https://blog.z.cash/zcash-private-transactions/ - -##### Notable projects relating to zk-SNARKs - 1. libsnark: A C++ Library for zk-SNARKs ("project README)". https://github.com/scipr-lab/libsnark - 1. ZoKrates: Scalable Privacy-Preserving Off-Chain Computations. https://www.ise.tu-berlin.de/fileadmin/fg308/publications/2018/2018_eberhardt_ZoKrates.pdf - 1. ZoKrates Project Repository. https://github.com/JacobEberhardt/ZoKrates - 1. Joseph Stockermans. zkSNARKs: Driver's Ed. https://github.com/jstoxrocky/zksnarks_example - 1. Christian Reitweissner - snarktest.solidity. https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d - -##### Notable 'alternatives' to zk-SNARKs - areas of ongoing zero-knowledge proof research - 1. Vitalik Buterin. STARKs. https://vitalik.ca/general/2017/11/09/starks_part_1.html - 1. Bu ̈nz, Bootle, Boneh, et. al. Bulletproofs. https://eprint.iacr.org/2017/1066.pdf - 1. Range Proofs. https://www.cosic.esat.kuleuven.be/ecrypt/provpriv2012/abstracts/canard.pdf - 1. Apple. Secure Enclaves. https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave - 1. Intel Software Guard Extensions. https://software.intel.com/en-us/sgx - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1922.md diff --git a/EIPS/eip-1923.md b/EIPS/eip-1923.md index 2865c7dc9f8a99..dd3d9382335887 100644 --- a/EIPS/eip-1923.md +++ b/EIPS/eip-1923.md @@ -1,164 +1,7 @@ --- eip: 1923 -title: zk-SNARK Verifier Registry Standard -author: Michael Connor , Chaitanya Konda , Duncan Westland -discussions-to: https://github.com/ethereum/EIPs/issues/1923 -type: Standards Track category: ERC -status: Stagnant -created: 2018-12-22 -requires: 165, 196, 197 +status: Moved --- -## Simple Summary - - -A standard interface for a "Verifier Registry"'" contract, through which all zk-SNARK verification activity can be registered. - -## Abstract -The following standard allows for the implementation of a standard contract API for the registration of zk-SNARKs ("Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge"), also known as "proofs", "arguments", or "commitments". - -TODO: Which functionality is exposed in this standard interface? - -## Motivation -zk-SNARKs are a promising area of interest for the Ethereum community. Key applications of zk-SNARKs include: -- Private transactions -- Private computations -- Ethereum scaling through proofs of 'bundled' transactions - -A standard interface for registering all zk-SNARKs will allow applications to more easily implement private transactions, private contracts, and scaling solutions; and to extract and interpret the limited information which gets emitted during zk-SNARK verifications. - -:warning: TODO: Explain the motivation for standardizing a registry, other than simply standardizing the verifier interactions. - -⚠️ TODO: Explain the benefits to and perspective of a consumer of information. I.e. the thing that interfaces with the standard verifier registry. - -## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - - -```solidity -pragma solidity ^0.5.6; - -/// @title EIP-XXXX zk-SNARK Verifier Registry Standard -/// @dev See https://github.com/EYBlockchain/zksnark-verifier-standard -/// Note: the ERC-165 identifier for this interface is 0xXXXXXXXXX. -/// ⚠️ TODO: Set the interface identifier -interface EIP-XXXX /* is ERC165 */ { - - event NewProofSubmitted(bytes32 indexed _proofId, uint256[] _proof, uint64[] _inputs); - - event NewVkRegistered(bytes32 indexed _vkId); - - event NewVerifierContractRegistered(address indexed _contractAddress); - - event NewAttestation(bytes32 indexed _proofId, address indexed _verifier, bool indexed _result); - - - function getVk(bytes32 _vkId) external returns (uint256[] memory); - - function registerVerifierContract(address _verifierContract) external returns (bool); - - function registerVk(uint256[] calldata _vk, address[] calldata _verifierContracts) external returns (bytes32); - - function submitProof(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId) external returns (bytes32); - - function submitProof(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId, address _verifierContract) external returns (bytes32); - - function submitProofAndVerify(uint256[] calldata _proof, uint64[] calldata _inputs, bytes32 _vkId, address _verifierContract) external returns (bytes32); - - function attestProof(bytes32 _proofId, bytes32 _vkId, bool _result) external; - - function attestProofs(bytes32[] calldata _proofIds, bytes32[] calldata _vkIds, bool[] calldata _results) external; - - function challengeAttestation(bytes32 _proofId, uint256[] calldata _proof, uint64[] calldata _inputs, address _verifierContract) external; - - function createNewVkId(uint256[] calldata _vk) external pure returns (bytes32); - - function createNewProofId(uint256[] calldata _proof, uint64[] calldata _inputs) external pure returns (bytes32); - -} -``` -### Interface -``` solidity -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - -⚠️ TODO: Add Rationale section. - -### Backwards Compatibility - -⚠️ TODO: Add Backwards Compatibility section. - -### Test Cases - -Truffle tests of example implementations are included in this Repo. - -⚠️ TODO: Reference specific test cases because there are many currently in the repository. - - -## Implementations -Detailed example implementations and Truffle tests of these example implementations are included in this Repo. - -⚠️ TODO: Update referenced verifier registry implementations so that they are ready-to-deploy or reference deployed versions of those implementations. At current, the referenced code specifically states "DO NOT USE THIS IN PRODUCTION". - -⚠️ TODO: Provide reference to an implementation which interrogates a standard verifier registry contract that implements this standard. - - -## References - -⚠️ TODO: Update references and confirm that each reference is cited (parenthetical documentation not necessary) in the text. - -**Standards** - -1. ERC-20 Token Standard. ./eip-20.md - -1. ERC-165 Standard Interface Detection. ./eip-165.md -2. ERC-173 Contract Ownership Standard (DRAFT). ./eip-173.md -3. ERC-196 Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. ./eip-196.md -4. ERC-197 Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. ./eip-197.md -5. Ethereum Name Service (ENS). https://ens.domains -6. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -##### Educational material: zk-SNARKs - -1. Zcash. What are zk-SNARKs? https://z.cash/technology/zksnarks.html -2. Vitalik Buterin. zk-SNARKs: Under the Hood. https://medium.com/@VitalikButerin/zk-snarks-under-the-hood-b33151a013f6 -3. Christian Reitweissner. zk-SNARKs in a Nutshell. https://blog.ethereum.org/2016/12/05/zksnarks-in-a-nutshell/ -4. Ben-Sasson, Chiesa, Tromer, et. al. Succinct Non-Interactive Zero Knowledge for a von Neumann Architecture. https://eprint.iacr.org/2013/879.pdf - -##### Notable applications of zk-SNARKs - -1. EY. Implementation of a business agreement through Token Commitment transactions on the Ethereum mainnet. https://github.com/EYBlockchain/ZKPChallenge -2. Zcash. https://z.cash -3. Zcash. How Transactions Between Shielded Addresses Work. https://blog.z.cash/zcash-private-transactions/ - -##### Notable projects relating to zk-SNARKs - -1. libsnark: A C++ Library for zk-SNARKs ("project README)". https://github.com/scipr-lab/libsnark -2. ZoKrates: Scalable Privacy-Preserving Off-Chain Computations. https://www.ise.tu-berlin.de/fileadmin/fg308/publications/2018/2018_eberhardt_ZoKrates.pdf -3. ZoKrates Project Repository. https://github.com/JacobEberhardt/ZoKrates -4. Joseph Stockermans. zkSNARKs: Driver's Ed. https://github.com/jstoxrocky/zksnarks_example -5. Christian Reitweissner - snarktest.solidity. https://gist.github.com/chriseth/f9be9d9391efc5beb9704255a8e2989d - -##### Notable 'alternatives' to zk-SNARKs - areas of ongoing zero-knowledge proof research - -1. Vitalik Buterin. STARKs. https://vitalik.ca/general/2017/11/09/starks_part_1.html -2. Bu ̈nz, Bootle, Boneh, et. al. Bulletproofs. https://eprint.iacr.org/2017/1066.pdf -3. Range Proofs. https://www.cosic.esat.kuleuven.be/ecrypt/provpriv2012/abstracts/canard.pdf -4. Apple. Secure Enclaves. https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave -5. Intel Software Guard Extensions. https://software.intel.com/en-us/sgx - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1923.md diff --git a/EIPS/eip-1930.md b/EIPS/eip-1930.md index a4aa44434647e6..bfb1245e185189 100644 --- a/EIPS/eip-1930.md +++ b/EIPS/eip-1930.md @@ -127,7 +127,7 @@ This solution does not require to compute a ```E``` value and thus do not relies But this check still pass if the gas given was less AND the external call reverted or succeeded EARLY (so that the gas left after the call > txGas / 63). This can be an issue if the code executed as part of the CALL is reverting as a result of a check against the gas provided. Like a meta transaction in a meta transaction. -Similarly to the the previous solution, an EVM mechanism would be much better. +Similarly to the previous solution, an EVM mechanism would be much better. ## Backwards Compatibility diff --git a/EIPS/eip-1948.md b/EIPS/eip-1948.md index 2b58a1afff421c..6658ba14e44a09 100644 --- a/EIPS/eip-1948.md +++ b/EIPS/eip-1948.md @@ -1,159 +1,7 @@ --- eip: 1948 -title: Non-fungible Data Token -author: Johann Barbie (@johannbarbie), Ben Bollen , pinkiebell (@pinkiebell) -discussions-to: https://ethereum-magicians.org/t/erc-non-fungible-data-token/3139 -status: Stagnant -type: Standards Track category: ERC -created: 2019-04-18 -requires: 721 +status: Moved --- -## Simple Summary - -Some NFT use-cases require to have dynamic data associated with a non-fungible token that can change during its lifetime. Examples for dynamic data: -- cryptokitties that can change color -- intellectual property tokens that encode rights holders -- tokens that store data to transport them across chains - -The existing metadata standard does not suffice as data can only be set at minting time and not modified later. - -## Abstract - -Non-fungible tokens (NFTs) are extended with the ability to store dynamic data. A 32 bytes data field is added and a read function allows to access it. The write function allows to update it, if the caller is the owner of the token. An event is emitted every time the data updates and the previous and new value is emitted in it. - -## Motivation - -The proposal is made to standardize on tokens with dynamic data. Interactions with bridges for side-chains like xDAI or Plasma chains will profit from the ability to use such tokens. Protocols that build on data tokens like [distributed breeding](https://ethresear.ch/t/a-distributed-breeding-function/5264) will be enabled. - -## Specification - -An extension of [ERC-721](./eip-721.md) interface with the following functions and events is suggested: - -``` solidity -pragma solidity ^0.5.2; - -/** - * @dev Interface of the ERC1948 contract. - */ -interface IERC1948 { - - /** - * @dev Emitted when `oldData` is replaced with `newData` in storage of `tokenId`. - * - * Note that `oldData` or `newData` may be empty bytes. - */ - event DataUpdated(uint256 indexed tokenId, bytes32 oldData, bytes32 newData); - - /** - * @dev Reads the data of a specified token. Returns the current data in - * storage of `tokenId`. - * - * @param tokenId The token to read the data off. - * - * @return A bytes32 representing the current data stored in the token. - */ - function readData(uint256 tokenId) external view returns (bytes32); - - /** - * @dev Updates the data of a specified token. Writes `newData` into storage - * of `tokenId`. - * - * @param tokenId The token to write data to. - * @param newData The data to be written to the token. - * - * Emits a `DataUpdated` event. - */ - function writeData(uint256 tokenId, bytes32 newData) external; - -} -``` - -## Rationale - -The suggested data field in the NFT is used either for storing data directly, like a counter or address. If more data is required the implementer should fall back to authenticated data structures, like merkle- or patricia-trees. - -The proposal for this ERC stems from the [distributed breeding proposal](https://ethresear.ch/t/a-distributed-breeding-function/5264) to allow better integration of NFTs across side-chains. [ost.com](https://ost.com/), [Skale](https://skalelabs.com/), [POA](https://poa.network/), and [LeapDAO](https://leapdao.org/) have been part of the discussion. - -## Backwards Compatibility - -🤷‍♂️ No related proposals are known to the author, hence no backwards compatibility to consider. - -## Test Cases - -Simple happy test: - -``` javascript -const ERC1948 = artifacts.require('./ERC1948.sol'); - -contract('ERC1948', (accounts) => { - const firstTokenId = 100; - const empty = '0x0000000000000000000000000000000000000000000000000000000000000000'; - const data = '0x0101010101010101010101010101010101010101010101010101010101010101'; - let dataToken; - - beforeEach(async () => { - dataToken = await ERC1948.new(); - await dataToken.mint(accounts[0], firstTokenId); - }); - - it('should allow to write and read', async () => { - let rsp = await dataToken.readData(firstTokenId); - assert.equal(rsp, empty); - await dataToken.writeData(firstTokenId, data); - rsp = await dataToken.readData(firstTokenId); - assert.equal(rsp, data); - }); - -}); -``` - - -## Implementation - -An example implementation of the interface in solidity would look like this: - -``` solidity -/** - * @dev Implementation of ERC721 token and the `IERC1948` interface. - * - * ERC1948 is a non-fungible token (NFT) extended with the ability to store - * dynamic data. The data is a bytes32 field for each tokenId. If 32 bytes - * do not suffice to store the data, an authenticated data structure (hash or - * merkle tree) shall be used. - */ -contract ERC1948 is IERC1948, ERC721 { - - mapping(uint256 => bytes32) data; - - /** - * @dev See `IERC1948.readData`. - * - * Requirements: - * - * - `tokenId` needs to exist. - */ - function readData(uint256 tokenId) external view returns (bytes32) { - require(_exists(tokenId)); - return data[tokenId]; - } - - /** - * @dev See `IERC1948.writeData`. - * - * Requirements: - * - * - `msg.sender` needs to be owner of `tokenId`. - */ - function writeData(uint256 tokenId, bytes32 newData) external { - require(msg.sender == ownerOf(tokenId)); - emit DataUpdated(tokenId, data[tokenId], newData); - data[tokenId] = newData; - } - -} -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1948.md diff --git a/EIPS/eip-1965.md b/EIPS/eip-1965.md index 6dd8dc0e662033..bb791ced399219 100644 --- a/EIPS/eip-1965.md +++ b/EIPS/eip-1965.md @@ -16,7 +16,7 @@ This EIP adds a precompile that returns whether a specific chainID (EIP-155 uniq ## Motivation [EIP-155](./eip-155.md) proposes to use the chain ID to prevent the replay of transactions between different chains. It would be a great benefit to have the same possibility inside smart contracts when handling off-chain message signatures, especially for Layer 2 signature schemes using [EIP-712](./eip-712.md). -[EIP-1344](./eip-1344.md) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insuficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. Furthermore EIP-1344 can't protect replay properly for minority-led hardfork as the caching system cannot guarantee accuracy of the blockNumber at which the new chainID has been introduced. +[EIP-1344](./eip-1344.md) is attempting to solve this by giving smart contract access to the tip of the chainID history. This is insufficient as such value is changing. Hence why EIP-1344 describes a contract based solution to work around the problem. It would be better to solve it in a simpler, cheaper and safer manner, removing the potential risk of misuse present in EIP-1344. Furthermore EIP-1344 can't protect replay properly for minority-led hardfork as the caching system cannot guarantee accuracy of the blockNumber at which the new chainID has been introduced. [EIP-1959](./eip-1959.md) solves the issue of EIP-1344 but do not attempt to protect from minority-led hardfork as mentioned in the rationale. We consider this a mistake, since it remove some freedom to fork. We consider that all fork should be given equal oportunities. And while there will always be issues we can't solve for the majority that ignore a particular fork, **users that decide to use both the minority-fork and the majority-chain should be protected from replay without having to wait for the majority chain to update its chainID.** diff --git a/EIPS/eip-1967.md b/EIPS/eip-1967.md index 98165407df80b8..48b32f9e9dec16 100644 --- a/EIPS/eip-1967.md +++ b/EIPS/eip-1967.md @@ -1,468 +1,7 @@ --- eip: 1967 -title: Proxy Storage Slots -description: A consistent location where proxies store the address of the logic contract they delegate to, as well as other proxy-specific information. -author: Santiago Palladino (@spalladino), Francisco Giordano (@frangio), Hadrien Croubois (@Amxx) -discussions-to: https://ethereum-magicians.org/t/eip-1967-standard-proxy-storage-slots/3185 -status: Final -type: Standards Track category: ERC -created: 2019-04-24 +status: Moved --- -## Abstract -Delegating **proxy contracts** are widely used for both upgradeability and gas savings. These proxies rely on a **logic contract** (also known as implementation contract or master copy) that is called using `delegatecall`. This allows proxies to keep a persistent state (storage and balance) while the code is delegated to the logic contract. - -To avoid clashes in storage usage between the proxy and logic contract, the address of the logic contract is typically saved in a specific storage slot (for example `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` in OpenZeppelin contracts) guaranteed to be never allocated by a compiler. This EIP proposes a set of standard slots to store proxy information. This allows clients like block explorers to properly extract and show this information to end users, and logic contracts to optionally act upon it. - -## Motivation -Delegating proxies are widely in use, as a means to both support upgrades and reduce gas costs of deployments. Examples of these proxies are found in OpenZeppelin Contracts, Gnosis, AragonOS, Melonport, Limechain, WindingTree, Decentraland, and many others. - -However, the lack of a common interface for obtaining the logic address for a proxy makes it impossible to build common tools that act upon this information. - -A classic example of this is a block explorer. Here, the end user wants to interact with the underlying logic contract and not the proxy itself. Having a common way to retrieve the logic contract address from a proxy allows a block explorer to show the ABI of the logic contract and not that of the proxy. The explorer checks the storage of the contract at the distinguished slots to determine if it is indeed a proxy, in which case it shows information on both the proxy and the logic contract. As an example, this is how `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` is shown on Etherscan: - -![Sample proxy on Etherscan](../assets/eip-1967/Sample-proxy-on-etherscan.png) - -Another example is logic contracts that explicitly act upon the fact that they are being proxied. This allows them to potentially trigger a code update as part of their logic. A common storage slot allows these use cases independently of the specific proxy implementation being used. - -## Specification -Monitoring of proxies is essential to the security of many applications. It is thus essential to have the ability to track changes to the implementation and admin slots. Unfortunately, tracking changes to storage slots is not easy. Consequently, it is recommended that any function that changes any of these slots SHOULD also emit the corresponding event. This includes initialization, from `0x0` to the first non-zero value. - -The proposed storage slots for proxy-specific information are the following. More slots for additional information can be added in subsequent ERCs as needed. - -### Logic contract address - -Storage slot `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` -(obtained as `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`). - -Holds the address of the logic contract that this proxy delegates to. SHOULD be empty if a beacon is used instead. Changes to this slot SHOULD be notified by the event: - -```solidity -event Upgraded(address indexed implementation); -``` - -### Beacon contract address - -Storage slot `0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50` (obtained as `bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)`). - -Holds the address of the beacon contract this proxy relies on (fallback). SHOULD be empty if a logic address is used directly instead, and should only be considered if the logic contract slot is empty. Changes to this slot SHOULD be notified by the event: - -```solidity -event BeaconUpgraded(address indexed beacon); -``` - -Beacons are used for keeping the logic address for multiple proxies in a single location, allowing the upgrade of multiple proxies by modifying a single storage slot. A beacon contract MUST implement the function: - -``` -function implementation() returns (address) -``` - -Beacon based proxy contracts do not use the logic contract slot. Instead, they use the beacon contract slot to store the address of the beacon they are attached to. In order to know the logic contract used by a beacon proxy, a client SHOULD: - -- Read the address of the beacon for the beacon logic storage slot; -- Call the `implementation()` function on the beacon contract. - -The result of the `implementation()` function on the beacon contract SHOULD NOT depend on the caller (`msg.sender`). - - -### Admin address - -Storage slot `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` -(obtained as `bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)`). - -Holds the address that is allowed to upgrade the logic contract address for this proxy (optional). Changes to this slot SHOULD be notified by the event: - -```solidity -event AdminChanged(address previousAdmin, address newAdmin); -``` - -## Rationale - -This EIP standardises the **storage slot** for the logic contract address, instead of a public method on the proxy contract. The rationale for this is that proxies should never expose functions to end users that could potentially clash with those of the logic contract. - -Note that a clash may occur even among functions with different names, since the ABI relies on just four bytes for the function selector. This can lead to unexpected errors, or even exploits, where a call to a proxied contract returns a different value than expected, since the proxy intercepts the call and answers with a value of its own. - -From _Malicious backdoors in Ethereum proxies_ by Nomic Labs: - -> Any function in the Proxy contract whose selector matches with one in the implementation contract will be called directly, completely skipping the implementation code. -> -> Because the function selectors use a fixed amount of bytes, there will always be the possibility of a clash. This isn’t an issue for day to day development, given that the Solidity compiler will detect a selector clash within a contract, but this becomes exploitable when selectors are used for cross-contract interaction. Clashes can be abused to create a seemingly well-behaved contract that’s actually concealing a backdoor. - -The fact that proxy public functions are potentially exploitable makes it necessary to standardise the logic contract address in a different way. - -The main requirement for the storage slots chosen is that they must never be picked by the compiler to store any contract state variable. Otherwise, a logic contract could inadvertently overwrite this information on the proxy when writing to a variable of its own. - -Solidity maps variables to storage based on the order in which they were declared, after the contract inheritance chain is linearized: the first variable is assigned the first slot, and so on. The exception is values in dynamic arrays and mappings, which are stored in the hash of the concatenation of the key and the storage slot. The Solidity development team has confirmed that the storage layout is to be preserved among new versions: - -> The layout of state variables in storage is considered to be part of the external interface of Solidity due to the fact that storage pointers can be passed to libraries. This means that any change to the rules outlined in this section is considered a breaking change of the language and due to its critical nature should be considered very carefully before being executed. In the event of such a breaking change, we would want to release a compatibility mode in which the compiler would generate bytecode supporting the old layout. - -Vyper seems to follow the same strategy as Solidity. Note that contracts written in other languages, or directly in assembly, may incur in clashes. - -They are chosen in such a way so they are guaranteed to not clash with state variables allocated by the compiler, since they depend on the hash of a string that does not start with a storage index. Furthermore, a `-1` offset is added so the preimage of the hash cannot be known, further reducing the chances of a possible attack. - -## Reference Implementation - -```solidity -/** - * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an - * implementation address that can be changed. This address is stored in storage in the location specified by - * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the - * implementation behind the proxy. - */ -contract ERC1967Proxy is Proxy, ERC1967Upgrade { - /** - * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. - * - * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded - * function call, and allows initializing the storage of the proxy like a Solidity constructor. - */ - constructor(address _logic, bytes memory _data) payable { - assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); - _upgradeToAndCall(_logic, _data, false); - } - - /** - * @dev Returns the current implementation address. - */ - function _implementation() internal view virtual override returns (address impl) { - return ERC1967Upgrade._getImplementation(); - } -} - -/** - * @dev This abstract contract provides getters and event emitting update functions for - * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. - */ -abstract contract ERC1967Upgrade { - // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 - bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; - - /** - * @dev Storage slot with the address of the current implementation. - * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is - * validated in the constructor. - */ - bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - - /** - * @dev Emitted when the implementation is upgraded. - */ - event Upgraded(address indexed implementation); - - /** - * @dev Returns the current implementation address. - */ - function _getImplementation() internal view returns (address) { - return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; - } - - /** - * @dev Stores a new address in the EIP1967 implementation slot. - */ - function _setImplementation(address newImplementation) private { - require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); - StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; - } - - /** - * @dev Perform implementation upgrade - * - * Emits an {Upgraded} event. - */ - function _upgradeTo(address newImplementation) internal { - _setImplementation(newImplementation); - emit Upgraded(newImplementation); - } - - /** - * @dev Perform implementation upgrade with additional setup call. - * - * Emits an {Upgraded} event. - */ - function _upgradeToAndCall( - address newImplementation, - bytes memory data, - bool forceCall - ) internal { - _upgradeTo(newImplementation); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(newImplementation, data); - } - } - - /** - * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. - * - * Emits an {Upgraded} event. - */ - function _upgradeToAndCallSecure( - address newImplementation, - bytes memory data, - bool forceCall - ) internal { - address oldImplementation = _getImplementation(); - - // Initial upgrade and setup call - _setImplementation(newImplementation); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(newImplementation, data); - } - - // Perform rollback test if not already in progress - StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); - if (!rollbackTesting.value) { - // Trigger rollback using upgradeTo from the new implementation - rollbackTesting.value = true; - Address.functionDelegateCall( - newImplementation, - abi.encodeWithSignature("upgradeTo(address)", oldImplementation) - ); - rollbackTesting.value = false; - // Check rollback was effective - require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); - // Finally reset to the new implementation and log the upgrade - _upgradeTo(newImplementation); - } - } - - /** - * @dev Storage slot with the admin of the contract. - * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is - * validated in the constructor. - */ - bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; - - /** - * @dev Emitted when the admin account has changed. - */ - event AdminChanged(address previousAdmin, address newAdmin); - - /** - * @dev Returns the current admin. - */ - function _getAdmin() internal view returns (address) { - return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; - } - - /** - * @dev Stores a new address in the EIP1967 admin slot. - */ - function _setAdmin(address newAdmin) private { - require(newAdmin != address(0), "ERC1967: new admin is the zero address"); - StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; - } - - /** - * @dev Changes the admin of the proxy. - * - * Emits an {AdminChanged} event. - */ - function _changeAdmin(address newAdmin) internal { - emit AdminChanged(_getAdmin(), newAdmin); - _setAdmin(newAdmin); - } - - /** - * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. - * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. - */ - bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; - - /** - * @dev Emitted when the beacon is upgraded. - */ - event BeaconUpgraded(address indexed beacon); - - /** - * @dev Returns the current beacon. - */ - function _getBeacon() internal view returns (address) { - return StorageSlot.getAddressSlot(_BEACON_SLOT).value; - } - - /** - * @dev Stores a new beacon in the EIP1967 beacon slot. - */ - function _setBeacon(address newBeacon) private { - require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); - require( - Address.isContract(IBeacon(newBeacon).implementation()), - "ERC1967: beacon implementation is not a contract" - ); - StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; - } - - /** - * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does - * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). - * - * Emits a {BeaconUpgraded} event. - */ - function _upgradeBeaconToAndCall( - address newBeacon, - bytes memory data, - bool forceCall - ) internal { - _setBeacon(newBeacon); - emit BeaconUpgraded(newBeacon); - if (data.length > 0 || forceCall) { - Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); - } - } -} - -/** - * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM - * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to - * be specified by overriding the virtual {_implementation} function. - * - * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a - * different contract through the {_delegate} function. - * - * The success and return data of the delegated call will be returned back to the caller of the proxy. - */ -abstract contract Proxy { - /** - * @dev Delegates the current call to `implementation`. - * - * This function does not return to its internal call site, it will return directly to the external caller. - */ - function _delegate(address implementation) internal virtual { - assembly { - // Copy msg.data. We take full control of memory in this inline assembly - // block because it will not return to Solidity code. We overwrite the - // Solidity scratch pad at memory position 0. - calldatacopy(0, 0, calldatasize()) - - // Call the implementation. - // out and outsize are 0 because we don't know the size yet. - let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) - - // Copy the returned data. - returndatacopy(0, 0, returndatasize()) - - switch result - // delegatecall returns 0 on error. - case 0 { - revert(0, returndatasize()) - } - default { - return(0, returndatasize()) - } - } - } - - /** - * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function - * and {_fallback} should delegate. - */ - function _implementation() internal view virtual returns (address); - - /** - * @dev Delegates the current call to the address returned by `_implementation()`. - * - * This function does not return to its internal call site, it will return directly to the external caller. - */ - function _fallback() internal virtual { - _beforeFallback(); - _delegate(_implementation()); - } - - /** - * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other - * function in the contract matches the call data. - */ - fallback() external payable virtual { - _fallback(); - } - - /** - * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data - * is empty. - */ - receive() external payable virtual { - _fallback(); - } - - /** - * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` - * call, or as part of the Solidity `fallback` or `receive` functions. - * - * If overridden should call `super._beforeFallback()`. - */ - function _beforeFallback() internal virtual {} -} - -/** - * @dev Library for reading and writing primitive types to specific storage slots. - * - * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. - * This library helps with reading and writing to such slots without the need for inline assembly. - * - * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. - */ -library StorageSlot { - struct AddressSlot { - address value; - } - - struct BooleanSlot { - bool value; - } - - struct Bytes32Slot { - bytes32 value; - } - - struct Uint256Slot { - uint256 value; - } - - /** - * @dev Returns an `AddressSlot` with member `value` located at `slot`. - */ - function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `BooleanSlot` with member `value` located at `slot`. - */ - function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. - */ - function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { - assembly { - r.slot := slot - } - } - - /** - * @dev Returns an `Uint256Slot` with member `value` located at `slot`. - */ - function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { - assembly { - r.slot := slot - } - } -} -``` - -## Security Considerations - -This ERC relies on the fact that the chosen storage slots are **not** to be allocated by the solidity compiler. This guarantees that an implementation contract will not accidentally overwrite any of the information required for the proxy to operate. As such, locations with a high slot number were chosen to avoid clashes with the slots allocated by the compiler. Also, locations with no known preimage were picked, to ensure that a write to mapping with a maliciously crafted key could not overwrite it. - -Logic contracts that intend to modify proxy-specific information must do so deliberately (as is the case with UUPS) by writing to the specific storage slot. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1967.md diff --git a/EIPS/eip-1973.md b/EIPS/eip-1973.md index d3c94b9bf0850b..8ee3f7066323e4 100644 --- a/EIPS/eip-1973.md +++ b/EIPS/eip-1973.md @@ -1,270 +1,7 @@ --- eip: 1973 -title: Scalable Rewards -author: Lee Raj (@lerajk), Qin Jian (@qinjian) -type: Standards Track category: ERC -status: Stagnant -created: 2019-04-01 +status: Moved --- -## Simple Summary - - A mintable token rewards interface that mints 'n' tokens per block which are distributed equally among the 'm' participants in the DAPP's ecosystem. - -## Abstract - - The mintable token rewards interface allows DApps to build a token economy where token rewards are distributed equally among the active participants. The tokens are minted based on per block basis that are configurable (E.g. 10.2356 tokens per block, 0.1 token per block, 1350 tokens per block) and the mint function can be initiated by any active participant. The token rewards distributed to each participant is dependent on the number of participants in the network. At the beginning, when the network has low volume, the tokens rewards per participant is high but as the network scales the token rewards decreases dynamically. - - - ## Motivation - -Distributing tokens through a push system to a large amount of participants fails due to block gas limit. As the number of participants in the network grow to tens of thousands, keeping track of the iterable registry of participants and their corresponding rewards in a push system becomes unmanagable. E.g. Looping through 5000 addresses to distribute 0.0000001 reward tokens is highly inefficient. Furthermore, the gas fees in these transactions are high and needs to be undertaken by the DApp developer or the respective company, leading to centralization concerns. - -A pull system is required to keep the application completely decentralized and to avoid the block gas limit problem. However, no standard solution has been proposed to distribute scalable rewards to tens of thousands participants with a pull system. This is what we propose with this EIP through concepts like TPP, round mask, participant mask. - -## Specification - -### Definitions - - `token amount per participant in the ecosytem or TPP (token per participant)`: TPP = (token amount to mint / total active participants) - - `roundMask`: the cumulative snapshot of TPP over time for the token contract. E.g. transactionOne = 10 tokens are minted with 100 available participants (TPP = 10 / 100) , transactionTwo = 12 tokens are minted with 95 participants (TPP = 12 / 95 ) - - roundMask = (10/100) + (12/95) - - `participantMask`: is used to keep track of a `msg.sender` (participant) rewards over time. When a `msg.sender` joins or leaves the ecosystem, the player mask is updated - - participantMask = previous roundMask OR (current roundMask - TPP) - - `rewards for msg.sender`: roundMask - participantMask - - E.g. Let's assume a total of 6 transactions (smart contract triggers or functions calls) are in place with 10 existing participants (denominator) and 20 tokens (numerator) are minted per transaction. At 2nd transaction, the 11th participant joins the network and exits before 5th transaction, the 11th participant's balance is as follows: - - ``` - t1 roundMask = (20/10) - t2 roundMask = (20/10) + (20/11) - t3 roundMask = (20/10) + (20/11) + (20/11) - t4 roundMask = (20/10) + (20/11) + (20/11) + (20/11) - t5 roundMask = (20/10) + (20/11) + (20/11) + (20/11)+ (20/10) - t6 roundMask = (20/10) + (20/11) + (20/11) + (20/11)+ (20/10) + (20/10) - ``` - - Total tokens released in 6 transactions = 60 tokens - - As the participant joins at t2 and leaves before t5, the participant deserves the rewards between t2 and t4. When the participant joins at t2, the 'participantMask = (20/10)', when the participant leaves before t5, the cumulative deserved reward tokens are : - - rewards for msg.sender: `[t4 roundMask = (20/10) + (20/11)+ (20/11) + (20/11)] - [participantMask = (20/10)] = [rewards = (20/11)+ (20/11) + (20/11)]` - - When the same participant joins the ecosystem at a later point (t27 or t35), a new 'participantMask' is given that is used to calculate the new deserved reward tokens when the participant exits. This process continues dynamically for each participant. - - `tokensPerBlock`: the amount of tokens that will be released per block - - `blockFreezeInterval`: the number of blocks that need to pass until the next mint. E.g. if set to 50 and 'n' tokens were minted at block 'b', the next 'n' tokens won't be minted until 'b + 50' blocks have passed - - `lastMintedBlockNumber`: the block number on which last 'n' tokens were minted - - `totalParticipants` : the total number of participants in the DApp network - - `tokencontractAddress` : the contract address to which tokens will be minted, default is address(this) - -```solidity - -pragma solidity ^0.5.2; - -import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol"; -import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; - -contract Rewards is ERC20Mintable, ERC20Detailed { - -using SafeMath for uint256; - -uint256 public roundMask; -uint256 public lastMintedBlockNumber; -uint256 public totalParticipants = 0; -uint256 public tokensPerBlock; -uint256 public blockFreezeInterval; -address public tokencontractAddress = address(this); -mapping(address => uint256) public participantMask; - -/** - * @dev constructor, initializes variables. - * @param _tokensPerBlock The amount of token that will be released per block, entered in wei format (E.g. 1000000000000000000) - * @param _blockFreezeInterval The amount of blocks that need to pass (E.g. 1, 10, 100) before more tokens are brought into the ecosystem. - */ - constructor(uint256 _tokensPerBlock, uint256 _blockFreezeInterval) public ERC20Detailed("Simple Token", "SIM", 18){ -lastMintedBlockNumber = block.number; -tokensPerBlock = _tokensPerBlock; -blockFreezeInterval = _blockFreezeInterval; -} - -/** - * @dev Modifier to check if msg.sender is whitelisted as a minter. - */ -modifier isAuthorized() { -require(isMinter(msg.sender)); -_; -} - -/** - * @dev Function to add participants in the network. - * @param _minter The address that will be able to mint tokens. - * @return A boolean that indicates if the operation was successful. - */ -function addMinters(address _minter) external returns (bool) { -_addMinter(_minter); -totalParticipants = totalParticipants.add(1); -updateParticipantMask(_minter); -return true; -} - - -/** - * @dev Function to remove participants in the network. - * @param _minter The address that will be unable to mint tokens. - * @return A boolean that indicates if the operation was successful. - */ -function removeMinters(address _minter) external returns (bool) { -totalParticipants = totalParticipants.sub(1); -_removeMinter(_minter); -return true; -} - - -/** - * @dev Function to introduce new tokens in the network. - * @return A boolean that indicates if the operation was successful. - */ -function trigger() external isAuthorized returns (bool) { -bool res = readyToMint(); -if(res == false) { -return false; -} else { -mintTokens(); -return true; -} -} - -/** - * @dev Function to withdraw rewarded tokens by a participant. - * @return A boolean that indicates if the operation was successful. - */ -function withdraw() external isAuthorized returns (bool) { -uint256 amount = calculateRewards(); -require(amount >0); -ERC20(tokencontractAddress).transfer(msg.sender, amount); -} - -/** - * @dev Function to check if new tokens are ready to be minted. - * @return A boolean that indicates if the operation was successful. - */ -function readyToMint() public view returns (bool) { -uint256 currentBlockNumber = block.number; -uint256 lastBlockNumber = lastMintedBlockNumber; -if(currentBlockNumber > lastBlockNumber + blockFreezeInterval) { -return true; -} else { -return false; -} -} - -/** - * @dev Function to calculate current rewards for a participant. - * @return A uint that returns the calculated rewards amount. - */ -function calculateRewards() private returns (uint256) { -uint256 playerMask = participantMask[msg.sender]; -uint256 rewards = roundMask.sub(playerMask); -updateParticipantMask(msg.sender); -return rewards; -} - -/** - * @dev Function to mint new tokens into the economy. - * @return A boolean that indicates if the operation was successful. - */ -function mintTokens() private returns (bool) { -uint256 currentBlockNumber = block.number; -uint256 tokenReleaseAmount = (currentBlockNumber.sub(lastMintedBlockNumber)).mul(tokensPerBlock); -lastMintedBlockNumber = currentBlockNumber; -mint(tokencontractAddress, tokenReleaseAmount); -calculateTPP(tokenReleaseAmount); -return true; -} - - /** -* @dev Function to calculate TPP (token amount per participant). -* @return A boolean that indicates if the operation was successful. -*/ -function calculateTPP(uint256 tokens) private returns (bool) { -uint256 tpp = tokens.div(totalParticipants); -updateRoundMask(tpp); -return true; -} - - /** -* @dev Function to update round mask. -* @return A boolean that indicates if the operation was successful. -*/ -function updateRoundMask(uint256 tpp) private returns (bool) { -roundMask = roundMask.add(tpp); -return true; -} - - /** -* @dev Function to update participant mask (store the previous round mask) -* @return A boolean that indicates if the operation was successful. -*/ -function updateParticipantMask(address participant) private returns (bool) { -uint256 previousRoundMask = roundMask; -participantMask[participant] = previousRoundMask; -return true; -} - -} -``` - -## Rationale - -Currently, there is no standard for a scalable reward distribution mechanism. In order to create a sustainable cryptoeconomic environment within DAPPs, incentives play a large role. However, without a scalable way to distribute rewards to tens of thousands of participants, most DAPPs lack a good incentive structure. The ones with a sustainable cryptoeconomic environment depend heavily on centralized servers or a group of selective nodes to trigger the smart contracts. But, in order to keep an application truly decentralized, the reward distribution mechanism must depend on the active participants itself and scale as the number of participants grow. This is what this EIP intends to accomplish. - -## Backwards Compatibility - -Not Applicable. - -## Test Cases - -WIP, will be added. - -## Implementation - -WIP, a proper implementation will be added later.A sample example is below: - -`etherscan rewards contract` : https://ropsten.etherscan.io/address/0x8b0abfc541ab7558857816a67e186221adf887bc#tokentxns - -`Step 1` : deploy Rewards contract with the following parameters_tokensPerBlock = 1e18, _blockFreezeInterval = 1 - -`Step 2` : add Alice(0x123) and Bob(0x456) as minters, addMinters(address _minter) - -`Step 3` : call trigger() from Alice / Bob's account. 65 blocks are passed, hence 65 SIM tokens are minted. The RM is 32500000000000000000 - -`Step 4` : Alice withdraws and receives 32.5 SIM tokens (65 tokens / 2 participants) and her PM = 32500000000000000000 - -`Step 5` : add Satoshi(0x321) and Vitalik(0x654) as minters, addMinters(address _minter) - -`Step 6` : call trigger() from Alice / Bob's / Satoshi / Vitalik account. 101 blocks are passed, hence 101 SIM tokens are minted. The RM is 57750000000000000000 - -`Step 7` : Alice withdraws and receives 25.25 SIM tokens (101 tokens / 4 participants) and her PM = 57750000000000000000 - -`Step 8` : Bob withdraws and receives 57.75 SIM tokens ((65 tokens / 2 participants) + (101 tokens / 4 participants)). Bob's PM = 57750000000000000000 - -## Copyright - -Copyright and related rights waived via CC0. - -## References - -1. Scalable Reward Distribution on the Ethereum Blockchain by Bogdan Batog, Lucian Boca and Nick Johnson - -2. Fomo3d DApp, https://fomo3d.hostedwiki.co/ +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1973.md diff --git a/EIPS/eip-1996.md b/EIPS/eip-1996.md index fffb24a77cb62c..3305a10c98c649 100644 --- a/EIPS/eip-1996.md +++ b/EIPS/eip-1996.md @@ -1,294 +1,7 @@ --- eip: 1996 -title: Holdable Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2103 -status: Stagnant -type: Standards Track category: ERC -created: 2019-04-10 -requires: 20 +status: Moved --- -## Simple Summary -An extension to the ERC-20 standard token that allows tokens to be put on hold. This guarantees a future transfer and makes the held tokens unavailable for transfer in the mean time. Holds are similar to escrows in that are firm and lead to final settlement. - -## Actors - -#### Operator -An account which has been approved by an account to create holds on its behalf. - -#### Hold issuer -The account, which creates a hold. This can be the account owner itself, or any account, which has been approved as an operator for the account. - -#### Notary -The account which decides if a hold should be executed. - -## Abstract -A hold specifies a payer, a payee, a maximum amount, a notary and an expiration time. When the hold is created, the specified token balance from the payer is put on hold. A held balance cannot be transferred until the hold is either executed or released. The hold can only be executed by the notary, which triggers the transfer of the tokens from the payer to the payee. If a hold is released, either by the notary at any time, or by anyone after the expiration, no transfer is carried out and the amount is available again for the payer. - -A hold can be partially executed, if the execution specifies an amount less than the maximum amount. In this case the specified amount is transferred to the payee and the remaining amount is available again to the payer. - -Holds can be specified to be perpetual. In this case, the hold cannot be released upon expiration, and thus can only be executed by the notary or released by the notary or payee. - -## Motivation - -A hold has to be used in different scenarios where a immediate transfer between accounts is not possible or has to be guaranteed beforehand: - -1. A regulated token may not allow to do a token transfer between accounts without verifying first, that it follows all the regulations. In this case a clearable transfer has to be used. During the clearing process a hold is created to ensure, that the transfer is successful after all checks have passed. If the transfer violates any of the regulations, it is cleared and not further processed. - -1. In certain business situations a payment has to be guaranteed before its services can be used. For example: When checking in a hotel, the hotel will put a hold on the guest's account to ensure that enough balance is available to pay for the room before handing over the keys. - -1. In other occasions a payment has to be guaranteed without knowing the exact amount beforehand. To stay with the hotel example: The hotel can put a hold on the guest's account as a guarantee for any possible extras, like room service. When the guest checks out the hold is partially executed and the remaining amount is available again on the guest's account. - -The ERC-20 `approve` function provides some of the necessary functionality for the use cases above. The main difference to holds, is that `approve` does not ensure a payment, as the approved money is not blocked and can be transferred at any moment. - -## Specification - -```solidity -interface IHoldable /* is ERC-20 */ { - enum HoldStatusCode { - Nonexistent, - Ordered, - Executed, - ReleasedByNotary, - ReleasedByPayee, - ReleasedOnExpiration - } - - function hold(string calldata operationId, address to, address notary, uint256 value, uint256 timeToExpiration) external returns (bool); - function holdFrom(string calldata operationId, address from, address to, address notary, uint256 value, uint256 timeToExpiration) external returns (bool); - function releaseHold(string calldata operationId) external returns (bool); - function executeHold(string calldata operationId, uint256 value) external returns (bool); - function renewHold(string calldata operationId, uint256 timeToExpiration) external returns (bool); - function retrieveHoldData(string calldata operationId) external view returns (address from, address to, address notary, uint256 value, uint256 expiration, HoldStatusCode status); - - function balanceOnHold(address account) external view returns (uint256); - function netBalanceOf(address account) external view returns (uint256); - function totalSupplyOnHold() external view returns (uint256); - - function authorizeHoldOperator(address operator) external returns (bool); - function revokeHoldOperator(address operator) external returns (bool); - function isHoldOperatorFor(address operator, address from) external view returns (bool); - - event HoldCreated(address indexed holdIssuer, string operationId, address from, address to, address indexed notary, uint256 value, uint256 expiration); - event HoldExecuted(address indexed holdIssuer, string operationId, address indexed notary, uint256 heldValue, uint256 transferredValue); - event HoldReleased(address indexed holdIssuer, string operationId, HoldStatusCode status); - event HoldRenewed(address indexed holdIssuer, string operationId, uint256 oldExpiration, uint256 newExpiration); - event AuthorizedHoldOperator(address indexed operator, address indexed account); - event RevokedHoldOperator(address indexed operator, address indexed account); -} -``` - -### Functions - -#### hold - -Creates a hold on behalf of the msg.sender in favor of the payee. It specifies a notary who is responsible to either execute or release the hold. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| timeToExpiration | The duration until the hold is expired. If it is '0' the hold must be perpetual. | - -#### holdFrom - -Creates a hold on behalf of the payer in favor of the payee. The `from` account has to approve beforehand, that another account can issue holds on its behalf by calling `approveToHold`. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| timeToExpiration | The duration until the hold is expired. If it is '0' the hold must be perpetual. | - -#### releaseHold - -Releases a hold. Release means that the transfer is not executed and the held amount is available again for the payer. Until a hold has expired it can only be released by the notary or the payee. After it has expired it can be released by anyone. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | - -#### executeHold - -Executes a hold. Execute means that the specified value is transferred from the payer to the payee. If the specified value is less than the hold value the remaining amount is available again to the payer. The implementation must verify that only the notary is able to successfully call the function. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| value | The amount to be transferred. This amount has to be less or equal than the hold value | - -#### renewHold - -Renews a hold. The new expiration time must be the block timestamp plus the given `timeToExpiration`, independently if the hold was perpetual or not before that. Furthermore a hold must be made perpetual if `timeToExpiration` is '0'. The implementation must verify that only the payer or operator are able to successfully call the function. Furthermore the only a hold, which has not yet expired can be successfully renewed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | -| timeToExpiration | The new duration until the hold is expired. | - -#### retrieveHoldData - -Retrieves all the information available for a particular hold. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the hold | - -#### balanceOnHold - -Retrieves how much of the balance is currently held and therefore not available for transfer. - -| Parameter | Description | -| ---------|-------------| -| account | The address which held balance should be returned | - -#### netBalanceOf - -Retrieves the net balance, which is the sum of `balanceOf` and `balanceOnHold`. - -| Parameter | Description | -| ---------|-------------| -| account | The address which net balance should be returned | - -#### totalSupplyOnHold - -Retrieves the total sum of how many tokens are on hold. - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### authorizeHoldOperator - -Approves an operator to issue holds on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of holds | - -#### revokeHoldOperator - -Revokes the approval to issue holds on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of holds | - -#### isHoldOperatorFor - -Retrieves if an operator is approved to create holds on behalf of `from`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| from | The address on which the holds would be created | - -#### balanceOf - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. - -#### transfer - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. Any amount that is held must not be transferred. - -#### transferFrom - -The standard implementation of ERC-20 has to be changed in order to deduct the held balance from the ERC-20 balance. Any amount that is held must not be transferred. - -### Events - -#### HoldCreated - -Emitted when a hold has been created. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | -| expiration | The unix timestamp when the hold is expired | - -#### HoldExecuted - -Emitted when a hold has been executed. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| notary | The address of the notary who executed the hold | -| heldValue | The amount which was put on hold during creation | -| transferredValue | The amount which was used for the transfer | - -#### HoldReleased - -Emitted when a hold has been released. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| status | Can be one of the following values: `ReleasedByNotary`, `ReleasedByPayee`, `ReleasedOnExpiration` | - -#### HoldRenewed - -Emitted when a hold has been renewed. - -| Parameter | Description | -| ---------|-------------| -| holdIssuer | The address of the hold issuer of the hold | -| operationId | The unique ID to identify the hold | -| oldExpiration | The expiration time before the renewal | -| newExpiration | The expiration time after the renewal | - -#### AuthorizedHoldOperator - -Emitted when an operator has been approved to create holds on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| account | Address on which behalf holds will potentially be created | - -#### RevokedHoldOperator - -Emitted when an operator has been revoked from creating holds on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be a operator of holds | -| account | Address on which behalf holds could potentially be created | - -## Rationale - -This standards provides a functionality, to guarantee future payments, which is needed for many business cases where transfers have to be guaranteed. - -It goes a step further than the ERC-20 `approve` function by ensuring that the held balance will be available when the transfer is done. Something that can not be done with `approve`, as the approved amount is only a maximum spending amount, but never guaranteed to be available. - -While not requiring it, the naming of the functions `authorizeHoldOperator`, `revokeHoldOperator` and `isHoldOperatorFor` follows the naming convention of [ERC-777](./eip-777.md). - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but nor required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of ERC-20. - -## Implementation -The GitHub repository [IoBuilders/holdable-token](https://github.com/IoBuilders/holdable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-1996.md diff --git a/EIPS/eip-20.md b/EIPS/eip-20.md index 98600bad836171..3f36b8ed23d8d4 100644 --- a/EIPS/eip-20.md +++ b/EIPS/eip-20.md @@ -1,193 +1,7 @@ --- eip: 20 -title: Token Standard -author: Fabian Vogelsteller , Vitalik Buterin -type: Standards Track category: ERC -status: Final -created: 2015-11-19 +status: Moved --- -## Simple Summary - -A standard interface for tokens. - - -## Abstract - -The following standard allows for the implementation of a standard API for tokens within smart contracts. -This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party. - - -## Motivation - -A standard interface allows any tokens on Ethereum to be re-used by other applications: from wallets to decentralized exchanges. - - -## Specification - -## Token -### Methods - -**NOTES**: - - The following specifications use syntax from Solidity `0.4.17` (or above) - - Callers MUST handle `false` from `returns (bool success)`. Callers MUST NOT assume that `false` is never returned! - - -#### name - -Returns the name of the token - e.g. `"MyToken"`. - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - - -``` js -function name() public view returns (string) -``` - - -#### symbol - -Returns the symbol of the token. E.g. "HIX". - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - -``` js -function symbol() public view returns (string) -``` - - - -#### decimals - -Returns the number of decimals the token uses - e.g. `8`, means to divide the token amount by `100000000` to get its user representation. - -OPTIONAL - This method can be used to improve usability, -but interfaces and other contracts MUST NOT expect these values to be present. - -``` js -function decimals() public view returns (uint8) -``` - - -#### totalSupply - -Returns the total token supply. - -``` js -function totalSupply() public view returns (uint256) -``` - - - -#### balanceOf - -Returns the account balance of another account with address `_owner`. - -``` js -function balanceOf(address _owner) public view returns (uint256 balance) -``` - - - -#### transfer - -Transfers `_value` amount of tokens to address `_to`, and MUST fire the `Transfer` event. -The function SHOULD `throw` if the message caller's account balance does not have enough tokens to spend. - -*Note* Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event. - -``` js -function transfer(address _to, uint256 _value) public returns (bool success) -``` - - - -#### transferFrom - -Transfers `_value` amount of tokens from address `_from` to address `_to`, and MUST fire the `Transfer` event. - -The `transferFrom` method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. -This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. -The function SHOULD `throw` unless the `_from` account has deliberately authorized the sender of the message via some mechanism. - -*Note* Transfers of 0 values MUST be treated as normal transfers and fire the `Transfer` event. - -``` js -function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) -``` - - - -#### approve - -Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount. If this function is called again it overwrites the current allowance with `_value`. - -**NOTE**: To prevent attack vectors like the one [described here](https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/) and discussed [here](https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729), -clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to `0` before setting it to another value for the same spender. -THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before - -``` js -function approve(address _spender, uint256 _value) public returns (bool success) -``` - - -#### allowance - -Returns the amount which `_spender` is still allowed to withdraw from `_owner`. - -``` js -function allowance(address _owner, address _spender) public view returns (uint256 remaining) -``` - - - -### Events - - -#### Transfer - -MUST trigger when tokens are transferred, including zero value transfers. - -A token contract which creates new tokens SHOULD trigger a Transfer event with the `_from` address set to `0x0` when tokens are created. - -``` js -event Transfer(address indexed _from, address indexed _to, uint256 _value) -``` - - - -#### Approval - -MUST trigger on any successful call to `approve(address _spender, uint256 _value)`. - -``` js -event Approval(address indexed _owner, address indexed _spender, uint256 _value) -``` - - - -## Implementation - -There are already plenty of ERC20-compliant tokens deployed on the Ethereum network. -Different implementations have been written by various teams that have different trade-offs: from gas saving to improved security. - -#### Example implementations are available at -- [OpenZeppelin implementation](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/9b3710465583284b8c4c5d2245749246bb2e0094/contracts/token/ERC20/ERC20.sol) -- [ConsenSys implementation](https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol) - - -## History - -Historical links related to this standard: - -- Original proposal from Vitalik Buterin: https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs/499c882f3ec123537fc2fccd57eaa29e6032fe4a -- Reddit discussion: https://www.reddit.com/r/ethereum/comments/3n8fkn/lets_talk_about_the_coin_standard/ -- Original Issue #20: https://github.com/ethereum/EIPs/issues/20 - - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-20.md diff --git a/EIPS/eip-2009.md b/EIPS/eip-2009.md index c628e6b2343e06..8fe47e1a42df3d 100644 --- a/EIPS/eip-2009.md +++ b/EIPS/eip-2009.md @@ -1,300 +1,7 @@ --- eip: 2009 -title: Compliance Service -author: Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2022 -status: Stagnant -type: Standards Track category: ERC -created: 2019-05-09 -requires: 1066 +status: Moved --- -## Simple Summary - -This EIP proposes a service for decentralized compliance checks for regulated tokens. - -## Actors - -#### Operator -An account which has been approved by a token to update the tokens accumulated. - -#### Token -An account, normally a smart contract, which uses the `Compliance Service` to check if the an action can be executed or not. - -#### Token holder -An account which is in possession of tokens and on for which the checks are made. - -## Abstract - -A regulated token needs to comply with several legal requirements, especially [KYC][KYC-Wikipedia] and [AML][AML-Wikipedia]. If the necessary checks have to be made off-chain the token transfer becomes centralized. Further the transfer in this case takes longer to complete as it can not be done in one transaction, but requires a second confirmation step. The goal of this proposal is to make this second step unnecessary by providing a service for compliance checks. - -## Motivation - -Currently there is no proposal on how to accomplish decentralized compliance checks. [ERC-1462][ERC-1462] proposes a basic set of functions to check if `transfer`, `mint` and `burn` are allowed for a user, but not how those checks should be implemented. This EIP proposes a way to implement them fully on-chain while being generic enough to leave the actual implementation of the checks up to the implementers, as these may vary a lot between different tokens. - -The proposed `Compliance Service` supports more than one token. Therefore it could be used by law-makers to maintain the compliance rules of regulated tokens in one smart contract. This smart contract could be used by all of the tokens that fall under this jurisdiction and ensure compliance with the current laws. - -By having a standard for compliance checks third-party developers can use them to verify if token movements for a specific account are allowed and act accordingly. - -## Specification - -```solidity -interface CompliantService { - function checkTransferAllowed(bytes32 tokenId, address from, address to, uint256 value) external view returns (byte); - function checkTransferFromAllowed(bytes32 tokenId, address sender, address from, address to, uint256 value) external view returns (byte); - function checkMintAllowed(bytes32 tokenId, address to, uint256 value) external view returns (byte); - function checkBurnAllowed(bytes32 tokenId, address from, uint256 value) external view returns (byte); - - function updateTransferAccumulated(bytes32 tokenId, address from, address to, uint256 value) external; - function updateMintAccumulated(bytes32 tokenId, address to, uint256 value) external; - function updateBurnAccumulated(bytes32 tokenId, address from, uint256 value) external; - - function addToken(bytes32 tokenId, address token) external; - function replaceToken(bytes32 tokenId, address token) external; - function removeToken(bytes32 tokenId) external; - function isToken(address token) external view returns (bool); - function getTokenId(address token) external view returns (bytes32); - - function authorizeAccumulatedOperator(address operator) external returns (bool); - function revokeAccumulatedOperator(address operator) external returns (bool); - function isAccumulatedOperatorFor(address operator, bytes32 tokenId) external view returns (bool); - - event TokenAdded(bytes32 indexed tokenId, address indexed token); - event TokenReplaced(bytes32 indexed tokenId, address indexed previousAddress, address indexed newAddress); - event TokenRemoved(bytes32 indexed tokenId); - event AuthorizedAccumulatedOperator(address indexed operator, bytes32 indexed tokenId); - event RevokedAccumulatedOperator(address indexed operator, bytes32 indexed tokenId); -} -``` - -### Mandatory checks - -The checks must be verified in their corresponding actions. The action must only be successful if the check return an `Allowed` status code. In any other case the functions must revert. - -### Status codes - -If an action is allowed `0x11` (Allowed) or an issuer-specific code with equivalent but more precise meaning must be returned. If the action is not allowed the status must be `0x10` (Disallowed) or an issuer-specific code with equivalent but more precise meaning. - -### Functions - -#### checkTransferAllowed - -Checks if the `transfer` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkTransferFromAllowed - -Checks if the `transferFrom` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| sender | The address of the sender, who initiated the transaction | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkMintAllowed - -Checks if the `mint` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| to | The address of the payee, to whom the tokens are to be given if executed | -| value | The amount to be minted | - -#### checkBurnAllowed - -Checks if the `burn` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| value | The amount to be burned | - -#### updateTransferAccumulated - -Must be called in the same transaction as `transfer` or `transferFrom`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### updateMintAccumulated - -Must be called in the same transaction as `mint`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| to | The address of the payee, to whom the tokens are to be given if executed | -| value | The amount to be minted | - -#### updateBurnAccumulated - -Must be called in the same transaction as `burn`. It must revert if the update violates any of the compliance rules. It is up to the implementer which specific logic is executed in the function. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| value | The amount to be minted | - -#### addToken - -Adds a token to the service, which allows the token to call the functions to update the accumulated. If an existing token id is used the function must revert. It is up to the implementer if adding a token should be restricted or not. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### replaceToken - -Replaces the address of a added token with another one. It is up to the implementer if replacing a token should be restricted or not, but a token should be able to replace its own address. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### removeToken - -Removes a token from the service, which disallows the token to call the functions to update the accumulated. It is up to the implementer if removing a token should be restricted or not. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | - -#### isToken - -Returns `true` if the address has been added to the service, `false` if not. - -| Parameter | Description | -| ---------|-------------| -| token | The address which should be checked | - -#### getTokenId - -Returns the token id of a token. If the token has not been added to the service, '0' must be returned. - -| Parameter | Description | -| ---------|-------------| -| token | The address which token id should be returned | - -#### authorizeAccumulatedOperator - -Approves an operator to update accumulated on behalf of the token id of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of accumulated updates | - -#### revokeAccumulatedOperator - -Revokes the approval to update accumulated on behalf the token id the token id ofof msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of accumulated updates | - -#### isAccumulatedOperatorFor - -Retrieves if an operator is approved to create holds on behalf of `tokenId`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which is operator of updating the accumulated | -| tokenId | The unique ID which identifies a token | - -### Events - -#### TokenAdded - -Must be emitted after a token has been added. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| token | The address from which the update functions will be called | - -#### TokenReplaced - -Must be emitted after the address of a token has been replaced. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | -| previousAddress | The previous address which was used before | -| newAddress | The address which will be used from now on | - -#### TokenRemoved - -Must be emitted after the a token has been removed. - -| Parameter | Description | -| ---------|-------------| -| tokenId | The unique ID which identifies a token | - -#### AuthorizedAccumulatedOperator - -Emitted when an operator has been approved to update the accumulated on behalf of a token. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which is operator of updating the accumulated | -| tokenId | Token id on which behalf updates of the accumulated will potentially be made | - -#### RevokedHoldOperator - -Emitted when an operator has been revoked from updating the accumulated on behalf of a token. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which was operator of updating the accumulated | -| tokenId | Token id on which behalf updates of the accumulated could be made | - -## Rationale - -The usage of a token id instead of the address has been chosen to give tokens the possibility to update their smart contracts and keeping all their associated accumulated. If the address would be used, a migration process would needed to be done after a smart contract update. - -No event is emitted after updating the accumulated as those are always associated with a `transfer`, `mint` or `burn` of a token which already emits an event of itself. - -While not requiring it, the naming of the functions `checkTransferAllowed`, `checkTransferFromAllowed`, `checkMintAllowed` and `checkBurnAllowed` was adopted from [ERC-1462][ERC-1462]. - -While not requiring it, the naming of the functions `authorizeAccumulatedOperator`, `revokeAccumulatedOperator` and `isAccumulatedOperatorFor` follows the naming convention of [ERC-777][ERC-777]. - -Localization is not part of this EIP, but [ERC-1066][ERC-1066] and [ERC-1444][ERC-1444] can be used together to achieve it. - -## Backwards Compatibility - -As the EIP is not using any existing EIP there are no backwards compatibilities to take into consideration. - -## Implementation - -The GitHub repository [IoBuilders/compliance-service](https://github.com/IoBuilders/compliance-service) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[KYC-Wikipedia]: https://en.wikipedia.org/wiki/Know_your_customer -[AML-Wikipedia]: https://en.wikipedia.org/wiki/Money_laundering#Anti-money_laundering -[ERC-777]: ./eip-777.md -[ERC-1066]: ./eip-1066.md -[ERC-1444]: ./eip-1444.md -[ERC-1462]: ./eip-1462.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2009.md diff --git a/EIPS/eip-2015.md b/EIPS/eip-2015.md index 7bb624830fbbe7..d5b4d3aaecb308 100644 --- a/EIPS/eip-2015.md +++ b/EIPS/eip-2015.md @@ -1,108 +1,74 @@ --- eip: 2015 -title: Wallet Update Ethereum Chain RPC Method (`wallet_updateEthereumChain`) -author: Pedro Gomes (@pedrouid), Erik Marks (@rekmarks) +title: wallet_updateEthereumChain RPC Method +description: Adds an RPC method to switch between EVM-compatible chains +author: Pedro Gomes (@pedrouid), Erik Marks (@rekmarks), Pandapip1 (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-2015-wallet-update-chain-json-rpc-method-wallet-updatechain/3274 status: Stagnant type: Standards Track category: Interface created: 2019-05-12 -requires: 155, 1474 +requires: 155 --- -## Simple Summary -Wallets can update the active chain when connected to a Dapp but not vice-versa, with `wallet_updateEthereumChain` the Dapp will be able to request this change from the Wallet. - ## Abstract -Dapp can request the Wallet to switch chains by providing the minimal parameters of `chainId`, `chainName`, `rpcUrl`, `nativeCurrency` and `blockExplorerUrl`. The Wallet will display a UI element to inform the user of this change. -## Motivation -Wallet and Dapp communication rely on the present provider that acts as middleware between the two. Using JSON-RPC methods, the Dapp is able to access not only the active accounts but also the active chain. With [EIP-1102](./eip-1102.md) we introduced the ability for Dapps to request access to the active accounts and the Wallet is able to provide a simple UI to inform the user of this action however the same is not currently possible for switching chains. The current pattern is to display some UI to request the user to switch chains within the Dapp, however this could be easily improved by triggering a UI from the Wallet side that can be approved or rejected by the user instead. +This EIP adds a wallet-namespaced RPC endpoint, `wallet_updateEthereumChain`, providing a standard interface for switching chains. The method takes the minimal parameters of `chainId`, `chainName`, `rpcUrl`, `nativeCurrency` and `blockExplorerUrl`. ## Specification -The JSON RPC method will be part of `wallet_` namespaced methods which aim to improve the UX and interoperability between Dapps and Wallets. - -### Required Parameters -- chainId (string): the id of the chain compliant with EIP-155 -- chainName (string): the name of the chain to update -- rpcUrl (string): the url endpoint for RPC requests for this chain -- nativeCurrency (Object): includes three fields for `name` (string), `symbol` (string) and `decimals` (number) -- blockExplorerUrl (string): the url endpoint for a block explorer web site for the chain. - -### Best Practices -- The Wallet should display a UI view similar to a [EIP-1102](./eip-1102.md) informing the user that the currently connected Dapp wants to switch to the specified chain. -- the Wallet should default the rpcUrl to any existing endpoints matching a chainId known previously to the wallet, otherwise it will use the provided rpcUrl as a fallback. -- the Wallet should call the rpcUrl with `net_version` and `eth_chainId` to verify the provided chainId and networkId match the responses from the rpcUrl -- the Wallet should change all nativeCurrency symbols to the provided parameter - -### Example 1 -A JSON-RPC request from a Dapp to switch the Ethereum Goerli chain would be as follows: -```json -{ - "id":1, - "jsonrpc": "2.0", - "method": "wallet_updateChain", - "params": [ - { - "chainId": 0x5, - "chainName": "Goerli", - "rpcUrl": "https://goerli.infura.io/v3/406405f9c65348f99d0d5c27104b2213", - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH" - }, - "blockExplorerUrl": "https://goerli.etherscan.io" - } - ] + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +This proposal adds a method to a wallet's web3 provider API: `wallet_updateEthereumChain`. + +### `wallet_updateEthereumChain` + +The `wallet_updateEthereumChain` method is used to switch to a network, and registering it with the wallet if it isn't already recognized. + +The `wallet_updateEthereumChain` method takes one parameter, an `EthereumChainSwitchRequest` object, defined below: + +```typescript +interface NativeCurrencyData { + name: string; + symbol: string; + decimals: number; } -``` -### Example 2 -A JSON-RPC request from a Dapp to switch the POA Network's xDAI chain would be as follows: -```json -{ - "id":1, - "jsonrpc": "2.0", - "method": "wallet_updateChain", - "params": [ - { - "chainId": "0x5", - "chainName": "Goerli", - "rpcUrl": "https://goerli.infura.io/v3/406405f9c65348f99d0d5c27104b2213", - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH" - }, - "blockExplorerUrl": "https://goerli.etherscan.io" - } - ] +interface EthereumChainSwitchRequest { + chainId: string; + chainName?: string; + rpcUrls?: string[]; + nativeCurrency?: NativeCurrencyData; + blockExplorerUrl?: string; } ``` -### Responses +The `chainId` is the `0x`-prefixed [EIP-155](./eip-155.md)-compliant chain ID. The `chainName` is a suggested human-readable name of the chain, to be displayed to the user. The `rpcUrls` array is a list of RPC endpoints for the given `chainId`. The `nativeCurrency` object suggests how the native currency should be displayed. Its parameters, `name`, `symbol`, and `decimals`, should be interpreted like in [ERC-20](./eip-20.md). Finally, the `blockExplorerUrl` should link to a block explorer compatible with the given `chainId`. -A success response: +All keys other than the `chainId` are optional. All keys other than `chainId` are suggestions to the wallet. Wallets can choose to ignore or display other data to users. Wallets should prompt the user before switching or adding chains. Wallets should also store a default list of data for commonly-used chains, in order to avoid phishing attacks. Wallets MUST sanitize each RPC url before using it to send other requests, including ensuring that it responds correctly to the `net_version` and `eth_chainId` methods. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "result": true -} -``` +The `wallet_updateEthereumChain` method returns `true` if the active chain matches the requested chain, regardless of whether the chain was already active or was added to the wallet previously. If the user rejects the request, it must return an error with code `4001`. -A failure response: +## Rationale -```json -{ - "id": 1, - "jsonrpc": "2.0", - "error": { - "code": 4001, - "message": "The user rejected the request." - } -} -``` +The `wallet_updateEthereumChain` method is designed to be as simple as possible, while still providing the necessary information for a wallet to switch to a new chain. The `chainId` is the only required parameter, as it is the only parameter that is guaranteed to be unique. The `chainName` is included to provide a human-readable name for the chain, and the `rpcUrls` array is included to provide a list of RPC endpoints for the chain. The `nativeCurrency` object is included to provide a suggestion for how the native currency should be displayed. Finally, the `blockExplorerUrl` is included to provide a link to a block explorer for the chain. + +The `wallet_updateEthereumChain` method is namespaced under `wallet_` to avoid conflicts with other methods. The `wallet_` prefix is used by other methods that are wallet-specific, such as `wallet_addEthereumChain` and `wallet_switchEthereumChain`. + +## Backwards Compatibility + +This EIP is fully backwards compatible. + +## Security Considerations + +### Server-Side Request Forgery (SSRF) + +The `rpcUrls` parameter is a list of RPC endpoints for the chain. Wallets should sanitize each RPC url before using it to send other requests, including ensuring that it responds correctly to the `net_version` and `eth_chainId` methods. + +### Phishing + +Wallets should store a default list of data for commonly-used chains, in order to avoid phishing attacks. ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2018.md b/EIPS/eip-2018.md index 9959a341a2a9b6..dce10628acf0ae 100644 --- a/EIPS/eip-2018.md +++ b/EIPS/eip-2018.md @@ -1,261 +1,7 @@ --- eip: 2018 -title: Clearable Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2104 -status: Stagnant -type: Standards Track category: ERC -created: 2019-04-30 -requires: 1996 +status: Moved --- -## Simple Summary - -> "In banking and finance, clearing denotes all activities from the time a commitment is made for a transaction until it is settled." [[1]][Clearing-Wikipedia] - -## Actors - -#### Clearing Agent - -An account which processes, executes or rejects a clearable transfer. - -#### Operator -An account which has been approved by an account to order clearable transfers on its behalf. - -#### Orderer -The account which orders a clearable transfer. This can be the account owner itself, or any account, which has been approved as an operator for the account. - -## Abstract - -The clearing process turns the promise of a transfer into the actual movement of money from one account to another. A clearing agent decides if the transfer can be executed or not. The amount which should be transferred is not deducted from the balance of the payer, but neither is it available for another transfer and therefore ensures, that the execution of the transfer will be successful when it is executed. - -## Motivation - -A regulated token needs to comply with all the legal requirements, especially [KYC][KYC-Wikipedia] and [AML][AML-Wikipedia]. Some of these checks may not be able to be done on-chain and therefore a transfer may not be completed in one step. Currently there is no EIP to make such off-chain checks possible. This proposal allows a user to order a transfer, which can be checked by a clearing agent off-chain. Depending on the result of it, the clearing agent will either execute or cancel the transfer. To provide more information why a transfer is cancelled, the clearing agent can add a reason why it is not executed. - -## Specification - -```solidity -interface ClearableToken /* is ERC-1996 */ { - enum ClearableTransferStatusCode { Nonexistent, Ordered, InProcess, Executed, Rejected, Cancelled } - - function orderTransfer(string calldata operationId, address to, uint256 value) external returns (bool); - function orderTransferFrom(string calldata operationId, address from, address to, uint256 value) external returns (bool); - function cancelTransfer(string calldata operationId) external returns (bool); - function processClearableTransfer(string calldata operationId) external returns (bool); - function executeClearableTransfer(string calldata operationId) external returns (bool); - function rejectClearableTransfer(string calldata operationId, string calldata reason) external returns (bool); - function retrieveClearableTransferData(string calldata operationId) external view returns (address from, address to, uint256 value, ClearableTransferStatusCode status); - - function authorizeClearableTransferOperator(address operator) external returns (bool); - function revokeClearableTransferOperator(address operator) external returns (bool); - function isClearableTransferOperatorFor(address operator, address from) external view returns (bool); - - event ClearableTransferOrdered(address indexed orderer, string operationId, address indexed from, address indexed to, uint256 value); - event ClearableTransferInProcess(address indexed orderer, string operationId); - event ClearableTransferExecuted(address indexed orderer, string operationId); - event ClearableTransferRejected(address indexed orderer, string operationId, string reason); - event ClearableTransferCancelled(address indexed orderer, string operationId); - event AuthorizedClearableTransferOperator(address indexed operator, address indexed account); - event RevokedClearableTransferOperator(address indexed operator, address indexed account); -} -``` - -### Functions - -#### orderTransfer - -Orders a clearable transfer on behalf of the msg.sender in favor of `to`. A clearing agent is responsible to either execute or reject the transfer. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | - -#### orderTransferFrom - -Orders a clearable transfer on behalf of the payer in favor of the `to`. A clearing agent is responsible to either execute or reject the transfer. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer. | - -#### cancelTransfer - -Cancels the order of a clearable transfer. Only the orderer can cancel their own orders. It must not be successful as soon as the transfer is in status `InProcess`. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### processClearableTransfer - -Sets a clearable transfer to status `InProcess`. Only a clearing agent can successfully execute this action. This status is optional, but without it the orderer can cancel the transfer at any time. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### executeClearableTransfer - -Executes a clearable transfer, which means that the tokens are transferred from the payer to the payee. Only a clearing agent can successfully execute this action. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### rejectClearableTransfer - -Rejects a clearable transfer, which means that the amount that is held is available again to the payer and no transfer is done. Only a clearing agent can successfully execute this action. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | -| reason | A reason given by the clearing agent why the transfer has been rejected | - -#### retrieveClearableTransferData - -Retrieves all the information available for a particular clearable transfer. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the clearable transfer | - -#### authorizeClearableTransferOperator - -Approves an operator to order transfers on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | - -#### revokeClearableTransferOperator - -Revokes the approval to order transfers on behalf of msg.sender. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be revoked as operator of clearable transfers | - -#### isClearableTransferOperatorFor - -Returns if an operator is approved to order transfers on behalf of `from`. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be an operator of clearable transfers | -| from | The address on which the holds would be created | - -#### transfer - -It is up to the implementer of the EIP if the `transfer` function of ERC-20 should always revert or is allowed under certain circumstances. - -#### transferFrom - -It is up to the implementer of the EIP if the `transferFrom` function of ERC-20 should always revert or is allowed under certain circumstances. - - -### Events - -#### ClearableTransferOrdered - -Must be emitted when a clearable transfer is ordered. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred if executed | - -#### ClearableTransferInProcess - -Must be emitted when a clearable transfer is put in status `ÌnProcess`. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### ClearableTransferExecuted - -Must be emitted when a clearable transfer is executed. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### ClearableTransferRejected - -Must be emitted when a clearable transfer is rejected. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | -| reason | A reason given by the clearing agent why the transfer has been rejected | - -#### ClearableTransferCancelled - -Must be emitted when a clearable transfer is cancelled by its orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer of the transfer | -| operationId | The unique ID to identify the clearable transfer | - -#### AuthorizedClearableTransferOperator - -Emitted when an operator has been approved to order transfers on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which has been approved as operator of clearable transfers | -| account | Address on which behalf transfers will potentially be ordered | - -#### RevokedClearableTransferOperator - -Emitted when an operator has been revoked from ordering transfers on behalf of another account. - -| Parameter | Description | -| ---------|-------------| -| operator | The address which has been revoked as operator of clearable transfers | -| account | Address on which behalf transfers could potentially be ordered | - -## Rationale - -This EIP uses [EIP-1996][EIP-1996] to hold the money after a transfer is ordered. A clearing agent, whose implementation is not part of this proposal, acts as a predefined notary to decide if the transfer complies with the rules of the token or not. - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -While not requiring it, the naming of the functions `authorizeClearableTransferOperator`, `revokeClearableTransferOperator` and `isClearableTransferOperatorFor` follows the naming convention of [ERC-777](./eip-777.md). - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [EIP-1996][EIP-1996]. - -## Implementation - -The GitHub repository [IoBuilders/clearable-token](https://github.com/IoBuilders/clearable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[1] https://en.wikipedia.org/wiki/Clearing_(finance) - -[Clearing-Wikipedia]: https://en.wikipedia.org/wiki/Clearing_(finance) -[KYC-Wikipedia]: https://en.wikipedia.org/wiki/Know_your_customer -[AML-Wikipedia]: https://en.wikipedia.org/wiki/Money_laundering#Anti-money_laundering -[EIP-1996]: ./eip-1996.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2018.md diff --git a/EIPS/eip-2019.md b/EIPS/eip-2019.md index a59cc4fbc5fe25..c4ad7b3c4f315d 100644 --- a/EIPS/eip-2019.md +++ b/EIPS/eip-2019.md @@ -1,255 +1,7 @@ --- eip: 2019 -title: Fundable Token -author: Fernando Paris , Julio Faura , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2105 -status: Stagnant -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20 +status: Moved --- -## Simple Summary -An extension to the [ERC-20] standard token that allows Token wallet owners to request a wallet to be funded, by calling the smart contract and attaching a fund instruction string. - -## Actors - -#### Token Wallet Owners -The person or company who owns the wallet, and will order a token fund request into the wallet. - -#### Token contract owner / agent -The entity, company responsible/owner of the token contract, and token issuing/minting. This actor is in charge of trying to fulfill all fund request(s), reading the fund instruction(s), and correlate the private payment details. - -#### Orderer -An actor who is enabled to initiate funding orders on behalf of a token wallet owner. - -## Abstract -Token wallet owners (or approved addresses) can order tokenization requests through blockchain. This is done by calling the ```orderFund``` or ```orderFundFrom``` methods, which initiate the workflow for the token contract operator to either honor or reject the fund request. In this case, fund instructions are provided when submitting the request, which are used by the operator to determine the source of the funds to be debited in order to do fund the token wallet (through minting). - -In general, it is not advisable to place explicit routing instructions for debiting funds on a verbatim basis on the blockchain, and it is advised to use a private communication alternatives, such as private channels, encrypted storage or similar, to do so (external to the blockchain ledger). Another (less desirable) possibility is to place these instructions on the instructions field in encrypted form. - -## Motivation -Nowadays most of the token issuing/funding request, based on any fiat based payment method need a previous centralized transaction, to be able to get the desired tokens issued on requester's wallet. -In the aim of trying to bring all the needed steps into decentralization, exposing all the needed steps of token lifecycle and payment transactions, a funding request can allow wallet owner to initiate the funding request via blockchain. -Key benefits: - -* Funding and payment traceability is enhanced bringing the initiation into the ledger. All payment stat -s can be stored on chain. -* Almost all money/token lifecycle is covered via a decentralized approach, complemented with private communications which is common use in the ecosystem. - -## Specification - -```solidity -interface IFundable /* is ERC-20 */ { - enum FundStatusCode { - Nonexistent, - Ordered, - InProcess, - Executed, - Rejected, - Cancelled - } - function authorizeFundOperator(address orderer) external returns (bool); - function revokeFundOperator(address orderer) external returns (bool) ; - function orderFund(string calldata operationId, uint256 value, string calldata instructions) external returns (bool); - function orderFundFrom(string calldata operationId, address walletToFund, uint256 value, string calldata instructions) external returns (bool); - function cancelFund(string calldata operationId) external returns (bool); - function processFund(string calldata operationId) external returns (bool); - function executeFund(string calldata operationId) external returns (bool); - function rejectFund(string calldata operationId, string calldata reason) external returns (bool); - - function isFundOperatorFor(address walletToFund, address orderer) external view returns (bool); - function retrieveFundData(address orderer, string calldata operationId) external view returns (address walletToFund, uint256 value, string memory instructions, FundStatusCode status); - - event FundOrdered(address indexed orderer, string indexed operationId, address indexed , uint256 value, string instructions); - event FundInProcess(address indexed orderer, string indexed operationId); - event FundExecuted(address indexed orderer, string indexed operationId); - event FundRejected(address indexed orderer, string indexed operationId, string reason); - event FundCancelled(address indexed orderer, string indexed operationId); - event FundOperatorAuthorized(address indexed walletToFund, address indexed orderer); - event FundOperatorRevoked(address indexed walletToFund, address indexed orderer); -} -``` - -### Functions - -#### authorizeFundOperator - -Wallet owner, authorizes a given address to be fund orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. - -#### revokeFundOperator - -Wallet owner, revokes a given address to be fund orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. - -#### orderFund - -Creates a fund request, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### orderFundFrom - -Creates a fund request, on behalf of a wallet owner, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId |The unique ID to identify the request | -| walletToFund | The wallet to be funded on behalf. -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### cancelFund - -Cancels a funding request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that is going to be cancelled. This can only be done by token holder, or the fund initiator. | - -#### processFund - -Marks a funding request as on process. After the status is on process, order cannot be cancelled. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request is in process. - -#### executeFund - -Issues the amount of tokens and marks a funding request as executed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. - -#### rejectFund - -Rejects a given operation with a reason. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. -| reason | The specific reason that explains why the fund request was rejected. EIP 1066 codes can be used | - -#### isFundOperatorFor - -Checks that given player is allowed to order fund requests, for a given wallet. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet to be funded, and checked for approval permission. -| orderer | The address of the orderer, to be checked for approval permission. - -#### retrieveFundData - -Retrieves all the fund request data. Only operator, tokenHolder, and orderer can get the given operation data. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the fund order. - -### Events - -#### FundOrdered - -Emitted when an token wallet owner orders a funding request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| walletToFund | The wallet that the player is allowed to start funding requests | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### FundInProcess - -Emitted when an operator starts a funding request after validating the instruction, and the operation is marked as in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundExecuted - -Emitted when an operator has executed a funding request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundRejected - -Emitted when an operator has rejected a funding request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | -| reason | The specific reason that explains why the fund request was rejected. EIP 1066 codes can be used | - -#### FundCancelled - -Emitted when a token holder, orderer, has cancelled a funding request. This can only be done if the operator hasn't put the funding order in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the fund request orderer. | -| operationId | The unique ID to identify the fund. | - -#### FundOperatorAuthorized - -Emitted when a given player, operator, company or a given persona, has been approved to start fund request for a given token holder. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet that the player is allowed to start funding requests | -| orderer | The address that allows the the player to start requests. | - -#### FundOperatorRevoked - -Emitted when a given player has been revoked initiate funding requests. - -| Parameter | Description | -| ---------|-------------| -| walletToFund | The wallet that the player is allowed to start funding requests | -| orderer | The address that allows the the player to start requests. | - -## Rationale -This standards provides a functionality to allow token holders to start funding requests in a decentralized way. - -It's important to highlight that the token operator, need to process all funding request, updating the fund status based on the linked payment that will be done. - -Funding instruction format is open. ISO payment standard like is a good start point, - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20]. - -## Implementation -The GitHub repository [IoBuilders/fundable-token](https://github.com/IoBuilders/fundable-token) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[ERC-20]: ./eip-20.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2019.md diff --git a/EIPS/eip-2020.md b/EIPS/eip-2020.md index ddf3419f59ab49..9cdaef6e9f076d 100644 --- a/EIPS/eip-2020.md +++ b/EIPS/eip-2020.md @@ -1,233 +1,7 @@ --- eip: 2020 -title: E-Money Standard Token -author: Julio Faura , Fernando Paris , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2407 -status: Stagnant -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20, 1066, 1996, 2009, 2018, 2019, 2021 +status: Moved --- -## Simple Summary - -The E-Money Standard Token aims to enable the issuance of regulated electronic money on blockchain networks, and its practical usage in real financial applications. - -## Actors - -#### Operator -An account, which has been approved by an account to perform an action on the behalf of another account. - -## Abstract - -Financial institutions work today with electronic systems, which hold account balances in databases on core banking systems. In order for an institution to be allowed to maintain records of client balances segregated and available for clients, such institution must be regulated under a known legal framework and must possess a license to do so. Maintaining a license under regulatory supervision entails ensuring compliance (i.e. performing KYC on all clients and ensuring good AML practices before allowing transactions) and demonstrating technical and operational solvency through periodic audits, so clients depositing funds with the institution can rest assured that their money is safe. - -## Motivation - -There are only a number of potential regulatory license frameworks that allow institutions to issue and hold money balances for customers (be it retail corporate or institutional types). The most important and practical ones are three: -* **Electronic money entities**: these are legally regulated vehicles that are mostly used today for cash and payments services, instead of more complex financial services. For example prepaid cards or online payment systems such as PayPal run on such schemes. In most jurisdictions, electronic money balances are required to be 100% backed by assets, which often entails holding cash on an omnibus account at a bank with 100% of the funds issued to clients in the electronic money ledger. -* **Banking licenses**: these include commercial and investment banks, which segregate client funds using current and other type of accounts implemented on core banking systems. Banks can create money by lending to clients, so bank money can be backed by promises to pay and other illiquid assets. -* **Central banks**: central banks hold balances for banks in RTGS systems, similar to core banking systems but with much more restricted yet critical functionality. Central banks create money by lending it to banks, which pledge their assets to central banks as a lender of last resort for an official interest rate. - -Regulations for all these types of electronic money are local, i.e. only valid for each jurisdiction and not valid in others. Regulations can vary as well dramatically in different jurisdictions — for example there are places with no electronic money frameworks, on everything has to be done through banking licenses or directly with a central bank. But in all cases compliance with existing regulation needs to ensured, in particular: -* **Know Your Customer (KYC)**: the institution needs to identify the client before providing them with the possibility of depositing money or transact. In different jurisdictions and for different types of licenses there are different levels of balance and activity that can be allowed for different levels of KYC. For example, low KYC requirements with little checks or even no checks at all can usually be acceptable in many jurisdictions if cashin balances are kept low (i.e. hundreds of dollars) -* **Anti Money Laundering (AML)**: the institution needs to perform checks of parties transacting with its clients, typically checking against black lists and doing sanction screening, most notably in the context of international transactions - -Beyond cash, financial instruments such as equities or bonds are also registered in electronic systems in most cases, although all these systems and the bank accounting systems are only connected through rudimentary messaging means, which leads to the need for reconciliations and manual management in many cases. Cash systems to provide settlement of transactions in the capital markets are not well-connected to the transactional systems, and often entail delays and settlement risk. - -The E-Money Standard Token builds on Ethereum standards currently in use such as [ERC-20], but it extends them to provide few key additional pieces of functionality, needed in the regulated financial world: -* **Compliance**: E-Money Standard Token implements a set of methods to check in advance whether user-initiated transactions can be done from a compliance point of view. Implementations must `require` that these methods return a positive answer before executing the transaction. -* **Clearing**: In addition to the standard [ERC-20] `transfer` method, E-Money Standard Token provides a way to submit transfers that need to be cleared by the token issuing authority off-chain. These transfers are then executed in two steps: - 1. transfers are ordered - 1. after clearing them, transfers are executed or rejected by the operator of the token contract -* **Holds**: token balances can be put on hold, which will make the held amount unavailable for further use until the hold is resolved (i.e. either executed or released). Holds have a payer, a payee, and a notary who is in charge of resolving the hold. Holds also implement expiration periods, after which anyone can release the hold Holds are similar to escrows in that are firm and lead to final settlement. Holds can also be used to implement collateralization. -* **Funding requests**: users can request for a wallet to be funded by calling the smart contract and attaching a debit instruction string. The tokenizer reads this request, interprets the debit instructions, and triggers a transfer in the bank ledger to initiate the tokenization process. -* **Payouts**: users can request payouts by calling the smart contract and attaching a payment instruction string. The (de)tokenizer reads this request, interprets the payment instructions, and triggers the transfer of funds (typically from the omnibus account) into the destination account, if possible. Note that a redemption request is a special type of payout in which the destination (bank) account for the payout is the bank account linked to the token wallet. - -The E-Money Standard Token is thus different from other tokens commonly referred to as "stable coins" in that it is designed to be issued, burnt and made available to users in a compliant manner (i.e. with full KYC and AML compliance) through a licensed vehicle (an electronic money entity, a bank, or a central bank), and in that it provides the additional functionality described above, so it can be used by other smart contracts implementing more complex financial applications such as interbank payments, supply chain finance instruments, or the creation of E-Money Standard Token denominated bonds and equities with automatic delivery-vs-payment. - -## Specification - -```solidity -interface EMoneyToken /* is ERC-1996, ERC-2018, ERC-2019, ERC-2021 */ { - function currency() external view returns (string memory); - function version() external pure returns (string memory); - - function availableFunds(address account) external view returns (uint256); - - function checkTransferAllowed(address from, address to, uint256 value) external view returns (byte status); - function checkApproveAllowed(address from, address spender, uint256 value) external view returns (byte status); - - function checkHoldAllowed(address from, address to, address notary, uint256 value) external view returns (byte status); - function checkAuthorizeHoldOperatorAllowed(address operator, address from) external view returns (byte status); - - function checkOrderTransferAllowed(address from, address to, uint256 value) external view returns (byte status); - function checkAuthorizeClearableTransferOperatorAllowed(address operator, address from) external view returns (byte status); - - function checkOrderFundAllowed(address to, address operator, uint256 value) external view returns (byte status); - function checkAuthorizeFundOperatorAllowed(address operator, address to) external view returns (byte status); - - function checkOrderPayoutAllowed(address from, address operator, uint256 value) external view returns (byte status); - function checkAuthorizePayoutOperatorAllowed(address operator, address from) external view returns (byte status); -} -``` - -### Mandatory checks - -The checks must be verified in their corresponding actions. The action must only be successful if the check return an `Allowed` status code. In any other case the functions must revert. - -### Status codes - -If an action is allowed `0x11` (Allowed), or an issuer-specific code with equivalent but more precise meaning must be returned. If the action is not allowed the status must be `0x10` (Disallowed), or an issuer-specific code with equivalent but more precise meaning. - -### Functions - -#### currency - -Returns the currency that backs the token. The value must be a code defined in [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217). - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### version - -Returns the current version of the smart contract. The format of the version is up to the implementer of the EIP. - -| Parameter | Description | -| ---------|-------------| -| - | - | - -#### availableFunds - -Returns the total net funds of an account. Taking into consideration the outright balance and the held balances. - -| Parameter | Description | -| ---------|-------------| -| account | The account which available funds should be returned | - -#### checkTransferAllowed - -Checks if the `transfer` or `transferFrom` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| value | The amount to be transferred | - -#### checkApproveAllowed - -Checks if the `approve` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| spender | The address of the spender, which potentially can initiate transfers on behalf of `from` | -| value | The maximum amount to be transferred | - -#### checkHoldAllowed - -Checks if the `hold` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be transferred if executed | -| notary | The address of the notary who is going to determine whether the hold is to be executed or released | -| value | The amount to be transferred. Must be less or equal than the balance of the payer | - -#### checkAuthorizeHoldOperatorAllowed - -Checks if the `checkAuthorizeHoldOperatorAllowed` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | -| from | The address on which behalf holds could potentially be issued | - -#### checkOrderTransferAllowed - -Checks if the `orderTransfer` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address of the payer, from whom the tokens are to be taken if executed | -| to | The address of the payee, to whom the tokens are to be paid if executed | -| value | The amount to be transferred. Must be less or equal than the balance of the payer | - -#### checkAuthorizeClearableTransferOperatorAllowed - -Checks if the `authorizeClearableTransferOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of clearable transfers | -| from | The address on which behalf clearable transfers could potentially be ordered | - -#### checkOrderFundAllowed - -Checks if the `orderFund` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| to | The address to which the tokens are to be given if executed | -| operator | The address of the requester, which initiates the funding order | -| value | The amount to be funded | - -#### checkAuthorizeFundOperatorAllowed - -Checks if the `authorizeFundOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of ordering funding | -| to | The address which the tokens are to be given if executed | - -#### checkOrderPayoutAllowed - -Checks if the `orderPayout` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| from | The address from whom the tokens are to be taken if executed | -| operator | The address of the requester, which initiates the payout request | -| value | The amount to be paid out | - -#### checkAuthorizePayoutOperatorAllowed - -Checks if the `authorizePayoutOperator` function is allowed to be executed with the given parameters. - -| Parameter | Description | -| ---------|-------------| -| operator | The address to be approved as operator of ordering payouts | -| from | The address from which the tokens are to be taken if executed | - -## Rationale - -This EIP unifies [ERC-1996][ERC-1996], [ERC-2018][ERC-2018], [ERC-2019][ERC-2019] and [ERC-2021][ERC-2021] and adds the checks for the compliance on top of it. By this way the separate EIPs are otherwise independent of each other, and the E-Money Standard Token offers a solution for all necessary functionality of regulated electronic money. - -While not requiring it, the naming of the check functions was adopted from [ERC-1462][ERC-1462]. - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-1996][ERC-1996], [ERC-2018][ERC-2018], [ERC-2019][ERC-2019], [ERC-2021][ERC-2021] and [ERC-1066][ERC-1066]. - -## Implementation - -The GitHub repository [IoBuilders/em-token](https://github.com/IoBuilders/em-token) contains the work in progress implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[ERC-20]: ./eip-20.md -[ERC-1066]: ./eip-1066.md -[ERC-1462]: ./eip-1462.md -[ERC-1996]: ./eip-1996.md -[ERC-2018]: ./eip-2018.md -[ERC-2019]: ./eip-2019.md -[ERC-2021]: ./eip-2021.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2020.md diff --git a/EIPS/eip-2021.md b/EIPS/eip-2021.md index 8464686dd789ce..a4f4befe9f91ca 100644 --- a/EIPS/eip-2021.md +++ b/EIPS/eip-2021.md @@ -1,290 +1,7 @@ --- eip: 2021 -title: Payoutable Token -author: Fernando Paris , Julio Faura , Daniel Lehrner -discussions-to: https://github.com/ethereum/EIPs/issues/2106 -status: Stagnant -type: Standards Track category: ERC -created: 2019-05-10 -requires: 20, 1066, 1996 +status: Moved --- -## Simple Summary -An extension to the [ERC-20] standard token that allows Token wallet owners to request payout from their wallet, by calling the smart contract and attaching a payout instruction string. - -## Actors - -#### Token Wallet Owners -The person or company who owns the wallet, and will order payout. - -#### Token contract owner / agent -The entity, company responsible/owner of the token contract, and token issuing/minting. This actor is in charge of trying to fulfill all payout request(s), reading the payout instruction(s), and correlate the payout details. - -#### Orderer -An actor who is enabled to initiate payout orders on behalf of a token wallet owner. - -## Abstract -Token wallet owners (or approved addresses) can order payout requests through blockchain. This is done by calling the ```orderPayoutFrom``` or ```orderPayoutFrom``` methods, which initiate the workflow for the token contract operator to either honor or reject the payout request. In this case, payout instructions are provided when submitting the request, which are used by the operator to determine the destination of the funds. - -In general, it is not advisable to place explicit routing instructions for the payouts on a verbatim basis on the blockchain, and it is advised to use a private communication alternatives, such as private channels, encrypted storage or similar, to do so (external to the blockchain ledger). Another (less desirable) possibility is to place these instructions on the instructions field in encrypted form. - -## Motivation -Nowadays most of the token payout requests, need a previous centralized transaction, to be able to define the payout destination to be able to execute the payout (burn transaction). -In the aim of trying to bring all the needed steps into decentralization, exposing all the needed steps of token lifecycle and payment transactions, a payout request can allow wallet owner to initiate the payout order via blockchain. -Key benefits: - -* Payout, burning traceability is enhanced bringing the initiation into the ledger. All payment, payout statuses can be stored on chain. -* Almost all money/token lifecycle is covered via a decentralized approach, complemented with private communications which is common use in the ecosystem. - -In this case, the following movement of tokens are done as the process progresses: - -* Upon launch of the payout request, the appropriate amount of funds are placed on a hold with a predefined notary defined by the platform, and the payout is placed into a ```Ordered``` state -* The operator then can put the payout request ```InProcess```, which prevents the _orderer_ of the payout from being able to cancel the payout request -* After checking the payout is actually possible the operator then executes the hold, which moves the funds to a suspense wallet and places the payout into the ```FundsInSuspense``` state -* The operator then moves the funds offchain (usually from the omnibus account) to the appropriate destination account, then burning the tokens from the suspense wallet and rendering the payout into the ```Executed``` state -* Either before or after placing the request ```InProcess```, the operator can also reject the payout, which returns the funds to the payer and eliminates the hold. The resulting end state of the payout is ```Rejected``` -* When the payout is ```Ordered``` and before the operator places it into the ```InProcess``` state, the orderer of the payout can also cancel it, which frees up the hold and puts the payout into the final ```Cancelled``` state - -## Specification - -```solidity -interface IPayoutable /* is ERC-20 */ { - enum PayoutStatusCode { - Nonexistent, - Ordered, - InProcess, - FundsInSuspense, - Executed, - Rejected, - Cancelled - } - function authorizePayoutOperator(address orderer) external returns (bool); - function revokePayoutOperator(address orderer) external returns (bool); - function orderPayout(string calldata operationId, uint256 value, string calldata instructions) external returns (bool); - function orderPayoutFrom(string calldata operationId, address walletToBePaidOut, uint256 value, string calldata instructions) external returns (bool); - function cancelPayout(string calldata operationId) external returns (bool); - function processPayout(string calldata operationId) external returns (bool); - function putFundsInSuspenseInPayout(string calldata operationId) external returns (bool); - function executePayout(string calldata operationId) external returns (bool); - function rejectPayout(string calldata operationId, string calldata reason) external returns (bool); - - function isPayoutOperatorFor(address walletToDebit, address orderer) external view returns (bool); - function retrievePayoutData(string calldata operationId) external view returns (address walletToDebit, uint256 value, string memory instructions, PayoutStatusCode status); - - event PayoutOrdered(address indexed orderer, string indexed operationId, address indexed walletToDebit, uint256 value, string instructions); - event PayoutInProcess(address indexed orderer, string indexed operationId); - event PayoutFundsInSuspense(address indexed orderer, string indexed operationId); - event PayoutExecuted(address indexed orderer, string indexed operationId); - event PayoutRejected(address indexed orderer, string indexed operationId, string reason); - event PayoutCancelled(address indexed orderer, string indexed operationId); - event PayoutOperatorAuthorized(address indexed walletToBePaidOut, address indexed orderer); - event PayoutOperatorRevoked(address indexed walletToBePaidOut, address indexed orderer); -} -``` - -### Functions - -#### authorizePayoutOperator - -Wallet owner, allows a given address to be payout orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. | - -#### revokePayoutOperator - -Wallet owner, Revokes a given address to be payout orderer. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer. | - -#### orderPayout - -Creates a payout request, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| value | The amount to be paid out. | -| instruction | A string including the payment instruction. | - -#### orderPayoutFrom - -Creates a payout request, on behalf of a wallet owner, that will be processed by the token operator. The function must revert if the operation ID has been used before. - -| Parameter | Description | -| ---------|-------------| -| operationId |The unique ID to identify the request | -| walletToBePaidOut | The wallet to be paid out on behalf. | -| value | The amount to be paid out. | -| instruction | A string including the payment instruction. | - -#### cancelPayout - -Cancels a payout request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that is going to be cancelled. This can only be done by token holder, or the payout initiator/orderer. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used. | - - -#### processPayout - -Marks a payout request as on process. After the status is on process, order cannot be cancelled. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify that the request is in process. | - -#### putFundsInSuspenseInPayout - -Put a given payout in suspense. Can only be done if it is in process. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify that the request is in process. | - -#### executePayout - -Burn the amount of tokens and marks a payout request as executed. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. | - -#### rejectPayout - -Rejects a given operation with a reason. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request that has been executed. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used | - -#### isApprovedToOrderPayout - -Checks that given player is allowed to order payout requests, for a given wallet. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet to be paid out, and checked for approval permission. | -| orderer | The address of the orderer, to be checked for approval permission. | - -#### retrievePayoutData - -Retrieves all the payout request data. Only operator, tokenHolder, and orderer can get the given operation data. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the orderer, to correlate the right data. | -| operationId | The unique ID to identify the payout order. | - -### Events - -#### Payout Ordered - -Emitted when an token wallet owner orders a payout request. - -| Parameter | Description | -| ---------|-------------| -| operationId | The unique ID to identify the request | -| walletToBePaidOut | The wallet that is requested to be paid out | -| value | The amount to be funded. | -| instruction | A string including the payment instruction. | - -#### PayoutFundsInSuspense - -Emitted when an operator puts fund in suspense. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutInProcess - -Emitted when an operator accepts a payout request, and the operation is in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutExecuted - -Emitted when an operator has executed a payout request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | - -#### PayoutRejected - -Emitted when an operator has rejected a payout request. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID to identify the payout. | -| reason | The specific reason that explains why the payout request was rejected. [EIP-1066] codes can be used | - -#### PayoutCancelled - -Emitted when a token holder, orderer, has cancelled a payout request. This can only be done if the operator hasn't put the payout order in process. - -| Parameter | Description | -| ---------|-------------| -| orderer | The address of the payout request orderer. | -| operationId | The unique ID per payout issuer to identify the payout. | - -#### PayoutOperatorAuthorized - -Emitted when a given player, operator, company or a given persona, has been approved to start payout request for a given token holder. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet that the player is allowed to start payout requests | -| orderer |The address that allows the the player to start requests. | - -#### PayoutOperatorRevoked - -Emitted when a given player has been revoked initiate payout requests. - -| Parameter | Description | -| ---------|-------------| -| walletToBePaidOut | The wallet that the player is allowed to start payout requests | -| orderer |The address that allows the the player to start requests. | - -## Rationale -This standards provides a functionality to allow token holders to start payout requests in a decentralized way. - -It's important to highlight that the token operator, need to process all payout request, updating the payout status based on the linked payment that will be done. - -Payout instruction format is open. ISO payment standard like is a good start point. - -This EIP uses [EIP-1996] to hold the money after a payout is ordered. The token contract owner or agent, whose implementation is not part of this proposal, acts as a predefined notary to decide if the payout is executed or not. - -The `operationId` is a string and not something more gas efficient to allow easy traceability of the hold and allow human readable ids. It is up to the implementer if the string should be stored on-chain or only its hash, as it is enough to identify a hold. - -The `operationId` is a competitive resource. It is recommended, but not required, that the hold issuers used a unique prefix to avoid collisions. - -## Backwards Compatibility -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20] and [ERC-1996]. - -## Implementation -The GitHub repository [IoBuilders/payoutable-token](https://github.com/IoBuilders/payoutable-token) contains the reference implementation. - -## Contributors -This proposal has been collaboratively implemented by [adhara.io](https://adhara.io/) and [io.builders](https://io.builders/). - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[ERC-20]: ./eip-20.md -[EIP-1066]: ./eip-1066.md -[EIP-1996]: ./eip-1996.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2021.md diff --git a/EIPS/eip-2025.md b/EIPS/eip-2025.md index 631f602b6c8fbc..ae9baa017c31db 100644 --- a/EIPS/eip-2025.md +++ b/EIPS/eip-2025.md @@ -65,7 +65,7 @@ FOR BENEFICIARY in BENEFICIARY_ADDRESSES: *With a price of Etheruem at $150.00 this will raise approx USD $2,325,000.00 for developing Eth1.X over the next 18 months.* -![Block Rewards Distribution](/assets/eip-2025/block_rewards_distribution.png) *Specific Addresses to be determined +![Block Rewards Distribution](../assets/eip-2025/block_rewards_distribution.png) *Specific Addresses to be determined * [FAQ - Why hardcoded values?]( #why-hardcoded-values ) @@ -80,7 +80,7 @@ The Eth1x initiative needs funding now, not in 18 months. A loan is necessary to ### Loan Repayment -![Loan State Diagram](/assets/eip-2025/loan_state.png) +![Loan State Diagram](../assets/eip-2025/loan_state.png) There is a risk that the investors lose part of their contribution in the case that this EIP is rejected by the community between the time the funds have been collected and the beginning of the payout schedule. In this case all remaining funds will be returned to the contributors. The interest on the loan is an incentive for investors to participate in spite of this risk. Their downside is limited to the amount of funds spent before this EIP is accepted or rejected, which should be no more than about 5%, while their upside consists of the 10% simple interest paid over the period. diff --git a/EIPS/eip-2026.md b/EIPS/eip-2026.md index 4523184bd6c481..e230dae7c2dbcc 100644 --- a/EIPS/eip-2026.md +++ b/EIPS/eip-2026.md @@ -27,7 +27,7 @@ The penalty is levied to the transaction sender. Rather than raising the gas cos ## Specification On and after block `H`, every newly created account gets a new field `rentbalance` of type unsigned 256-bit integer. On and after block `H`, any operation that leads to the creation of a new account, deducts the amount `ACCOUNT_PREPAYMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the created account. -On and after block `H`, any operation that modifies an account that does not yet have `rentbalance` field, deducts the amount `ACCOUNT_PREPAYEMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the modified account. This is a anti-hoarding measure. +On and after block `H`, any operation that modifies an account that does not yet have `rentbalance` field, deducts the amount `ACCOUNT_PREPAYEMENT` from `tx.origin`. This amount is added to the `rentbalance` field of the modified account. This is an anti-hoarding measure. Operations leading to the creations of a new account: 1. Creation of a non-contract account by sending non-zero ETH to an address with no associated account @@ -45,7 +45,7 @@ Prior to rent prepayments, other alternatives were considered: 1. In [first version of State Rent proposal](https://github.com/ledgerwatch/eth_state/blob/master/State_rent.pdf), there was no notion of extra levy upon account creation. It created a slight usability issue, where newly created contracts with 0 endowment would be evicted in the same block (when rent is introduced). It delays the benefits of the State Rent programme until the actual introduction of rent (in second or third hard-fork). 2. In the [second version of State Rent proposal](https://github.com/ledgerwatch/eth_state/blob/master/State_Rent_2.pdf), there was a notion of lock-up. It is very similar to rent prepayment, with the different that lock-up would not be covering future rent payments. -An alternative approach to limiting the prepayments (instead of the using `gaslimit` * `gasprice` as the limit) is to introduce a new dedicated field `prepaymenlimit` into the transaction. This field would only limit prepayments). Such approach would require changes in the transaction format, as well as changes in the user interface for transaction sender, and having two counters during the transaction execution - one for gas, and one for prepayments. +An alternative approach to limiting the prepayments (instead of the using `gaslimit` * `gasprice` as the limit) is to introduce a new dedicated field `prepaymenlimit` into the transaction. This field would only limit prepayments. Such approach would require changes in the transaction format, as well as changes in the user interface for transaction sender, and having two counters during the transaction execution - one for gas, and one for prepayments. ## Backwards Compatibility This change is not backwards compatible and requires hard fork to be activated. diff --git a/EIPS/eip-205.md b/EIPS/eip-205.md index 451cc835e4f67a..6b7887551ff154 100644 --- a/EIPS/eip-205.md +++ b/EIPS/eip-205.md @@ -1,69 +1,7 @@ --- eip: 205 -title: ENS support for contract ABIs -author: Nick Johnson -type: Standards Track category: ERC -status: Stagnant -created: 2017-02-06 -requires: 137, 181 +status: Moved --- -## Simple Summary -This EIP proposes a mechanism for storing ABI definitions in ENS, for easy lookup of contract interfaces by callers. - -## Abstract -ABIs are important metadata required for interacting with most contracts. At present, they are typically supplied out-of-band, which adds an additional burden to interacting with contracts, particularly on a one-off basis or where the ABI may be updated over time. The small size of ABIs permits an alternative solution, storing them in ENS, permitting name lookup and ABI discovery via the same process. - -ABIs are typically quite compact; the largest in-use ABI we could find, that for the DAO, is 9450 bytes uncompressed JSON, 6920 bytes uncompressed CBOR, and 1128 bytes when the JSON form is compressed with zlib. Further gains on CBOR encoding are possible using a CBOR extension that permits eliminating repeated strings, which feature extensively in ABIs. Most ABIs, however, are far shorter than this, consisting of only a few hundred bytes of uncompressed JSON. - -This EIP defines a resolver profile for retrieving contract ABIs, as well as encoding standards for storing ABIs for different applications, allowing the user to select between different representations based on their need for compactness and other considerations such as onchain access. - -## Specification -### ABI encodings -In order to allow for different tradeoffs between onchain size and accessibility, several ABI encodings are defined. Each ABI encoding is defined by a unique constant with only a single bit set, allowing for the specification of 256 unique encodings in a single uint. - -The currently recognised encodings are: - -| ID | Description | -|----|----------------------| -| 1 | JSON | -| 2 | zlib-compressed JSON | -| 4 | CBOR | -| 8 | URI | - -This table may be extended in future through the EIP process. - -Encoding type 1 specifies plaintext JSON, uncompressed; this is the standard format in which ABIs are typically encoded, but also the bulkiest, and is not easily parseable onchain. - -Encoding type 2 specifies zlib-compressed JSON. This is significantly smaller than uncompressed JSON, and is straightforward to decode offchain. However, it is impracticalfor onchain consumers to use. - -Encoding type 4 is [CBOR](https://cbor.io/). CBOR is a binary encoding format that is a superset of JSON, and is both more compact and easier to parse in limited environments such as the EVM. Consumers that support CBOR are strongly encouraged to also support the [stringref extension](http://cbor.schmorp.de/stringref) to CBOR, which provides significant additional reduction in encoded size. - -Encoding type 8 indicates that the ABI can be found elsewhere, at the specified URI. This is typically the most compact of the supported forms, but also adds external dependencies for implementers. The specified URI may use any schema, but HTTP, IPFS, and Swarm are expected to be the most common. - -### Resolver profile -A new resolver interface is defined, consisting of the following method: - - function ABI(bytes32 node, uint256 contentType) constant returns (uint256, bytes); - -The interface ID of this interface is 0x2203ab56. - -contentType is a bitfield, and is the bitwise OR of all the encoding types the caller will accept. Resolvers that implement this interface must return an ABI encoded using one of the requested formats, or `(0, "")` if they do not have an ABI for this function, or do not support any of the requested formats. - -The `abi` resolver profile is valid on both forward and reverse records. - -### ABI lookup process - -When attempting to fetch an ABI based on an ENS name, implementers should first attempt an ABI lookup on the name itself. If that lookup returns no results, they should attempt a reverse lookup on the Ethereum address the name resolves to. - -Implementers should support as many of the ABI encoding formats as practical. - -## Rationale - -Storing ABIs onchain avoids the need to introduce additional dependencies for applications wishing to fetch them, such as swarm or HTTP access. Given the typical compactness of ABIs, we believe this is a worthwhile tradeoff in many cases. - -The two-step resolution process permits different names to provide different ABIs for the same contract, such as in the case where it's useful to provide a minimal ABI to some callers, as well as specifying ABIs for contracts that did not specify one of their own. The fallback to looking up an ABI on the reverse record permits contracts to specify their own canonical ABI, and prevents the need for duplication when multiple names reference the same contract without the need for different ABIs. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-205.md diff --git a/EIPS/eip-2070.md b/EIPS/eip-2070.md index 6ed8df9ad820e9..a3c30508a2d6ee 100644 --- a/EIPS/eip-2070.md +++ b/EIPS/eip-2070.md @@ -4,7 +4,7 @@ title: "Hardfork Meta: Berlin" author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/hardfork-meta-eip-2070-berlin-discussion/3561 type: Meta -status: Stagnant +status: Withdrawn created: 2019-05-20 requires: 1679 --- diff --git a/EIPS/eip-2098.md b/EIPS/eip-2098.md index f440b4057e7655..1fd5c74486e65e 100644 --- a/EIPS/eip-2098.md +++ b/EIPS/eip-2098.md @@ -1,138 +1,7 @@ --- eip: 2098 -title: Compact Signature Representation -description: A compact representation of an Ethereum Signature. -status: Final -type: Standards Track category: ERC -author: Richard Moore (@ricmoo), Nick Johnson -discussions-to: https://github.com/ethereum/EIPs/issues/2440 -created: 2019-03-14 -requires: 2 +status: Moved --- - -## Abstract - -The secp256k1 curve permits the computation of the public key of signed -digest when coupled with a signature, which is used implicitly to -establish the origin of a transaction from an Externally Owned Account -as well as on-chain in EVM contracts for example, in meta-transactions and -multi-sig contracts. - -Currently signatures require 65 bytes to represent, which when aligned -to 256-bit words, requires 96 bytes (with 31 zero bytes injected). The -yParity in RLP-encoded transactions also require (on average) 1.5 bytes. -With compact signatures, this can be reduced to 64 bytes, which remains 64 -bytes when word-aligned, and in the case of RLP-encoded transactions -saves the 1.5 bytes required for the yParity. - -## Motivation - -The motivations for a compact representation are to simplify handling -transactions in client code, reduce gas costs and reduce transaction sizes. - - -## Specification - -A secp256k1 signature is made up of 3 parameters, `r`, `s` and `yParity`. -The `r` represents the `x` component on the curve (from which the `y` can be -computed), and the `s` represents the challenge solution for signing by a -private key. Due to the symmetric nature of an elliptic curve, a `yParity` -is required, which indicates which of the 2 possible solutions was intended, -by indicating its parity (odd-ness). - -Two key observations are required to create a compact representation. - -First, the `yParity` parameter is always either 0 or 1 (canonically the values -used have historically been 27 and 28, as these values didn't collide with other -binary prefixes used in Bitcoin). - -Second, the top bit of the `s` parameters is **always** 0, due to the use of -canonical signatures which flip the solution parity to prevent negative values, -which was introduced as [a constraint in Homestead](./eip-2.md). - -So, we can hijack the top bit in the `s` parameter to store the value of -`yParity`, resulting in: - -``` -[256-bit r value][1-bit yParity value][255-bit s value] -``` - - -### Example Implementation In Python - -```python -# Assume yParity is 0 or 1, normalized from the canonical 27 or 28 -def to_compact(r, s, yParity): - return { - "r": r, - "yParityAndS": (yParity << 255) | s - } - -def to_canonical(r, yParityAndS): - return { - "r": r, - "s": yParityAndS & ((1 << 255) - 1), - "yParity": (yParityAndS >> 255) - } -``` - - -## Rationale - -The compact representation proposed is simple to both compose and decompose -in clients and in Solidity, so that it can be easily (and intuitively) supported, -while reducing transaction sizes and gas costs. - - -## Backwards Compatibility - -The Compact Representation does not collide with canonical signature as -it uses 2 parameters (r, yParityAndS) and is 64 bytes long while canonical -signatures involve 3 separate parameters (r, s, yParity) and are 65 bytes long. - - -## Test Cases - -``` -Private Key: 0x1234567890123456789012345678901234567890123456789012345678901234 -Message: "Hello World" -Signature: - r: 0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90 - s: 0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064 - v: 27 -Compact Signature: - r: 0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90 - yParityAndS: 0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064 -``` - -``` -Private Key: 0x1234567890123456789012345678901234567890123456789012345678901234 -Message: "It's a small(er) world" -Signature: - r: 0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76 - s: 0x139c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793 - v: 28 -Compact Signature: - r: 0x9328da16089fcba9bececa81663203989f2df5fe1faa6291a45381c81bd17f76 - yParityAndS: 0x939c6d6b623b42da56557e5e734a43dc83345ddfadec52cbe24d0cc64f550793 -``` - - -## Reference Implementation - -The ethers.js library [supports this in v5](https://github.com/ethers-io/ethers.js/blob/ethers-v5-beta/packages/bytes/src.ts/index.ts#L323) -as an unofficial property of split signatures (i.e. `sig._vs`), but should be -considered an internal property that may change at discretion of the community -and any changes to this EIP. - - -## Security Considerations - -There are no additional security concerns introduced by this EIP. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2098.md diff --git a/EIPS/eip-210.md b/EIPS/eip-210.md index ecb4e37fd6e7df..838c23021cc850 100644 --- a/EIPS/eip-210.md +++ b/EIPS/eip-210.md @@ -29,11 +29,11 @@ If `block.number >= CONSTANTINOPLE_FORK_BLKNUM`, then when processing a block, b * `GAS`: 1000000 * `TO`: BLOCKHASH_CONTRACT_ADDR * `VALUE`: 0 -* `DATA`: <32 bytes corresponding to the block's prevhash> +* `DATA`: <32 bytes corresponding to the block's prevhash> If `block.number >= CONSTANTINOPLE_FORK_BLKNUM + 256`, then the BLOCKHASH opcode instead returns the result of executing a call (NOT a transaction) with the parameters: -* `SENDER`: +* `SENDER`: <account from which the opcode was called> * `GAS`: 1000000 * `TO`: BLOCKHASH_CONTRACT_ADDR * `VALUE`: 0 diff --git a/EIPS/eip-2135.md b/EIPS/eip-2135.md index 811258895652f3..731777c2aea3e3 100644 --- a/EIPS/eip-2135.md +++ b/EIPS/eip-2135.md @@ -1,168 +1,7 @@ --- eip: 2135 -title: Consumable Interface (Tickets, etc) -description: An interface extending EIP-721 and EIP-1155 for consumability, supporting use case such as an event ticket. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/eip-2135-erc-consumable-interface/3439 -status: Last Call -last-call-deadline: 2023-02-01 -type: Standards Track category: ERC -created: 2019-06-23 -requires: 165, 721, 1155 +status: Moved --- -## Abstract - -This EIP defines an interface to mark a digital asset as "consumable" and to react to its "consumption." - -## Motivation - -Digital assets sometimes need to be consumaed. One of the most common examples is a concert ticket. -It is "consumed" when the ticket-holder enters the concert hall. - -Having a standard interface enables interoperability for services, clients, UI, and inter-contract functionalities on top of this use-case. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -1. Any compliant contract **MUST** implement the following interface: - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -/// The EIP-165 identifier of this interface is 0xdd691946 -interface IERC2135 { - /// @notice The consume function consumes a token every time it succeeds. - /// @param _consumer the address of consumer of this token. It doesn't have - /// to be the EOA or contract Account that initiates the TX. - /// @param _assetId the NFT asset being consumed - /// @param _data extra data passed in for consume for extra message - /// or future extension. - function consume( - address _consumer, - uint256 _assetId, - uint256 _amount, - bytes calldata _data - ) external returns (bool _success); - - /// @notice The interface to check whether an asset is consumable. - /// @param _consumer the address of consumer of this token. It doesn't have - /// to be the EOA or contract Account that initiates the TX. - /// @param _assetId the NFT asset being consumed. - /// @param _amount the amount of the asset being consumed. - function isConsumableBy( - address _consumer, - uint256 _assetId, - uint256 _amount - ) external view returns (bool _consumable); - - /// @notice The event emitted when there is a successful consumption. - /// @param consumer the address of consumer of this token. It doesn't have - /// to be the EOA or contract Account that initiates the TX. - /// @param assetId the NFT asset being consumed - /// @param amount the amount of the asset being consumed. - /// @param data extra data passed in for consume for extra message - /// or future extension. - event OnConsumption( - address indexed consumer, - uint256 indexed assetId, - uint256 amount, - bytes data - ); -} -``` - -2. If the compliant contract is an [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md) token, in addition to `OnConsumption`, it **MUST** also emit the `Transfer` / `TransferSingle` event (as applicable) as if a token has been transferred from the current holder to the zero address if the call to `consume` method succeeds. - -3. `supportsInterface(0xdd691946)` **MUST** return `true` for any compliant contract, as per [EIP-165](./eip-165.md). - -## Rationale - -1. The function `consume` performs the consume action. This EIP does not assume: - -- who has the power to perform consumption -- under what condition consumption can occur - -It does, however, assume the asset can be identified in a `uint256` asset id as in the parameter. A design convention and compatibility consideration is put in place to follow the EIP-721 pattern. - -2. The event notifies subscribers whoever are interested to learn an asset is being consumed. - -3. To keep it simple, this standard *intentionally* contains no functions or events related to the creation of a consumable asset. This is because the creation of a consumable asset will need to make assumptions about the nature of an actual use-case. If there are common use-cases for creation, another follow up standard can be created. - -4. Metadata associated to the consumables is not included the standard. If necessary, related metadata can be created with a separate metadata extension interface like `ERC721Metadata` from [EIP-721](./eip-721.md) - -5. We choose to include an `address consumer` for `consume` function and `isConsumableBy` so that an NFT MAY be consumed for someone other than the transaction initiator. - -6. We choose to include an extra `_data` field for future extension, such as -adding crypto endorsements. - -7. We explicitly stay opinion-less about whether EIP-721 or EIP-1155 shall be required because -while we design this EIP with EIP-721 and EIP-1155 in mind mostly, we don't want to rule out -the potential future case someone use a different token standard or use it in different use cases. - -8. The boolean view function of `isConsumableBy` can be used to check whether an asset is -consumable by the `_consumer`. - -## Backwards Compatibility - -This interface is designed to be compatible with EIP-721 and NFT of EIP-1155. It can be tweaked to used for [EIP-20](./eip-20.md), [EIP-777](./eip-777.md) and Fungible Token of EIP-1155. - -## Test Cases - -```ts - - describe("Consumption", function () { - it("Should consume when minted", async function () { - const fakeTokenId = "0x1234"; - const { contract, addr1 } = await loadFixture(deployFixture); - await contract.safeMint(addr1.address, fakeTokenId); - expect(await contract.balanceOf(addr1.address)).to.equal(1); - expect(await contract.ownerOf(fakeTokenId)).to.equal(addr1.address); - expect(await contract.isConsumableBy(addr1.address, fakeTokenId, 1)).to.be.true; - const tx = await contract.consume(addr1.address, fakeTokenId, 1, []); - const receipt = await tx.wait(); - const events = receipt.events.filter((x: any) => { return x.event == "OnConsumption" }); - expect(events.length).to.equal(1); - expect(events[0].args.consumer).to.equal(addr1.address); - expect(events[0].args.assetId).to.equal(fakeTokenId); - expect(events[0].args.amount).to.equal(1); - expect(await contract.balanceOf(addr1.address)).to.equal(0); - await expect(contract.ownerOf(fakeTokenId)) - .to.be.rejectedWith('ERC721: invalid token ID'); - await expect(contract.isConsumableBy(addr1.address, fakeTokenId, 1)) - .to.be.rejectedWith('ERC721: invalid token ID'); - }); - }); - - describe("EIP-165 Identifier", function () { - it("Should match", async function () { - const { contract } = await loadFixture(deployFixture); - expect(await contract.get165()).to.equal("0xdd691946"); - expect(await contract.supportsInterface("0xdd691946")).to.be.true; - }); - }); -``` - -## Reference Implementation - -A deployment of version 0x1002 has been deployed onto `goerli` testnet at address `0x3682bcD67b8A5c0257Ab163a226fBe07BF46379B`. - -Find the reference contract verified source code on Etherscan's -`goerli` site for the address above. - -## Security Considerations - -Compliant contracts should pay attention to the balance change when a token is consumed. -When the contract is being paused, or the user is being restricted from transferring a token, -the consumeability should be consistent with the transferral restriction. - -Compliant contracts should also carefully define access control, particularlly whether any EOA or contract account may or may not initiate a `consume` method in their own use case. - -Security audits and tests should be used to verify that the access control to the `consume` -function behaves as expected. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2135.md diff --git a/EIPS/eip-2157.md b/EIPS/eip-2157.md index 47481224e37605..0a6c2541e17816 100644 --- a/EIPS/eip-2157.md +++ b/EIPS/eip-2157.md @@ -1,136 +1,7 @@ --- eip: 2157 -title: dType Storage Extension - Decentralized Type System for EVM -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/2157 -status: Stagnant -type: Standards Track category: ERC -created: 2019-06-28 -requires: 1900 +status: Moved --- -## Simple Summary - -This ERC is an extension of ERC-1900, proposing an optional storage extension for dType, a decentralized type system, specifying a general ABI for all storage contracts that contain type instances. - -## Abstract - -The storage extension will enable easy navigation and retrieval of type data that is intended to be of public use. This is possible through standardizing the ABI of the dType storage contracts, with the effect of having a deterministic path to a type instance record. This standardization enables a more effective on-chain and off-chain use of data and opens up possibilities for decentralized applications, enabling developers to build on top of public global data. - -## Motivation - -Currently, Ethereum does not have standardization of data addressability. This might not be needed for data that is meant to be quasi-private, however, it is needed for data that is meant for public consumption. ERC-1900 has started standardizing data types for increasing interoperability between projects, but this is not enough if we want to build a global ecosystem. Deterministic data addressability will enable anyone to build upon the same public data sets, off-chain or on-chain. - -It is true that with ERC-1900, blockchain data analysis and type-specific data retrieval will be possible off-chain, but this implies relying on centralized data caches (blockchain explorers) or maintaining your own data cache. Moreover, this option does not allow on-chain standardization on data retrieval paths, therefore limiting the type of on-chain interoperable operations that can be done. - -Having a clear way of retrieving data, instead of analyzing the blockchain for contracts that have a certain type in their ABI or bytecode, will make development easier and more decentralized for applications that target global data on specific types. - -For example, a decentralized market place can be built on top of some marketplace-specific types, and by knowing exactly where the type data is stored, it is easy to create custom algorithms that provide the user with the product information they seek. Everyone has access to the data and the data path is standardized. - -Moreover, by standardizing storage contract interfaces, ABI inference is possible. The common interface, together with the dType registry will provide all the data needed to reconstruct the ABI. - -This system can be extended with access and mutability control later on, in a future proposal. Access and mutability control will be necessary for public-use global systems. Moreover, we can have a homogeneous application of permissions across system components. This is not detailed in the present proposal. - -Another use case is data bridges between Ethereum shards or between Ethereum and other chains. Data syncing between shards/chains can be done programmatically, across data types (from various projects). Imagine a user having a public profile/identity contract on one chain, wishing to move that profile on Ethereum. By supporting the origin chain types and having a standardized storage mechanism, data moving processes will be the same. - -This pattern of separating data type definitions and storage allows developers to create functional programming-like patterns on Ethereum, even though languages such as Solidity are not functional. - -## Specification - -### TypeRootContract - -ERC-1900 defines a `contractAddress` field in the type metadata. For the limited purpose of ERC-1900, this field contains the value of the Ethereum type library in which the type definition exists. For the purpose of this ERC, the `contractAddress` will contain the Etherereum address of a `TypeRootContract`. - -```solidity -contract TypeRootContract { - address public libraryAddress; - address public storageAddress; - - constructor(address _library, address _storage) public { - libraryAddress = _library; - storageAddress = _storage; - } -} -``` - -- `libraryAddress` - Ethereum address of the type definition library, from ERC-1900 -- `storageAddress` - Ethereum address of the type data storage contract - - -### TypeStorageContract - -This contract will use the type library to define the internal data stored in it. Each record will be a type instance, addressable by a primary identifier. The primary identifier is calculated by the type library's `getIdentifier` function, based on the type instance values. - -We propose a Solidity CRUD pattern, as described in https://medium.com/robhitchens/solidity-crud-part-1-824ffa69509a, where records can also be retrieved using their index - a monotonically increasing counter. - -An stub implementation for the TypeStorageContract would look like: - -```solidity -import './TypeALib.sol'; - -contract TypeAStorage { - using TypeALib for TypeALib.TypeA; - - bytes32[] public typeIndex; - mapping(bytes32 => Type) public typeStruct; - - struct Type { - TypeALib.TypeA data; - uint256 index; - } - - event LogNew(bytes32 indexed identifier, uint256 indexed index); - event LogUpdate(bytes32 indexed identifier, uint256 indexed index); - event LogRemove(bytes32 indexed identifier, uint256 indexed index); - - function insert(TypeALib.TypeA memory data) public returns (bytes32 identifier); - - function insertBytes(bytes memory data) public returns (bytes32 identifier); - - function remove(bytes32 identifier) public returns(uint256 index); - - function update(bytes32 identifier, TypeALib.TypeA memory data) public returns(bytes32 identifier) - - function isStored(bytes32 identifier) public view returns(bool stored); - - function getByHash(bytes32 identifier) public view returns(TypeALib.TypeA memory data); - - function getByIndex(uint256 index) public view returns(TypeALib.TypeA memory data); - - function count() public view returns(uint256 counter); -} -``` - -## Rationale - -We are now thinking about a building block as a smart contract with an encapsulated object that contains state changing functions that are only understood from within. This is more akin to Object-Oriented Programming and poses interoperability and scalability issues. Not necessarily for an individual project, but for a global Ethereum OS. This is why we are proposing to separate data from business logic and data structure definitions. - -When you have public aggregated data, categorized on each type, anyone can build tools on top of it. This is a radical change from the closed or dispersed data patterns that we find in web2. - -We have chosen to define a `TypeRootContract` instead of extending the dType registry with fields for the TypeStorage contract, because this approach enables easier interface updates in the future. It is more extensible. - -The storage pattern used for dType itself and all the Type Storage contracts can be the same. This lowers the cost of building, testing and auditing the code. - -The `TypeStorageContract` pattern should ensure: -- type instance addressability by the primary identifier -- a way to retrieve all records from the contract -- counting the number of records - - -## Backwards Compatibility - -This proposal does not affect existent Ethereum standards or implementations. It uses the present experimental version of ABIEncoderV2. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/tree/master/contracts/contracts. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2157.md diff --git a/EIPS/eip-2193.md b/EIPS/eip-2193.md index 34152793a68686..a27b4aa888bb95 100644 --- a/EIPS/eip-2193.md +++ b/EIPS/eip-2193.md @@ -1,92 +1,7 @@ --- eip: 2193 -title: dType Alias Extension - Decentralized Type System -author: Loredana Cirstea (@loredanacirstea), Christian Tzurcanu (@ctzurcanu) -discussions-to: https://github.com/ethereum/EIPs/issues/2192 -status: Stagnant -type: Standards Track category: ERC -created: 2019-07-16 -requires: 155, 1900, 2157 +status: Moved --- -## Simple Summary - -We are proposing Alias - a semantic standard for identifying on-chain resources by human-readable qualifiers, supporting any type of data. - -## Abstract - -The dType Alias is a system for providing human-readable resource identifiers to on-chain content. A resource identifier is based on the type of data (identifier provided by dType, [EIP-1900](./eip-1900.md)) and the data content (identifier provided by a dType Storage Contract, [EIP-2157](./eip-2157.md)). It is a universal way of addressing content, supporting any type of data. - -## Motivation - -There are standards that currently address the need for attaching human-readable identifiers to Ethereum accounts, such as [EIP-137](./eip-137.md). These standards are an attempt to bring domain names to Ethereum, following the same format as DNS: `subdomain.domain.tld`. This leaf -> root format is unintuitive and contradicts the semantic meaning that `.` has in programming languages, which is a root -> leaf connection (e.g. in OOP, when accessing an object's property). A more intuitive and widely used approach is a root->leaf format, used in file browsers, hierarchical menus, and even in other decentralized systems, which give unique identifiers to resources (e.g. `0x56.Currency.TCoin` in [Libra](https://medium.com/r/?url=https%3A%2F%2Fdevelopers.libra.org). - -Moreover, [EIP-137](./eip-137.md) is not flexible enough to address smart contract content, which can contain heterogeneous data that belongs to various accounts. For example, a `PaymentChannel` smart contract can have an domain name. However, the `Alice-Bob` channel data from inside the smart contract, cannot have a subdomain name. Having uniquely identified, granular resources opens the way to creating both human and machine-readable protocols on top of Ethereum. It also provides a basis for protocols based on functional programming. - -This ERC proposes a set of separators which maintain their semantic meaning and provides a way to address any type of resource - from Ethereum addresses, to individual `struct` instances inside smart contracts. - -Imagine the following dType types: `SocialNetwork` and `Profile`, with related storage data about user profiles. One could access such a profile using an alias for the data content: `alice@socialnetwork.profile`. For a `PaymentChannel` type, Alice can refer to her channel with Bob with `alice-bob.paymentchannel`. -This alias system can be used off-chain, to replace the old DNS system with a deterministic and machine-readable way of displaying content, based on the dType type's metadata. - -## Specification - -The dType registry will provide domain and subdomain names for the resource type. Subdomains can be attributed recursively, to dType types which contain other complex types in their composition. - -We define an `Alias` registry contract, that keeps track of the human-readable identifiers for data resources, which exist in dType storage contracts. -Anyone can set an alias in the `Alias` registry, as long as the Ethereum address that signs the alias data has ownership on the resource, in the dType storage contract. Storage contract data ownership will be detailed in [EIP-2157](./eip-2157.md). An owner can update or delete an alias at any time. - -```solidity -interface Alias { - - event AliasSet(bytes32 dtypeIdentifier, bytes1 separator, string name, bytes32 indexed identifier); - - function setAlias(bytes32 dtypeIdentifier, bytes1 separator, string memory name, bytes32 identifier, bytes memory signature) external; - - function getAliased(bytes1 separator, string memory name) view external returns (bytes32 identifier); -} -``` - -- `dtypeIdentifier`: Type identifier from the dType registry, needed to ensure uniqueness of `name` for a dType type. `dtypeIdentifier` is checked to see if it exists in the dType registry. The dType registry also links the type's data storage contract, where the existence and ownership of the `identifier` is checked. -- `name`: user-defined human-readable name for the resource referenced by `identifier` -- `separator`: Character acting as a separator between the name and the rest of the alias. Allowed values: - - `.`: general domain separation, using root->leaf semantics. E.g. `domain.subdomain.leafsubdomain.resource` - - `@`: identifying actor-related data, such as user profiles, using leaf->root semantics. E.g. `alice@socialnetwork.profile` or `alice@dao@eth` - - `#`: identifying concepts, using root->leaf semantics. E.g. `topicX#postY` - - `/`: general resource path definition, using root->leaf semantics. E.g. `resourceRoot/resource` -- `identifier`: Resource identifier from a smart contract linked with dType -- `signature`: Alias owner signature on `dtypeIdentifier`, `identifier`, `name`, `separator`, `nonce`, `aliasAddress`, `chainId`. - - `nonce`: monotonically increasing counter, used to prevent replay attacks - - `aliasAddress`: Ethereum address of `Alias` contract - - `chainId`: chain on which the `Alias` contract is deployed, as detailed in [EIP-155](./eip-155.md), used to prevent replay attacks when updating the `identifier` for an alias. - -Content addressability can be done: -- using the `bytes32` identifiers directly, e.g. `0x0b5e76559822448f6243a6f76ac7864eba89c810084471bdee2a63429c92d2e7@0x9dbb9abe0c47484c5707699b3ceea23b1c2cca2ac72681256ab42ae01bd347da` -- using the human identifiers, e.g. `alice@socialnetwork` - -Both of the above examples will resolve to the same content. - - -## Rationale - -Current attempts to solve content addressability, such as [EIP-137](./eip-137.md), only target Ethereum accounts. These are based on inherited concepts from HTTP and DNS, which are not machine friendly. - -With [EIP-1900](./eip-1900.md) and [EIP-2157](./eip-2157.md), general content addressability can be achieved. dType provides type information and a reference to the smart contract where the type instances are stored. Additionally, Alias uses the semantic meaning of subdomain separators to have a [intuitive order rule](https://github.com/loredanacirstea/articles/blob/master/articles/Flexible_Alias_or_Why_ENS_is_Obsolete.md). - -Multiple aliases can be assigned to a single resource. Either by using a different `name` or by using a different `separator`. Each `separator` can have a specific standard for displaying and processing data, based on its semantic meaning. - -## Backwards Compatibility - -Will be added. - -## Test Cases - -Will be added. - -## Implementation - -An in-work implementation can be found at https://github.com/pipeos-one/dType/blob/master/contracts/contracts/Alias.sol. -This proposal will be updated with an appropriate implementation when consensus is reached on the specifications. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2193.md diff --git a/EIPS/eip-223.md b/EIPS/eip-223.md new file mode 100644 index 00000000000000..6096d61cbca7c3 --- /dev/null +++ b/EIPS/eip-223.md @@ -0,0 +1,7 @@ +--- +eip: 223 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-223.md diff --git a/EIPS/eip-225.md b/EIPS/eip-225.md index ce084a71779698..2dce2e16cca8e2 100644 --- a/EIPS/eip-225.md +++ b/EIPS/eip-225.md @@ -146,7 +146,7 @@ To authorize a block for the network, the signer needs to sign the block's sigha The sighash is signed using the standard `secp256k1` curve, and the resulting 65 byte signature (`R`, `S`, `V`, where `V` is `0` or `1`) is embedded into the `extraData` as the trailing 65 byte suffix. -To ensure malicious signers (loss of signing key) cannot wreck havoc in the network, each singer is allowed to sign **maximum one** out of **`SIGNER_LIMIT`** consecutive blocks. The order is not fixed, but in-turn signing weighs more (**`DIFF_INTURN`**) than out of turn one (**`DIFF_NOTURN`**). +To ensure malicious signers (loss of signing key) cannot wreck havoc in the network, each signer is allowed to sign **maximum one** out of **`SIGNER_LIMIT`** consecutive blocks. The order is not fixed, but in-turn signing weighs more (**`DIFF_INTURN`**) than out of turn one (**`DIFF_NOTURN`**). #### Authorization strategies diff --git a/EIPS/eip-2255.md b/EIPS/eip-2255.md index 324b09c988d708..14d31a8f67727d 100644 --- a/EIPS/eip-2255.md +++ b/EIPS/eip-2255.md @@ -2,9 +2,9 @@ eip: 2255 title: Wallet Permissions System description: An interface to restrict access to sensitive methods -author: Dan Finlay (@danfinlay), Erik Marks (@rekmarks), Pandapip1 (@Pandapip1) +author: Dan Finlay (@danfinlay), Erik Marks (@rekmarks), Gavin John (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/web3-login-permissions/3583 -status: Review +status: Final type: Standards Track category: Interface created: 2019-08-22 @@ -140,7 +140,11 @@ provider.request({ ## Security Considerations -Needs discussion. +### Server-Side Request Forgery (SSRF) + +This consideration is applicable if the favicon of a website is to be displayed. + +Wallets should be careful about making arbitrary requests to URLs. As such, it is recommended for wallets to sanitize the URI by whitelisting specific schemes and ports. A vulnerable wallet could be tricked into, for example, modifying data on a locally-hosted redis database. ## Copyright diff --git a/EIPS/eip-2266.md b/EIPS/eip-2266.md index 2489d320f18ec3..ae3e2df3601021 100644 --- a/EIPS/eip-2266.md +++ b/EIPS/eip-2266.md @@ -1,252 +1,7 @@ --- eip: 2266 -title: Atomic Swap-based American Call Option Contract Standard -author: Runchao Han , Haoyu Lin , Jiangshan Yu -discussions-to: https://github.com/ethereum/EIPs/issues/2266 -status: Last Call -type: Standards Track category: ERC -created: 2019-08-17 -last-call-deadline: 2020-12-31 +status: Moved --- -## Simple Summary - -A standard for token contracts providing Atomic Swap-based American Call Option functionalities. - -## Abstract - -This standard provides functionality to make Atomic Swap-based American Call Option payment. The Atomic Swap protocol based on Hashed Time-Locked Contract (HTLC) [^1] has optionality [^2], and such optionality can be utilised to construct American Call Options without trusted third party. This standard defines the common way of implementing this protocol. In particular, this EIP defines technical terms, provides interfaces, and gives reference implementations of this protocol. - - -## Motivation - -Atomic Swap allows users to atomically exchange their tokens without trusted third parties while the HTLC is commonly used for the implementation. However, the HTLC-based Atomic Swap has optionality. More specifically, the swap initiator can choose to proceed or abort the swap for several hours, which gives him time for speculating according to the exchange rate. A discussion[^2] shows that the HTLC-based Atomic Swap is equivalent to an American Call Option in finance. On the other hand,thanks to such optionality, the HTLC-based Atomic Swap can be utilised to construct American Call Options without trusted third party. A paper[^3] proposes a secure Atomic-Swap-based American Call Option protocol on smart contracts. This protocol not only eliminates the arbitrage opportunity but also prevents any party from locking the other party's money maliciously. This EIP aims at providing the standard of implementing this protocol in existing token standards. - -## Specification - -The Atomic Swap-based American Call Option smart contract should follow the syntax and semantics of Ethereum smart contracts. - -### Definitions - -+ `initiator`: the party who publishes the advertisement of the swap. -+ `participant`: the party who agrees on the advertisement and participates in the swap with `initiator`. -+ `asset`: the amount of token(s) to be exchanged. -+ `premium`: the amount of token(s) that `initiator` pays to `participant` as the premium. -+ `redeem`: the action to claim the token from the other party. -+ `refund`: the action to claim the token from the party herself/himself, because of timelock expiration. -+ `secrect`: a random string chosen by `initiator` as the preimage of a hash. -+ `secrectHash`: a string equals to the hash of `secrect`, used for constructing HTLCs. -+ `timelock`: a timestamp representing the timelimit, before when the asset can be redeemed, and otherwise can only be refunded. - -### Storage Variables - -#### swap - -This mapping stores the metadata of the swap contracts, including the parties and tokens involved. Each contract uses different `secretHash`, and is distinguished by `secretHash`. - -```solidity -mapping(bytes32 => Swap) public swap; -``` - -#### initiatorAsset - -This mapping stores the detail of the asset initiators want to sell, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => InitiatorAsset) public initiatorAsset; -``` - -#### participantAsset - -This mapping stores the details of the asset participants want to sell, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => ParticipantAsset) public participantAsset; -``` - -#### premiumAsset - -This mapping stores the details of the premium initiators attach in the swap contract, including the amount, the timelock and the state. It is associated with the swap contract with the same `secretHash`. - -```solidity -mapping(bytes32 => Premium) public premium; -``` - - -### Methods - -#### setup - -This function sets up the swap contract, including the both parties involved, the tokens to exchanged, and so on. - -```solidity -function setup(bytes32 secretHash, address payable initiator, address tokenA, address tokenB, uint256 initiatorAssetAmount, address payable participant, uint256 participantAssetAmount, uint256 premiumAmount) public payable -``` - -#### initiate - -The initiator invokes this function to fill and lock the token she/he wants to sell and join the contract. - -```solidity -function initiate(bytes32 secretHash, uint256 assetRefundTime) public payable -``` - -#### fillPremium - -The initiator invokes this function to fill and lock the premium. - -```solidity -function fillPremium(bytes32 secretHash, uint256 premiumRefundTime) public payable -``` - -#### participate - -The participant invokes this function to fill and lock the token she/he wants to sell and join the contract. - -```solidity -function participate(bytes32 secretHash, uint256 assetRefundTime) public payable -``` - -#### redeemAsset - -One of the parties invokes this function to get the token from the other party, by providing the preimage of the hash lock `secret`. - -```solidity -function redeemAsset(bytes32 secret, bytes32 secretHash) public -``` - -#### refundAsset - -One of the parties invokes this function to get the token back after the timelock expires. - -```solidity -function refundAsset(bytes32 secretHash) public -``` - -#### redeemPremium - -The participant invokes this function to get the premium. This can be invoked only if the participant has already invoked `participate` and the participant's token is redeemed or refunded. - -```solidity -function redeemPremium(bytes32 secretHash) public -``` - -#### refundPremium - -The initiator invokes this function to get the premium back after the timelock expires. - -```solidity -function refundPremium(bytes32 secretHash) public -``` - - -### Events - -#### SetUp - -This event indicates that one party has set up the contract using the function `setup()`. - -```solidity -event SetUp(bytes32 secretHash, address initiator, address participant, address tokenA, address tokenB, uint256 initiatorAssetAmount, uint256 participantAssetAmount, uint256 premiumAmount); -``` - -#### Initiated - -This event indicates that `initiator` has filled and locked the token to be exchanged using the function `initiate()`. - -```solidity -event Initiated(uint256 initiateTimestamp, bytes32 secretHash, address initiator, address participant, address initiatorAssetToken, uint256 initiatorAssetAmount, uint256 initiatorAssetRefundTimestamp); -``` - -#### Participated - -This event indicates that `participant` has filled and locked the token to be exchanged using the function `participate()`. - -```solidity -event Participated(uint256 participateTimestamp, bytes32 secretHash, address initiator, address participant, address participantAssetToken, uint256 participantAssetAmount, uint256 participantAssetRefundTimestamp); -``` - -#### PremiumFilled - -This event indicates that `initiator` has filled and locked `premium` using the function `fillPremium()`. - -```solidity -event PremiumFilled(uint256 fillPremiumTimestamp, bytes32 secretHash, address initiator, address participant, address premiumToken, uint256 premiumAmount, uint256 premiumRefundTimestamp); -``` - -#### InitiatorAssetRedeemed/ParticipantAssetRedeemed - -These two events indicate that `asset` has been redeemed by the other party before the timelock by providing `secret`. - -```solidity -event InitiatorAssetRedeemed(uint256 redeemTimestamp, bytes32 secretHash, bytes32 secret, address redeemer, address assetToken, uint256 amount); -``` - -```solidity -event ParticipantAssetRedeemed(uint256 redeemTimestamp, bytes32 secretHash, bytes32 secret, address redeemer, address assetToken, uint256 amount); -``` - -#### InitiatorAssetRefunded/ParticipantAssetRefunded - -These two events indicate that `asset` has been refunded by the original owner after the timelock expires. - -```solidity -event InitiatorAssetRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address assetToken, uint256 amount); -``` - -```solidity -event ParticipantAssetRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address assetToken, uint256 amount); -``` - -#### PremiumRedeemed - -This event indicates that `premium` has been redeemed by `participant`. This implies that `asset` is either redeemed by `initiator` if it can provide the preimage of `secrectHash` before `asset` timelock expires; or refunded by `participant` if `asset` timelock expires. - -```solidity -event PremiumRedeemed(uint256 redeemTimestamp,bytes32 secretHash,address redeemer,address token,uint256 amount); -``` - -#### PremiumRefunded - -This event indicates that `premium` has been refunded back to `initiator`, because of `participant` doesn't participate at all, by the time of `premium` timelock expires. - -```solidity -event PremiumRefunded(uint256 refundTimestamp, bytes32 secretHash, address refunder, address token, uint256 amount); -``` - -## Rationale - -+ To achieve the atomicity, HTLC is used. -+ The participant should decide whether to participate after the initiator locks the token and sets up the timelock. -+ The initiator should decide whether to proceed the swap (redeem the tokens from the participant and reveal the preimage of the hash lock), after the participant locks the tokens and sets up the time locks. -+ Premium is redeemable for the participant only if the participant participates in the swap and redeems the initiator's token before premium's timelock expires. -+ Premium is refundable for the initiator only if the initiator initiates but the participant does not participate in the swap at all. - - -## Security Considerations - -+ The `initiateTimestamp` should cover the whole swap process. -+ The participant should never participate before the premium has been deposited. - - -## Backwards Compatibility - -This proposal is fully backward compatible. Functionalities of existing standards will not be affected by this proposal, as it only provides additional features to them. - - -## Implementation - -Please visit [here](../assets/eip-2266/Example.sol) to find our example implementation. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - -## References - -[^1]: [Hash Time Locked Contracts](https://en.bitcoin.it/wiki/Hash_Time_Locked_Contracts) - -[^2]: [An Argument For Single-Asset Lightning Network](https://lists.linuxfoundation.org/pipermail/lightning-dev/2019-January/001798.html) - -[^3]: [On the optionality and fairness of Atomic Swaps](https://eprint.iacr.org/2019/896) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2266.md diff --git a/EIPS/eip-2294.md b/EIPS/eip-2294.md index 9837e6ad5dc67c..511705388cf948 100644 --- a/EIPS/eip-2294.md +++ b/EIPS/eip-2294.md @@ -4,7 +4,7 @@ title: Explicit bound to Chain ID size description: Adds a maximum value to the Chain ID parameter to avoid potential encoding issues that may occur when using large values of the parameter. author: Zainan Victor Zhou (@xinbenlv), Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-2294-explicit-bound-to-chain-id/11090 -status: Review +status: Stagnant type: Standards Track category: Core created: 2019-09-19 diff --git a/EIPS/eip-2304.md b/EIPS/eip-2304.md index 16a550edad50c9..5dadd8d6646379 100644 --- a/EIPS/eip-2304.md +++ b/EIPS/eip-2304.md @@ -1,219 +1,7 @@ --- eip: 2304 -title: Multichain address resolution for ENS -author: Nick Johnson -type: Standards Track category: ERC -status: Stagnant -created: 2019-09-09 -discussions-to: https://discuss.ens.domains/t/new-standard-proposal-ens-multicoin-support/1148 -requires: 137 +status: Moved --- -## Abstract - -This EIP introduces new overloads for the the `addr` field for ENS resolvers, which permit resolution of addresses for other blockchains via ENS. - -## Motivation - -With the increasing uptake of ENS by multi-coin wallets, wallet authors have requested the ability to resolve addresses for non-Ethereum chains inside ENS. This specification standardises a way to enter and retrieve these addresses in a cross-client fashion. - -## Specification - -A new accessor function for resolvers is specified: - -```solidity -function addr(bytes32 node, uint coinType) external view returns(bytes memory); -``` - -The EIP165 interface ID for this function is 0xf1cb7e06. - -When called on a resolver, this function must return the cryptocurrency address for the specified namehash and coin type. A zero-length string must be returned if the specified coin ID does not exist on the specified node. - -`coinType` is the cryptocurrency coin type index from [SLIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md). - -The return value is the cryptocurency address in its native binary format. Detailed descriptions of the binary encodings for several popular chains are provided in the Address Encoding section below. - -A new event for resolvers is defined: - -```solidity -event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); -``` - -Resolvers MUST emit this event on each change to the address for a name and coin type. - -### Recommended accessor functions - -The following function provides the recommended interface for changing the addresses stored for a node. Resolvers SHOULD implement this interface for setting addresses unless their needs dictate a different interface. - -```solidity -function setAddr(bytes32 node, uint coinType, bytes calldata addr); -``` - -`setAddr` adds or replaces the address for the given node and coin type. The parameters for this function are as per those described in `addr()` above. - -This function emits an `AddressChanged` event with the new address; see also the backwards compatibility section below for resolvers that also support `addr(bytes32)`. - -### Address Encoding - -In general, the native binary representation of the address should be used, without any checksum commonly used in the text representation. - -A table of encodings for common blockchains is provided, followed by a more detailed description of each format. In the table, 'encodings' lists the address encodings supported by that chain, along with any relevant parameters. Details of those address encodings are described in the following sections. - -| Cryptocurrency | Coin Type | Encoding | -| --- | --- | --- | -| Bitcoin | 0 | P2PKH(0x00), P2SH(0x05), SegWit('bc') | -| Litecoin | 2 | P2PKH(0x30), P2SH(0x32), P2SH(0x05), SegWit('ltc') | -| Dogecoin | 3 | P2PKH(0x1e), P2SH(0x16) | -| Monacoin | 22 | P2PKH(0x32), P2SH(0x05) | -| Ethereum | 60 | ChecksummedHex | -| Ethereum Classic | 61 | ChecksummedHex | -| Rootstock | 137 | ChecksummedHex(30) | -| Ripple | 144 | Ripple | -| Bitcoin Cash | 145 | P2PKH(0x00), P2SH(0x05), CashAddr | -| Binance | 714 | Bech32('bnb') | - -#### P2PKH(version) - -Pay to Public Key Hash addresses are [base58check](https://en.bitcoin.it/wiki/Base58Check_encoding) encoded. After decoding, the first byte is a version byte. For example, the Bitcoin address `1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa` base58check decodes to the 21 bytes `0062e907b15cbf27d5425399ebf6f0fb50ebb88f18`. - -P2PKH addresses have a version byte, followed by a 20 byte pubkey hash. Their canonical encoding is their scriptPubkey encoding (specified [here](https://en.bitcoin.it/wiki/Transaction#Types_of_Transaction)) is `OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG`. - -The above example address is thus encoded as the 25 bytes `76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac`. - -##### P2SH(version) - -P2SH addresses are base58check encoded in the same manner as P2PKH addresses. -P2SH addresses have a version, followed by a 20 byte script hash. Their scriptPubkey encoding (specified [here](https://en.bitcoin.it/wiki/Transaction#Pay-to-Script-Hash)) is `OP_HASH160 OP_EQUAL`. A Bitcoin address of `3Ai1JZ8pdJb2ksieUV8FsxSNVJCpoPi8W6` decodes to the 21 bytes `0562e907b15cbf27d5425399ebf6f0fb50ebb88f18` and is encoded as the 23 bytes `a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1887`. - -##### SegWit(hrp) - -SegWit addresses are encoded with [bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki). Bech32 addresses consist of a human-readable part - 'bc' for Bitcoin mainnet - and a machine readable part. For SegWit addresses, this decodes to a 'witness version', between 0 and 15, and a 'witness program', as defined in [BIP141](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki). - -The scriptPubkey encoding for a bech32 address, as defined in BIP141, is `OP_n`, where `n` is the witness version, followed by a push of the witness program. Note this warning from BIP173: - -> Implementations should take special care when converting the address to a scriptPubkey, where witness version n is stored as OP_n. OP_0 is encoded as 0x00, but OP_1 through OP_16 are encoded as 0x51 though 0x60 (81 to 96 in decimal). If a bech32 address is converted to an incorrect scriptPubKey the result will likely be either unspendable or insecure. - -For example, the Bitcoin SegWit address `BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4` decodes to a version of `0` and a witness script of `751e76e8199196d454941c45d1b3a323f1433bd6`, and then encodes to a scriptPubkey of `0014751e76e8199196d454941c45d1b3a323f1433bd6`. - -#### ChecksummedHex(chainId?) - -To translate a text format checksummed hex address into binary format, simply remove the '0x' prefix and hex decode it. `0x314159265dD8dbb310642f98f50C066173C1259b` is hex-decoded and stored as the 20 bytes `314159265dd8dbb310642f98f50c066173c1259b`. - -A checksum format is specified by [EIP-55](./eip-55.md), and extended by [RSKIP60](https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md), which specifies a means of including the chain ID in the checksum. The checksum on a text format address must be checked. Addresses with invalid checksums that are not all uppercase or all lowercase MUST be rejected with an error. Implementations may choose whether to accept non-checksummed addresses, but the authors recommend at least providing a warning to users in this situation. - -When encoding an address from binary to text, an EIP55/RSKIP60 checksum MUST be used - so the correct encoding of the above address for Ethereum is `0x314159265dD8dbb310642f98f50C066173C1259b`. - -#### Ripple - -Ripple addresses are encoded using a version of base58check with an alternative alphabet, described [here](https://xrpl.org/base58-encodings.html). Two types of ripple addresses are supported, 'r-addresses', and 'X-addresss'. r-addresses consist of a version byte followed by a 20 byte hash, while X-addresses consist of a version byte, a 20 byte hash, and a tag, specified [here](https://github.com/xrp-community/standards-drafts/issues/6). - -Both address types should be stored in ENS by performing ripple's version of base58check decoding and storing them directly (including version byte). For example, the ripple address `rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn` decodes to and is stored as `004b4e9c06f24296074f7bc48f92a97916c6dc5ea9`, while the address `X7qvLs7gSnNoKvZzNWUT2e8st17QPY64PPe7zriLNuJszeg` decodes to and is stored as `05444b4e9c06f24296074f7bc48f92a97916c6dc5ea9000000000000000000`. - -#### CashAddr - -Bitcoin Cash defines a new address format called 'CashAddr', specified [here](https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md). This uses a variant of bech32 encoding to encode and decode (non-segwit) Bitcoin Cash addresses, using a prefix of 'bitcoincash:'. A CashAddr should be decoded using this bech32 variant, then converted and stored based on its type (P2PKH or P2SH) as described in the relevant sections above. - -#### Bech32 - -[Bech32](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) addresses consist of a human-readable part - for example, 'bnb' for Binance - and a machine readable part. The encoded data is simply the address, which can be converted to binary and stored directly. - -For example, the BNB address `bnb1grpf0955h0ykzq3ar5nmum7y6gdfl6lxfn46h2` decodes to the binary representation `40c2979694bbc961023d1d27be6fc4d21a9febe6`, which is stored directly in ENS. - -### Example - -An example implementation of a resolver that supports this EIP is provided here: - -```solidity -pragma solidity ^0.5.8; - -contract AddrResolver is ResolverBase { - bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; - bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; - uint constant private COIN_TYPE_ETH = 60; - - event AddrChanged(bytes32 indexed node, address a); - event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); - - mapping(bytes32=>mapping(uint=>bytes)) _addresses; - - /** - * Sets the address associated with an ENS node. - * May only be called by the owner of that node in the ENS registry. - * @param node The node to update. - * @param a The address to set. - */ - function setAddr(bytes32 node, address a) external authorised(node) { - setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); - } - - /** - * Returns the address associated with an ENS node. - * @param node The ENS node to query. - * @return The associated address. - */ - function addr(bytes32 node) public view returns (address) { - bytes memory a = addr(node, COIN_TYPE_ETH); - if(a.length == 0) { - return address(0); - } - return bytesToAddress(a); - } - - function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { - emit AddressChanged(node, coinType, a); - if(coinType == COIN_TYPE_ETH) { - emit AddrChanged(node, bytesToAddress(a)); - } - _addresses[node][coinType] = a; - } - - function addr(bytes32 node, uint coinType) public view returns(bytes memory) { - return _addresses[node][coinType]; - } - - function supportsInterface(bytes4 interfaceID) public pure returns(bool) { - return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); - } -} -``` - -### Implementation - -An implementation of this interface is provided in the [ensdomains/resolvers](https://github.com/ensdomains/resolvers/) repository. - -## Backwards Compatibility - -If the resolver supports the `addr(bytes32)` interface defined in EIP137, the resolver MUST treat this as a special case of this new specification in the following ways: - - 1. The value returned by `addr(node)` from EIP137 should always match the value returned by `addr(node, 60)` (60 is the coin type ID for Ethereum). - 2. Anything that causes the `AddrChanged` event from EIP137 to be emitted must also emit an `AddressChanged` event from this EIP, with the `coinType` specified as 60, and vice-versa. - -## Tests - -The table below specifies test vectors for valid address encodings for each cryptocurrency described above. - -| Cryptocurrency | Coin Type | Text | Onchain (hex) | -| --- | --- | --- | --- | -| Bitcoin | 0 | `1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa` | `76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac` | -| | | `3Ai1JZ8pdJb2ksieUV8FsxSNVJCpoPi8W6` | `a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1887` | -| | | `BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4` | `0014751e76e8199196d454941c45d1b3a323f1433bd6` | -| Litecoin | 2 | `LaMT348PWRnrqeeWArpwQPbuanpXDZGEUz` | `76a914a5f4d12ce3685781b227c1f39548ddef429e978388ac` | -| | | `MQMcJhpWHYVeQArcZR3sBgyPZxxRtnH441` | `a914b48297bff5dadecc5f36145cec6a5f20d57c8f9b87` | -| | | `ltc1qdp7p2rpx4a2f80h7a4crvppczgg4egmv5c78w8` | `0014687c150c26af5493befeed7036043812115ca36c` | -| Dogecoin | 3 | `DBXu2kgc3xtvCUWFcxFE3r9hEYgmuaaCyD` | `76a9144620b70031f0e9437e374a2100934fba4911046088ac` | -| | | `AF8ekvSf6eiSBRspJjnfzK6d1EM6pnPq3G` | `a914f8f5d99a9fc21aa676e74d15e7b8134557615bda87` | -| Monacoin | 22 | `MHxgS2XMXjeJ4if2PRRbWYcdwZPWfdwaDT` | `76a9146e5bb7226a337fe8307b4192ae5c3fab9fa9edf588ac` | -| Ethereum | 60 | `0x314159265dD8dbb310642f98f50C066173C1259b` | `314159265dd8dbb310642f98f50c066173c1259b` | -| Ethereum Classic | 61 | `0x314159265dD8dbb310642f98f50C066173C1259b` | `314159265dd8dbb310642f98f50c066173c1259b` | -| Rootstock | 137 | `0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD` | `5aaeb6053f3e94c9b9a09f33669435e7ef1beaed` | -| Ripple | 144 | `rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn` | `004b4e9c06f24296074f7bc48f92a97916c6dc5ea9` | -| | | `X7qvLs7gSnNoKvZzNWUT2e8st17QPY64PPe7zriLNuJszeg` | `05444b4e9c06f24296074f7bc48f92a97916c6dc5ea9000000000000000000` | -| Bitcoin Cash | 145 | `1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu` | `76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac` | -| | | `bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a` | `76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac` | -| | | `3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC` | `a91476a04053bda0a88bda5177b86a15c3b29f55987387` | -| | | `bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq` | `a91476a04053bda0a88bda5177b86a15c3b29f55987387` | -| Binance | 714 | `bnb1grpf0955h0ykzq3ar5nmum7y6gdfl6lxfn46h2` | `40c2979694bbc961023d1d27be6fc4d21a9febe6` | - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2304.md diff --git a/EIPS/eip-2309.md b/EIPS/eip-2309.md index a98b8e0daae20e..5f69168969c98f 100644 --- a/EIPS/eip-2309.md +++ b/EIPS/eip-2309.md @@ -1,121 +1,7 @@ --- eip: 2309 -title: ERC-721 Consecutive Transfer Extension -author: Sean Papanikolas (@pizzarob) -discussions-to: https://github.com/ethereum/EIPs/issues/2309 -status: Final -type: Standards Track category: ERC -created: 2019-10-08 -requires: 721 +status: Moved --- -## Simple Summary - -A standardized event emitted when creating/transferring one, or many non-fungible tokens using consecutive token identifiers. - -## Abstract - -The optional ERC-721 Consecutive Transfer Extension provides a standardized event which could be emitted during the creation/transfer of one, or many non-fungible tokens. This standard does not set the expectation of how you might create/transfer many tokens it is only concerned with the event emitted after the creation, or transfer of ownership of these tokens. This extension assumes that token identifiers are in consecutive order. - -## Motivation - -This extension provides even more scalibility of the [ERC-721 specification](./eip-721.md). It is possible to create, transfer, and burn 2^256 non-fungible tokens in one transaction. However, it is not possible to emit that many `Transfer` events in one transaction. The `Transfer` event is part of the original specification which states: - -> This emits when ownership of any NFT changes by any mechanism. -> This event emits when NFTs are created (`from` == 0) and destroyed -> (`to` == 0). Exception: during contract creation, any number of NFTs -> may be created and assigned without emitting Transfer. At the time of -> any transfer, the approved address for that NFT (if any) is reset to none. - -This allows for the original `Transfer` event to be emitted for one token at a time, which in turn gives us O(n) time complexity. Minting one billion NFTs can be done in one transaction using efficient data structures, but in order to emit the `Transfer` event - according to the original spec - one would need a loop with one billion iterations which is bound to run out of gas, or exceed transaction timeout limits. This cannot be accomplished with the current spec. This extension solves that problem. - -Many decentralized marketplaces and block explorers utilize the `Transfer` event as a way to determine which NFTs an address owns. The Consecutive Transfer Extension provides a standard mechanism for these platforms to use to determine ownership of many tokens. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL -NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and -"OPTIONAL" in this document are to be interpreted as described in -RFC 2119. - -**ERC-721 compliant contracts MAY implement this Consecutive Transfer Extension to provide a standard event to be emitted at the time of creation, burn, or transfer of one or many consecutive tokens** - -The address executing the transaction **MUST** own all the tokens within the range of `fromTokenId` and `toTokenId`, or **MUST** be an approved operator to act on the owners behalf. - -The `fromTokenId` and `toTokenId` **MUST** be a consecutive range of tokens IDs. - -The `fromTokenId`, `fromAddress`, and `toAddress` **MUST** be indexed parameters - -The `toTokenId` **MUST NOT** be an indexed parameter - -When minting/creating tokens, the `fromAddress` argument **MUST** be set to `0x0` (i.e. zero address). - -When burning/destroying tokens, the `toAddress` argument **MUST** be set to `0x0` (i.e. zero address). - -When emitting the ConsecutiveTransfer event the Transfer event **MUST NOT** be emitted - -Contracts that implement the `ConsecutiveTransfer` event **MAY** still use the original `Transfer` event, however when emitting the `ConsecutiveTransfer` event the `Transfer` event **MUST NOT** be emitted. - -```solidity - event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); -``` - -### Examples - -The `ConsecutiveTransfer` event can be used for a single token as well as many tokens: - -**Single token creation** - -`emit ConsecutiveTransfer(1, 1, address(0), toAddress);` - -**Batch token creation** - -`emit ConsecutiveTransfer(1, 100000, address(0), toAddress);` - -**Batch token transfer** - -`emit ConsecutiveTransfer(1, 100000, fromAddress, toAddress);` - -**Burn** - -`emit ConsecutiveTransfer(1, 100000, from, address(0));` - - -## Rationale - -Standardizing the `ConsecutiveTransfer` event gives decentralized platforms a standard way of determining ownership of large quantities of non-fungible tokens without the need to support a new token standard. There are many ways in which the batch creation and transfer of NFTs can be implemented. The Consecutive Transfer Extension allows contract creators to implement batch creation, transfer, and burn methods however they see fit, but provides a standardized event in which all implementations can use. By specifying a range of consecutive token identifiers we can easily cover the transfer, or creation of 2^(256) tokens and decentralized platforms can react accordingly. - -Take this example. I sell magical fruit and have a farm with 10,000 magical fruit trees each with different fruit and 1,000 new trees every few years. I want to turn each tree into a non-fungible token that people can own. Each person that owns one of my non-fungible tree tokens will receive a quarterly percentage of each harvest from that tree. The problem is that I would need to create and transfer each of these tokens individually - which will cost me a lot of time and money and frankly would keep me from doing this. - -With this extension I would be able to to mint my initial 10,000 tree tokens in one transaction. I would be able to quickly and cheaply mint my additional 1,000 tree tokens when a new batch is planted. I would then be able to transfer all of the 10,000+ tree tokens to a special smart contract that keeps track of the selling and distribution of funds in one transaction all while adhering to a specified standard. - -**Rationale to have a single event that covers minting, burning, and transferring** - -The `ConsecutiveTransfer` event can be used to cover minting, burning, and transferring events. While there may have been confusion in the beginning adhering to transfer to/from "0" pattern this is mitigated by checking for the `ConsecutiveTransfer` topic and verifying the emitting contract supports the ERC-721 interface by using the ERC-165 standard. - -**Indexed event parameters** - -Events in Solidity can have up to three indexed parameters which will make it possible to filter for specific values of indexed arguments. This standard sets the `fromAddress`, `toAddress`, and `fromTokenId` as the indexed parameters. The `toTokenId` can be retrieved from the data part of the log. The reason for this is that more often than not one may be searching for events to learn about the history of ownership for a given address. The `fromTokenId` can then be retrieved along with the other two indexed parameters for simplicity. Then one only needs to decode the log data which is ensured to be the `toTokenId`. - -**Rationale to not emit `Transfer` when `ConsecutiveTransfer` is also emitted** - -This can lead to bugs and unnecessary complex logic for platforms using these events to track token ownership. When transferring a single token it is acceptable to emit the original `Transfer` event, but the `ConsecutiveTransfer` event should not be emitted during the same transaction and vice-versa. - -**Comparing 2309 and 1155** - -As the NFT market continues to grow so does the need for the ability to scale the smart contracts. Users need to be able to do things like mint a massive amount of tokens at one time, transfer a massive amount of tokens, and be able to track ownership of all these assets. We need to do this in a way that is cost effective and doesn’t fail under the confines of the Ethereum blockchain. As millions of tokens are minted we need contracts with the ability to scale. - -[ERC-1155](./eip-1155.md) was created and added as a standard in 2019 to try to solve these problems, but it falls short when it comes to minting massive amounts of unique tokens in a cost-effective way. With ERC-1155 it’s either going to cost hundreds (or thousands) of dollars or it’s going to run out of gas. ERC-1155 works well when minting many semi-fungible tokens but falls short when minting many unique tokens. Using the 2309 standard you could mint millions of blank NFTs upfront and update the metadata for each one in a cost effective way. - - -## Backwards Compatibility - -This extension was written to allow for the smallest change possible to the original ERC-721 spec while still providing a mechanism to track the creation, transfer, and deletion of a massive amount of tokens. While it is a minimal change the effects on platforms that only use the original `Transfer` event to index token ownership would be severe. They would not be properly recording token ownership information that could be known by listening for the `ConsecutiveTransfer` event. For platforms that wish to support the `ConsecutiveTransfer` event it would be best to support both the original `Transfer` event and the `ConsecutiveTransfer` event to track token ownership. - -## Security Considerations -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2309.md diff --git a/EIPS/eip-2315.md b/EIPS/eip-2315.md index 276034506f6c2d..2da8392004a06c 100644 --- a/EIPS/eip-2315.md +++ b/EIPS/eip-2315.md @@ -9,7 +9,7 @@ type: Standards Track category: Core created: 2019-10-17 requires: 3540, 3670, 4200 -withdrawal-reason: This proposal has been superceded by the EOF proposals. +withdrawal-reason: This proposal has been superseded by the EOF proposals. --- ## Abstract diff --git a/EIPS/eip-2330.md b/EIPS/eip-2330.md index 77b085ad12e716..a648f15e78e970 100644 --- a/EIPS/eip-2330.md +++ b/EIPS/eip-2330.md @@ -4,7 +4,7 @@ title: EXTSLOAD opcode description: A new EVM opcode to read external contract storage data. author: Dominic Letz (@dominicletz), Santiago Palladino (@spalladino) discussions-to: https://ethereum-magicians.org/t/eip-2330-extsload-and-abi-for-lower-gas-cost-and-off-chain-apps/3733 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2019-10-29 diff --git a/EIPS/eip-2333.md b/EIPS/eip-2333.md index 095c82a874cb6b..962cb23c8fa536 100644 --- a/EIPS/eip-2333.md +++ b/EIPS/eip-2333.md @@ -1,816 +1,7 @@ --- eip: 2333 -title: BLS12-381 Key Generation -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2337 -status: Stagnant -type: Standards Track category: ERC -created: 2019-09-30 +status: Moved --- -## Simple Summary - -This EIP is a method based on a tree structure for deriving BLS private keys from a single source of entropy while providing a post-quantum cryptographic fallback for each key. - -## Abstract - -This standard is a method for deriving a tree-hierarchy of BLS12-381 keys based on an entropy seed. Starting with the aforementioned seed, a tree of keys is built out using only the parent node's private key and the index of the desired child. This allows for a practically limitless number of keys to be derived for many different purposes while only requiring knowledge of a single ancestor key in the tree. This allows for keys, or families thereof, to be provisioned for different purposes by further standards. - -In addition to the above, this method of deriving keys provides an emergency backup signature scheme that is resistant to quantum computers for in the event that BLS12-381 is ever deemed insecure. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted [BLS signatures over BLS12-381](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -### Deficiencies of the existing mechanism - -The curve BLS12-381 used for BLS signatures within Ethereum 2.0 (alongside many other projects) mandates a new key derivation scheme. The most commonly used scheme for key derivation within Ethereum 1.x is [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) (also known as HD derivation) which deems keys greater than the curve order invalid. Based on the order of the private key subgroup of BLS12-381 and the size of the entropy utilised, more than 54% of keys generated by BIP32 would be invalid. (secp256k1 keys derived by BIP32 are invalid with probability less than 1 in 2-127.) - -### Establishing a multi-chain standard early on - -By establishing a standard before the first users begin to generate their keys, the hope is that a single standard is highly pervasive and therefore can be assumed to be the method by which the majority of keys are provided. This is valuable for two reasons, firstly in order for a post-quantum backup mechanism to be effective, there needs to be an enshrined mechanism whereby users can switch to a post-quantum signature scheme with pre-shared public keys (something this EIP provides at 0 extra storage cost). Secondly, this unifies the inter- and intra-chain ecosystem by having common tooling ideally allowing users to switch between key-management systems. - -### A post-quantum backup - -This key derivation scheme has a Lamport key pair which is generated as a intermediate step in the key generation process. This key pair can be used to provide a Lamport signature which is a useful backup in the event of BLS12-381 no longer being considered secure (in the event of quantum computing making a sudden advancement, for example). The idea is the Lamport signature will act as a bridge to a new signature scheme which is deemed to be secure. - -## Specification - -### Version - -Due to the evolving BLS signatures CFRG draft (currently v4), the `KeyGen` function was updated, meaning that `hkdf_mod_r` no longer reflected what appeared in the BLS standard. This EIP was updated on the 17th of September 2020 to reflect this new method for deriving keys, **if you are implementing this EIP, please make sure your version is up to date.** - -### Specification - -Keys are defined in terms of a tree structure where a key is determined by the tree's seed and a tree path. This is very useful as one can start with a single source of entropy and build out a practically unlimited number of keys. The specification can be broken into two sub-components: generating the master key, and constructing a child key from its parent. The master key is used as the root of the tree and then the tree is built in layers on top of this root. - -### The Tree Structure - -The key tree is defined purely through the relationship between a child-node and its ancestors. Starting with the root of the tree, the *master key*, a child node can be derived by knowing the parent's private key and the index of the child. The tree is broken up into depths which are indicated by `/` and the master node is described as `m`. The first child of the master node is therefore described as `m / 0` and `m / 0`'s siblings are `m / i` for all `0 <= i < 2**32`. - -```text - [m / 0] - [m / 0 / 0] - / \ - / [m / 0 / 1] -[m] - [m / 1] - \ - ... - [m / i] -``` - -### Key derivation - -Every key generated via the key derivation process derives a child key via a set of intermediate Lamport keys. The idea behind the Lamport keys is to provide a post-quantum backup in case BLS12-381 is no longer deemed secure. At a high level, the key derivation process works by using the parent node's privkey as an entropy source for the Lamport private keys which are then hashed together into a compressed Lamport public key, this public key is then hashed into BLS12-381's private key group. - -#### `IKM_to_lamport_SK` - -##### Inputs - -* `IKM`, a secret octet string -* `salt`, an octet string - -##### Outputs - -* `lamport_SK`, an array of 255 32-octet strings - -##### Definitions - -* `HKDF-Extract` is as defined in [RFC5869](https://tools.ietf.org/html/rfc5869), instantiated with SHA256 -* `HKDF-Expand` is as defined in [RFC5869](https://tools.ietf.org/html/rfc5869), instantiated with SHA256 -* `K = 32` is the digest size (in octets) of the hash function (SHA256) -* `L = K * 255` is the HKDF output size (in octets) -* `""` is the empty string -* `bytes_split` is a function takes in an octet string and splits it into `K`-byte chunks which are returned as an array - -##### Procedure - -``` text -0. PRK = HKDF-Extract(salt, IKM) -1. OKM = HKDF-Expand(PRK, "" , L) -2. lamport_SK = bytes_split(OKM, K) -3. return lamport_SK -``` - -#### `parent_SK_to_lamport_PK` - -##### Inputs - -* `parent_SK`, the BLS Secret Key of the parent node -* `index`, the index of the desired child node, an integer `0 <= index < 2^32` - -##### Outputs - -* `lamport_PK`, the compressed lamport PK, a 32 octet string - -##### Definitions - -* `I2OSP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian decoding) -* `flip_bits` is a function that returns the bitwise negation of its input -* `""` is the empty string -* `a | b` is the concatenation of `a` with `b` - -##### Procedure - -```text -0. salt = I2OSP(index, 4) -1. IKM = I2OSP(parent_SK, 32) -2. lamport_0 = IKM_to_lamport_SK(IKM, salt) -3. not_IKM = flip_bits(IKM) -4. lamport_1 = IKM_to_lamport_SK(not_IKM, salt) -5. lamport_PK = "" -6. for i in 1, .., 255 - lamport_PK = lamport_PK | SHA256(lamport_0[i]) -7. for i in 1, .., 255 - lamport_PK = lamport_PK | SHA256(lamport_1[i]) -8. compressed_lamport_PK = SHA256(lamport_PK) -9. return compressed_lamport_PK -``` - -**Note:** The indexing, `i`, in the above procedure iterates from 1 to 255 (inclusive). This is due to the limit to which HKDF can stretch the input bytes (255 times the length of the input bytes). The result of this is that the security of the lamport-backup signature is \*only\* 127.5 bit. - -#### `HKDF_mod_r` - -`hkdf_mod_r()` is used to hash 32 random bytes into the subgroup of the BLS12-381 private keys. - -##### Inputs - -* `IKM`, a secret octet string >= 256 bits in length -* `key_info`, an optional octet string (default=`""`, the empty string) - -##### Outputs - -* `SK`, the corresponding secret key, an integer 0 <= SK < r. - -##### Definitions - -* `HKDF-Extract` is as defined in RFC5869, instantiated with hash H. -* `HKDF-Expand` is as defined in RFC5869, instantiated with hash H. -* `L` is the integer given by `ceil((3 * ceil(log2(r))) / 16)`.(`L=48`) -* `"BLS-SIG-KEYGEN-SALT-"` is an ASCII string comprising 20 octets. -* `OS2IP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian encoding) -* `I2OSP` is as defined in [RFC3447](https://ietf.org/rfc/rfc3447.txt) (Big endian decoding) -* `r` is the order of the BLS 12-381 curve defined in [the v4 draft IETF BLS signature scheme standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-04) `r=52435875175126190479447740508185965837690552500527637822603658699938581184513` - -##### Procedure - -```text -1. salt = "BLS-SIG-KEYGEN-SALT-" -2. SK = 0 -3. while SK == 0: -4. salt = H(salt) -5. PRK = HKDF-Extract(salt, IKM || I2OSP(0, 1)) -6. OKM = HKDF-Expand(PRK, key_info || I2OSP(L, 2), L) -7. SK = OS2IP(OKM) mod r -8. return SK -``` - -### `derive_child_SK` - -The child key derivation function takes in the parent's private key and the index of the child and returns the child private key. - -##### Inputs - -* `parent_SK`, the secret key of the parent node, a big endian encoded integer -* `index`, the index of the desired child node, an integer `0 <= index < 2^32` - -##### Outputs - -* `child_SK`, the secret key of the child node, a big endian encoded integer - -##### Procedure - -```text -0. compressed_lamport_PK = parent_SK_to_lamport_PK(parent_SK, index) -1. SK = HKDF_mod_r(compressed_lamport_PK) -2. return SK -``` - -### `derive_master_SK` - -The child key derivation function takes in the parent's private key and the index of the child and returns the child private key. The seed should ideally be derived from a mnemonic, with the intention being that [BIP39 mnemonics](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki), with the associated [mnemonic_to_seed method](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#from-mnemonic-to-seed) be used. - -##### Inputs - -* `seed`, the source entropy for the entire tree, a octet string >= 256 bits in length - -##### Outputs - -* `SK`, the secret key of master node within the tree, a big endian encoded integer - -##### Procedure - -```text -0. SK = HKDF_mod_r(seed) -1. return SK -``` - -## Rationale - -### Lamport signatures - -Lamport signatures are used as the backup mechanism because of their relative simplicity for a post-quantum signature scheme. Lamport signatures are very easy both to explain and implement as the sole cryptographic dependency is a secure hash function. This is important as it minimises the complexity of implementing this standard as well as the compute time for deriving a key. Lamport signatures have very large key sizes which make them impractical for many use cases, but this is not deemed to be an issue in this case as this scheme is only meant to be a once-off event to migrate to a new scheme. - -Revealing the associated Lamport public key for a corresponding BLS key is done by verifying that the Lamport public key is the pre-image of the corresponding BLS private key (which in turn is verified against the BLS public key). This means that using a key's Lamport signature reveals the BLS private key rendering the BLS key pair unsafe. This has the upside of not requiring additional storage space for backup keys alongside BLS keys but does require that the Lamport signatures be used once and that the BLS key is no longer trusted after that point. - -The Lamport signatures used within this scheme have 255 bits worth of security, not 256. This is done because HKDF-SHA256, the mechanism used to stretch a key's entropy, has a length-limit of `255 * hash_function_digest_size`. The 1-bit reduction in security is deemed preferable over increasing the complexity of the entropy stretching mechanism. - -### SHA256 - -SHA256 is used as the hash function throughout this standard as it is the hash function chosen by the [IETF BLS signature proposed standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). Using a single hash function for everything decreases the number of cryptographic primitives required to implement the entire BLS standardised key-stack while reducing the surface for flaws in the overall system. - -### `hkdf_mod_r()` - -The function `hkdf_mod_r()` in this standard is the same as the `KeyGen` function described in the [proposed standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/) and therefore the private key obtained from `KeyGen` is equal to that obtained from `hkdf_mod_r` for the same seed bytes. This means that common engineering can be done when implementing this function. Additionally because of its inclusion in an IETF standard, it has had much scrutiny by many cryptographers and cryptanalysts, thereby lending credence to its safety as a key derivation mechanism. - -While `hkdf_mod_r()` has modulo bias, the magnitude of this bias is minuscule (the output size of HKDF is set to 48 bytes which is greater 2128 time larger than the curve order). This bias is deemed acceptable in light of the simplicity of the constant time scheme. - -### Only using hardened keys - -Widely accepted standards that existed before this one ([BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) utilise the notion of hardened and non-hardened keys whereas this specification only offers the former. Non-hardened keys are primarily useful in a UTXO system in which having one's balance spilt amongst many accounts does not present much additionally complexity, but such keys are much less useful outside of this context. Further complicating matters is the problem of deriving non-hardened keys using a post-quantum signature scheme as non-hardened keys are made possible by the very group arithmetic quantum computers gain an advantage over. - -## Backwards Compatibility - -There are no major backwards compatibility issues brought upon by this EIP as it is not designed for use within Ethereum 1.0 as it currently stands. That said, this standard is not compatible with BIP32/ BIP44 style paths as paths specified by these systems make use of non-hardened keys, something that does not exist within this standard. - -## Test Cases - -### Test Case 0 - -```text -seed = 0xc55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04 -master_SK = 6083874454709270928345386274498605044986640685124978867557563392430687146096 -child_index = 0 -child_SK = 20397789859736650942317412262472558107875392172444076792671091975210932703118 -``` - -This test case can be extended to test the entire mnemonic-to-`child_SK` stack, assuming [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) is used as the mnemonic generation mechanism. Using the following parameters, the above seed can be calculated: - -```test -mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" -passphrase = "TREZOR" -``` - -This test case can be extended to test the entire `mnemonic-to -child_SK` stack, assuming [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) is used as the mnemonic generation mechanism. Using the following parameters, the above seed can be calculated: - -```text -mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" -passphrase = "TREZOR" -``` - -### Test Case 1 - -```text -seed = 0x3141592653589793238462643383279502884197169399375105820974944592 -master_SK = 29757020647961307431480504535336562678282505419141012933316116377660817309383 -child_index = 3141592653 -child_SK = 25457201688850691947727629385191704516744796114925897962676248250929345014287 -``` - -### Test Case 2 - -```text -seed = 0x0099FF991111002299DD7744EE3355BBDD8844115566CC55663355668888CC00 -master_SK = 27580842291869792442942448775674722299803720648445448686099262467207037398656 -child_index = 4294967295 -child_SK = 29358610794459428860402234341874281240803786294062035874021252734817515685787 -``` - -### Test Case 3 - -```text -seed = 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3 -master_SK = 19022158461524446591288038168518313374041767046816487870552872741050760015818 -child_index = 42 -child_SK = 31372231650479070279774297061823572166496564838472787488249775572789064611981 -``` - -### Test Vector with Intermediate values - -```text -seed = 0xc55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04 -master_SK = 6083874454709270928345386274498605044986640685124978867557563392430687146096 -child_index = 0 -lamport_0 = [0xe345d0ad7be270737de05cf036f688f385d5f99c7fddb054837658bdd2ebd519, -0x65050bd4db9c77c051f67dcc801bf1cdf33d81131e608505bb3e4523868eb76c, -0xc4f8e8d251fbdaed41bdd9c135b9ed5f83a614f49c38fffad67775a16575645a, -0x638ad0feace7567255120a4165a687829ca97e0205108b8b73a204fba6a66faa, -0xb29f95f64d0fcd0f45f265f15ff7209106ab5f5ce6a566eaa5b4a6f733139936, -0xbcfbdd744c391229f340f02c4f2d092b28fe9f1201d4253b9045838dd341a6bf, -0x8b9cf3531bfcf0e4acbfd4d7b4ed614fa2be7f81e9f4eaef53bedb509d0b186f, -0xb32fcc5c4e2a95fb674fa629f3e2e7d85335f6a4eafe7f0e6bb83246a7eced5f, -0xb4fe80f7ac23065e30c3398623b2761ac443902616e67ce55649aaa685d769ce, -0xb99354f04cfe5f393193c699b8a93e5e11e6be40ec16f04c739d9b58c1f55bf3, -0x93963f58802099ededb7843219efc66a097fab997c1501f8c7491991c780f169, -0x430f3b027dbe9bd6136c0f0524a0848dad67b253a11a0e4301b44074ebf82894, -0xd635c39b4a40ad8a54d9d49fc8111bd9d11fb65c3b30d8d3eaef7d7556aac805, -0x1f7253a6474cf0b2c05b02a7e91269137acddedcb548144821f9a90b10eccbab, -0x6e3bdb270b00e7b6eb8b044dbfae07b51ea7806e0d24218c59a807a7fd099c18, -0x895488ad2169d8eaae332ce5b0fe1e60ffab70e62e1cb15a2a1487544af0a6e8, -0x32d45a99d458c90e173a3087ea3661ab62d429b285089e92806a9663ba825342, -0xc15c52106c3177f5848a173076a20d46600ca65958a1e3c7d45a593aaa9670ed, -0xd8180c550fbe4cd6d5b676ff75e0728729d8e28a3b521d56152594ac6959d563, -0x58fe153fac8f4213aaf175e458435e06304548024bcb845844212c774bdffb2a, -0x10fff610a50f4bee5c978f512efa6ab4fafacb65929606951ba5b93eeb617b5a, -0x78ac9819799b52eba329f13dd52cf0f6148a80bf04f93341814c4b47bb4aa5ec, -0xa5c3339caa433fc11e74d1765bec577a13b054381a44b23c2482e750696876a9, -0x9f716640ab5cdc2a5eb016235cddca2dc41fa4ec5acd7e58af628dade99ec376, -0x2544364320e67577c4fed8c7c7c839deed93c24076d5343c5b8faca4cc6dc2d8, -0x62553e782541f822c589796be5d5c83bfc814819100b2be0710b246f5aa7149c, -0x229fb761c46c04b22ba5479f2696be0f936fded68d54dd74bcd736b8ba512afb, -0x0af23996a65b98a0ebaf19f3ec0b3ef20177d1bfd6eb958b3bd36e0bdbe04c8c, -0x6f0954f9deab52fd4c8d2daba69f73a80dea143dd49d9705c98db3d653adf98c, -0xfa9221dd8823919a95b35196c1faeb59713735827f3e84298c25c83ac700c480, -0x70c428e3ff9e5e3cda92d6bb85018fb89475c19f526461cca7cda64ebb2ff544, -0xdcaac3413e22314f0f402f8058a719b62966b3a7429f890d947be952f2e314ba, -0xb6b383cb5ec25afa701234824491916bfe6b09d28cf88185637e2367f0cf6edc, -0x7b0d91488fc916aba3e9cb61a5a5645b9def3b02e4884603542f679f602afb8d, -0xe9c20abca284acfde70c59584b9852b85c52fa7c263bb981389ff8d638429cd7, -0x838524f798daee6507652877feb9597f5c47e9bb5f9aa52a35fb6fff796813b9, -0xbe1ca18faf9bf322474fad1b3d9b4f1bc76ae9076e38e6dd2b16e2faf487742b, -0xbf02d70f1a8519343a16d24bade7f7222912fd57fe4f739f367dfd99d0337e8e, -0xc979eb67c107ff7ab257d1c0f4871adf327a4f2a69e01c42828ea27407caf058, -0xf769123d3a3f19eb7b5c3fd4f467a042944a7c5ff8834cebe427f47dbd71460c, -0xaefc8edc23257e1168a35999fe3832bcbc25053888cc89c38667482d6748095b, -0x8ff399f364d3a2428b1c92213e4fdc5341e7998007da46a5a2f671929b42aaab, -0xcf2a3d9e6963b24c5001fbba1e5ae7f45dd6cf520fd24861f745552db86bab48, -0xb380e272d7f3091e5c887fa2e7c690c67d59f4d95f8376d150e555da8c738559, -0xc006a749b091d91204dbb64f59059d284899de5986a7f84f8877afd5e0e4c253, -0x818d8bb9b7da2dafa2ef059f91975e7b6257f5e199d217320de0a576f020de5c, -0x7aabf4a1297d2e550a2ee20acb44c1033569e51b6ec09d95b22a8d131e30fd32, -0xdd01c80964a5d682418a616fb10810647c9425d150df643c8ddbbe1bfb2768b7, -0x1e2354e1d97d1b06eb6cfe9b3e611e8d75b5c57a444523e28a8f72a767eff115, -0x989c9a649dca0580256113e49ea0dd232bbfd312f68c272fe7c878acc5da7a2c, -0x14ee1efe512826fff9c028f8c7c86708b841f9dbf47ce4598298b01134ebdc1a, -0x6f861dba4503f85762d9741fa8b652ce441373f0ef2b7ebbd5a794e48cdab51b, -0xda110c9492ffdb87efe790214b7c9f707655a5ec08e5af19fb2ab2acc428e7dc, -0x5576aa898f6448d16e40473fcb24c46c609a3fc46a404559faa2d0d34d7d49ce, -0x9bd9a35675f2857792bc45893655bfdf905ffeaee942d93ad39fbcadd4ca9e11, -0xfa95e4c37db9303d5213890fd984034089cbc9c6d754741625da0aa59cc45ccf, -0xfef7d2079713f17b47239b76c8681bf7f800b1bfeac7a53265147579572ddf29, -0x39aa7c0fecf9a1ed037c685144745fda16da36f6d2004844cf0e2d608ef6ed0e, -0x5530654d502d6ba30f2b16f49cc5818279697308778fd8d40db8e84938144fb6, -0xb1beaa36397ba1521d7bf7df16536969d8a716e63510b1b82a715940180eb29f, -0x21abe342789f7c15a137afa373f686330c0db8c861572935a3cd8dcf9e4e1d45, -0x27b5a1acda55b4e0658887bd884d3203696fcae0e94f19e31bfe931342b1c257, -0x58401a02502d7708a812c0c72725f768f5a556480517258069f2d72543cda888, -0x4b38f291548f51bee7e4cf8cc5c8aa8f4ad3ec2461dba4ccbab70f1c1bfd7feb, -0x9b39a53fdafaaf1d23378e0aa8ae65d38480de69821de2910873eefc9f508568, -0x932200566a3563ee9141913d12fd1812cb008cb735724e8610890e101ec10112, -0x6a72f70b4ec5491f04780b17c4776a335fcc5bff5073d775150e08521dc74c91, -0x86d5c60e627a4b7d5d075b0ba33e779c45f3f46d22ed51f31360afd140851b67, -0x5ca2a736bb642abc4104faa781c9aff13d692a400d91dc961aec073889836946, -0xa14bca5a262ac46ceac21388a763561fc85fb9db343148d786826930f3e510cd, -0x87be03a87a9211504aa70ec149634ee1b97f7732c96377a3c04e98643dcba915, -0x8fe283bc19a377823377e9c326374ebb3f29527c12ea77bfb809c18eef8943b0, -0x8f519078b39a3969f7e4caeca9839d4e0eccc883b89e4a86d0e1731bfc5e33fc, -0x33d7c28c3d26fdfc015a8c2131920e1392ef0aea55505637b54ea63069c7858e, -0xe57de7c189fcc9170320c7acedb38798562a48dbc9943b2a8cd3441d58431128, -0x513dac46017050f82751a07b6c890f14ec43cadf687f7d202d2369e35b1836b4, -0xfd967d9f805bb7e78f7b7caa7692fdd3d6b5109c41ad239a08ad0a38eeb0ac4c, -0xf2013e4da9abcc0f03ca505ed94ec097556dbfd659088cd24ec223e02ac43329, -0xe0dcfac50633f7417f36231df2c81fa1203d358d5f57e896e1ab4b512196556b, -0xf022848130e73fe556490754ef0ecfcdaaf3b9ff16ae1eda7d38c95c4f159ded, -0x2147163a3339591ec7831d2412fb2d0588c38da3cd074fa2a4d3e5d21f9f1d2d, -0x11ee2404731962bf3238dca0d9759e06d1a5851308b4e6321090886ec5190b69, -0xf7679ecd07143f8ac166b66790fa09aed39352c09c0b4766bbe500b1ebace5a5, -0xc7a0e95f09076472e101813a95e6ea463c35bd5ee9cfda3e5d5dbccb35888ef0, -0xde625d3b547eb71bea5325a0191a592fa92a72e4b718a499fdba32e245ddf37e, -0x7e5bdccd95df216e8c59665073249072cb3c9d0aef6b341afc0ca90456942639, -0xc27f65fd9f797ede374e06b4ddb6e8aa59c7d6f36301f18b42c48b1889552fe3, -0x8175730a52ea571677b035f8e2482239dda1cfbff6bc5cde00603963511a81af, -0x09e440f2612dad1259012983dc6a1e24a73581feb1bd69d8a356eea16ba5fd0e, -0x59dcc81d594cbe735a495e38953e8133f8b3825fd84767af9e4ea06c49dbabfa, -0x6c8480b59a1a958c434b9680edea73b1207077fb9a8a19ea5f9fbbf6f47c4124, -0x81f5c89601893b7a5a231a7d37d6ab9aa4c57f174fcfc6b40002fa808714c3a1, -0x41ba4d6b4da141fcc1ee0f4b47a209cfd143d34e74fc7016e9956cedeb2db329, -0x5e0b5b404c60e9892040feacfb4a84a09c2bc4a8a5f54f3dad5dca4acdc899dc, -0xe922eebf1f5f15000d8967d16862ed274390cde808c75137d2fb9c2c0a80e391, -0xbf49d31a59a20484f0c08990b2345dfa954509aa1f8901566ab9da052b826745, -0xb84e07da828ae668c95d6aa31d4087504c372dbf4b5f8a8e4ded1bcf279fd52b, -0x89288bf52d8c4a9561421ad199204d794038c5d19ae9fee765ee2b5470e68e7e, -0xf6f618be99b85ec9a80b728454a417c647842215e2160c6fe547dd5a69bd9302, -0xdd9adc002f98c9a47c7b704fc0ce0a5c7861a5e2795b6014749cde8bcb8a034b, -0xd119a4b2c0db41fe01119115bcc35c4b7dbfdb42ad3cf2cc3f01c83732acb561, -0x9c66bc84d416b9193bad9349d8c665a9a06b835f82dc93ae0cccc218f808aad0, -0xd4b50eefcd2b5df075f14716cf6f2d26dfc8ae02e3993d711f4a287313038fde, -0xaf72bfb346c2f336b8bc100bff4ba35d006a3dad1c5952a0adb40789447f2704, -0xc43ca166f01dc955e7b4330227635feb1b0e0076a9c5633ca5c614a620244e5b, -0x5efca76970629521cfa053fbbbda8d3679cadc018e2e891043b0f52989cc2603, -0x35c57de1c788947f187051ce032ad1e899d9887d865266ec6fcfda49a8578b2b, -0x56d4be8a65b257216eab7e756ee547db5a882b4edcd12a84ed114fbd4f5be1f1, -0x257e858f8a4c07a41e6987aabaa425747af8b56546f2a3406f60d610bcc1f269, -0x40bd9ee36d52717ab22f1f6b0ee4fb38b594f58399e0bf680574570f1b4b8c90, -0xcb6ac01c21fc288c12973427c5df6eb8f6aefe64b92a6420c6388acdf36bc096, -0xa5716441312151a5f0deb52993a293884c6c8f445054ce1e395c96adeee66c6d, -0xe15696477f90113a10e04ba8225c28ad338c3b6bdd7bdeb95c0722921115ec85, -0x8faeaa52ca2f1d791cd6843330d16c75eaf6257e4ba236e3dda2bc1a644aee00, -0xc847fe595713bf136637ce8b43f9de238762953fed16798878344da909cc76ae, -0xb5740dc579594dd110078ce430b9696e6a308078022dde2d7cfe0ef7647b904e, -0x551a06d0771fcd3c53aea15aa8bf700047138ef1aa22265bee7fb965a84c9615, -0x9a65397a5907d604030508d41477de621ce4a0d79b772e81112d634455e7a4da, -0x6462d4cc2262d7faf8856812248dc608ae3d197bf2ef410f00c3ae43f2040995, -0x6782b1bd319568e30d54b324ab9ed8fdeac6515e36b609e428a60785e15fb301, -0x8bcdcf82c7eb2a07e14db20d80d9d2efea8d40320e121923784c92bf38250a8e, -0x46ed84fa17d226d5895e44685747ab82a97246e97d6237014611aaaba65ed268, -0x147e87981673326c5a2bdb06f5e90eaaa9583857129451eed6dde0c117fb061f, -0x4141d6fe070104c29879523ba6669552f3d457c0929bb878d2751f4ff059b895, -0xd866ce4ef226d74841f950fc28cdf2235db21e0e3f07a0c8f807704464db2210, -0xa804f9118bf92558f684f90c2bda832a4f51ef771ffb2765cde3ec6f48124f32, -0xc436d4a65910124e00cded9a637178914a8fbc090400f3f031c03eac4d0295a5, -0x643fdb9243656512316528de04dcc7344ca33783580ad0c3debf8c4a6e7c8bc4, -0x7f4a345b41706b281b2de998e91ff62d908eb29fc333ee336221757753c96e23, -0x6bdc086a5b11de950cabea33b72d98db886b291c4c2f02d3e997edc36785d249, -0xfb10b5b47d374078c0a52bff7174bf1cd14d872c7d20b4a009e2afd3017a9a17, -0x1e07e605312db5380afad8f3d7bd602998102fdd39565b618ac177b13a6527e6, -0xc3161b5a7b93aabf05652088b0e5b4803a18be693f590744c42c24c7aaaeef48, -0xa47e4f25112a7d276313f153d359bc11268b397933a5d5375d30151766bc689a, -0xb24260e2eff88716b5bf5cb75ea171ac030f5641a37ea89b3ac45acb30aae519, -0x2bcacbebc0a7f34406db2c088390b92ee34ae0f2922dedc51f9227b9afb46636, -0xc78c304f6dbe882c99c5e1354ce6077824cd42ed876db6706654551c7472a564, -0x6e2ee19d3ee440c78491f4e354a84fa593202e152d623ed899e700728744ac85, -0x2a3f438c5dc012aa0997b66f661b8c10f4a0cd7aa5b6e5922b1d73020561b27f, -0xd804f755d93173408988b95e9ea0e9feae10d404a090f73d9ff84df96f081cf7, -0xe06fda941b6936b8b33f00ffa02c8b05fd78fbec953da61da2043f5644b30a50, -0x45ee279b465d53148850a16cc7f6bd33e7627aef554a9418ed012ca8f9717f80, -0x9c79348c1bcd6aa2135452491d73564413a247ea8cc38fa7dcc6c43f8a2d61d5, -0x7c91e056f89f2a77d3e3642e595bcf4973c3bca68dd2b10f51ca0d8945e4255e, -0x669f976ebe38cbd22c5b1f785e14b76809d673d2cb1458983dbda41f5adf966b, -0x8bc71e99ffcc119fd8bd604af54c0663b0325a3203a214810fa2c588089ed5a7, -0x36b3f1ffeae5d9855e0965eef33f4c5133d99685802ac5ce5e1bb288d308f889, -0x0aad33df38b3f31598e04a42ec22f20bf2e2e9472d02371eb1f8a06434621180, -0x38c5632b81f90efbc51a729dcae03626a3063aa1f0a102fd0e4326e86a08a732, -0x6ea721753348ed799c98ffa330d801e6760c882f720125250889f107915e270a, -0xe700dd57ce8a653ce4269e6b1593a673d04d3de8b79b813354ac7c59d1b99adc, -0xe9294a24b560d62649ca898088dea35a644d0796906d41673e29e4ea8cd16021, -0xf20bb60d13a498a0ec01166bf630246c2f3b7481919b92019e2cfccb331f2791, -0xf639a667209acdd66301c8e8c2385e1189b755f00348d614dc92da14e6866b38, -0x49041904ee65c412ce2cd66d35570464882f60ac4e3dea40a97dd52ffc7b37a2, -0xdb36b16d3a1010ad172fc55976d45df7c03b05eab5432a77be41c2f739b361f8, -0x71400cdd2ea78ac1bf568c25a908e989f6d7e2a3690bc869c7c14e09c255d911, -0xf0d920b2d8a00b88f78e7894873a189c580747405beef5998912fc9266220d98, -0x1a2baefbbd41aa9f1cc5b10e0a7325c9798ba87de6a1302cf668a5de17bc926a, -0x449538a20e52fd61777c45d35ff6c2bcb9d9165c7eb02244d521317f07af6691, -0x97006755b9050b24c1855a58c4f4d52f01db4633baff4b4ef3d9c44013c5c665, -0xe441363a27b26d1fff3288222fa8ed540f8ca5d949ddcc5ff8afc634eec05336, -0xed587aa8752a42657fea1e68bc9616c40c68dcbbd5cb8d781e8574043e29ef28, -0x47d896133ba81299b8949fbadef1c00313d466827d6b13598685bcbb8776c1d2, -0x7786bc2cb2d619d07585e2ea4875f15efa22110e166af87b29d22af37b6c047d, -0x956b76194075fe3daf3ca508a6fad161deb05d0026a652929e37c2317239cbc6, -0xec9577cb7b85554b2383cc4239d043d14c08d005f0549af0eca6994e203cb4e7, -0x0722d0c68d38b23b83330b972254bbf9bfcf32104cc6416c2dad67224ac52887, -0x532b19d54fb6d77d96452d3e562b79bfd65175526cd793f26054c5f6f965df39, -0x4d62e065e57cbf60f975134a360da29cabdcea7fcfc664cf2014d23c733ab3b4, -0x09be0ea6b363fd746b303e482cb4e15ef25f8ae57b7143e64cbd5c4a1d069ebe, -0x69dcddc3e05147860d8d0e90d602ac454b609a82ae7bb960ee2ecd1627d77777, -0xa5e2ae69d902971000b1855b8066a4227a5be7234ac9513b3c769af79d997df4, -0xc287d4bc953dcff359d707caf2ccba8cc8312156eca8aafa261fb72412a0ea28, -0xb27584fd151fb30ed338f9cba28cf570f7ca39ebb03eb2e23140423af940bd96, -0x7e02928194441a5047af89a6b6555fea218f1df78bcdb5f274911b48d847f5f8, -0x9ba611add61ea6ba0d6d494c0c4edd03df9e6c03cafe10738cee8b7f45ce9476, -0x62647ec3109ac3db3f3d9ea78516859f0677cdde3ba2f27f00d7fda3a447dd01, -0xfa93ff6c25bfd9e17d520addf5ed2a60f1930278ff23866216584853f1287ac1, -0x3b391c2aa79c2a42888102cd99f1d2760b74f772c207a39a8515b6d18e66888a, -0xcc9ae3c14cbfb40bf01a09bcde913a3ed208e13e4b4edf54549eba2c0c948517, -0xc2b8bce78dd4e876da04c54a7053ca8b2bedc8c639cee82ee257c754c0bea2b2, -0xdb186f42871f438dba4d43755c59b81a6788cb3b544c0e1a3e463f6c2b6f7548, -0xb7f8ba137c7783137c0729de14855e20c2ac4416c33f5cac3b235d05acbab634, -0x282987e1f47e254e86d62bf681b0803df61340fdc9a8cf625ef2274f67fc6b5a, -0x04aa195b1aa736bf8875777e0aebf88147346d347613b5ab77bef8d1b502c08c, -0x3f732c559aee2b1e1117cf1dec4216a070259e4fa573a7dcadfa6aab74aec704, -0x72699d1351a59aa73fcede3856838953ee90c6aa5ef5f1f7e21c703fc0089083, -0x6d9ce1b8587e16a02218d5d5bed8e8d7da4ac40e1a8b46eeb412df35755c372c, -0x4f9c19b411c9a74b8616db1357dc0a7eaf213cb8cd2455a39eb7ae4515e7ff34, -0x9163dafa55b2b673fa7770b419a8ede4c7122e07919381225c240d1e90d90470, -0x268ff4507b42e623e423494d3bb0bc5c0917ee24996fb6d0ebedec9ce8cd9d5c, -0xff6e6169d233171ddc834e572024586eeb5b1bda9cb81e5ad1866dbc53dc75fe, -0xb379a9c8279205e8753b6a5c865fbbf70eb998f9005cd7cbde1511f81aed5256, -0x3a6b145e35a592e037c0992c9d259ef3212e17dca81045e446db2f3686380558, -0x60fb781d7b3137481c601871c1c3631992f4e01d415841b7f5414743dcb4cfd7, -0x90541b20b0c2ea49bca847e2db9b7bba5ce15b74e1d29194a12780e73686f3dd, -0xe2b0507c13ab66b4b769ad1a1a86834e385b315da2f716f7a7a8ff35a9e8f98c, -0xeefe54bc9fa94b921b20e7590979c28a97d8191d1074c7c68a656953e2836a72, -0x8676e7f59d6f2ebb0edda746fc1589ef55e07feab00d7008a0f2f6f129b7bb3a, -0x78a3d93181b40152bd5a8d84d0df7f2adde5db7529325c13bc24a5b388aed3c4, -0xcc0e2d0cba7aaa19c874dbf0393d847086a980628f7459e9204fda39fad375c0, -0x6e46a52cd7745f84048998df1a966736d2ac09a95a1c553016fef6b9ec156575, -0x204ac2831d2376d4f9c1f5c106760851da968dbfc488dc8a715d1c764c238263, -0xbdb8cc7b7e5042a947fca6c000c10b9b584e965c3590f92f6af3fe4fb23e1358, -0x4a55e4b8a138e8508e7b11726f617dcf4155714d4600e7d593fd965657fcbd89, -0xdfe064bb37f28d97b16d58b575844964205e7606dce914a661f2afa89157c45b, -0x560e374fc0edda5848eef7ff06471545fcbdd8aefb2ecddd35dfbb4cb03b7ddf, -0x10a66c82e146da5ec6f48b614080741bc51322a60d208a87090ad7c7bf6b71c6, -0x62534c7dc682cbf356e6081fc397c0a17221b88508eaeff798d5977f85630d4f, -0x0138bba8de2331861275356f6302b0e7424bbc74d88d8c534479e17a3494a15b, -0x580c7768bf151175714b4a6f2685dc5bcfeb088706ee7ed5236604888b84d3e4, -0xd290adb1a5dfc69da431c1c0c13da3be788363238d7b46bc20185edb45ab9139, -0x1689879db6c78eb4d3038ed81be1bc106f8cfa70a7c6245bd4be642bfa02ebd7, -0x6064c384002c8b1594e738954ed4088a0430316738def62822d08b2285514918, -0x01fd23493f4f1cc3c5ff4e96a9ee386b2a144b50a428a6b5db654072bddadfe7, -0xd5d05bb7f23ab0fa2b82fb1fb14ac29c2477d81a85423d0a45a4b7d5bfd81619, -0xd72b9a73ae7b24db03b84e01106cea734d4b9d9850b0b7e9d65d6001d859c772, -0x156317cb64578db93fee2123749aff58c81eae82b189b0d6f466f91de02b59df, -0x5fba299f3b2c099edbac18d785be61852225890fc004bf6be0787d62926a79b3, -0x004154f28f685bdbf0f0d6571e7a962a4c29b6c3ebedaaaf66097dfe8ae5f756, -0x4b45816f9834c3b289affce7a3dc80056c2b7ffd3e3c250d6dff7f923e7af695, -0x6ca53bc37816fff82346946d83bef87860626bbee7fd6ee9a4aeb904d893a11f, -0xf48b2f43184358d66d5b5f7dd2b14a741c7441cc7a33ba3ebcc94a7b0192d496, -0x3cb98f4baa429250311f93b46e745174f65f901fab4eb8075d380908aaaef650, -0x343dfc26b4473b3a20e706a8e87e5202a4e6b96b53ed448afb9180c3f766e5f8, -0x1ace0e8a735073bcbaea001af75b681298ef3b84f1dbab46ea52cee95ab0e7f9, -0xd239b110dd71460cdbc41ddc99494a7531186c09da2a697d6351c116e667733b, -0x22d6955236bd275969b8a6a30c23932670a6067f68e236d2869b6a8b4b493b83, -0x53c1c01f8d061ac89187e5815ef924751412e6a6aa4dc8e3abafb1807506b4e0, -0x2f56dd20c44d7370b713e7d7a1bfb1a800cac33f8a6157f278e17a943806a1f7, -0xc99773d8a5b3e60115896a65ac1d6c15863317d403ef58b90cb89846f4715a7f, -0x9f4b6b77c254094621cd336da06fbc6cbb7b8b1d2afa8e537ceca1053c561ef5, -0x87944d0b210ae0a6c201cba04e293f606c42ebaed8b4a5d1c33f56863ae7e1b5, -0xa7d116d962d03ca31a455f9cda90f33638fb36d3e3506605aa19ead554487a37, -0x4042e32e224889efd724899c9edb57a703e63a404129ec99858048fbc12f2ce0, -0x36759f7a0faeea1cd4cb91e404e4bf09908de6e53739603d5f0db52b664158a3, -0xa4d50d005fb7b9fea8f86f1c92439cc9b8446efef7333ca03a8f6a35b2d49c38, -0x80cb7c3e20f619006542edbe71837cdadc12161890a69eea8f41be2ee14c08a3, -0xbb3c44e1df45f2bb93fb80e7f82cee886c153ab484c0095b1c18df03523629b4, -0x04cb749e70fac3ac60dea779fceb0730b2ec5b915b0f8cf28a6246cf6da5db29, -0x4f5189b8f650687e65a962ef3372645432b0c1727563777433ade7fa26f8a728, -0x322eddddf0898513697599b68987be5f88c0258841affec48eb17cf3f61248e8, -0x6416be41cda27711d9ec22b3c0ed4364ff6975a24a774179c52ef7e6de9718d6, -0x0622d31b8c4ac7f2e30448bdadfebd5baddc865e0759057a6bf7d2a2c8b527e2, -0x40f096513588cc19c08a69e4a48ab6a43739df4450b86d3ec2fb3c6a743b5485, -0x09fcf7d49290785c9ea2d54c3d63f84f6ea0a2e9acfcdbb0cc3a281ce438250e, -0x2000a519bf3da827f580982d449b5c70fcc0d4fa232addabe47bb8b1c471e62e, -0xf4f80008518e200c40b043f34fb87a6f61b82f8c737bd784292911af3740245e, -0x939eaab59f3d2ad49e50a0220080882319db7633274a978ced03489870945a65, -0xadcad043d8c753fb10689280b7670f313253f5d719039e250a673d94441ee17c, -0x58b7b75f090166b8954c61057074707d7e38d55ce39d9b2251bbc3d72be458f8, -0xf61031890c94c5f87229ec608f2a9aa0a3f455ba8094b78395ae312cbfa04087, -0x356a55def50139f94945e4ea432e7a9defa5db7975462ebb6ca99601c614ea1d, -0x65963bb743d5db080005c4db59e29c4a4e86f92ab1dd7a59f69ea7eaf8e9aa79] -lamport_1 = [0x9c0bfb14de8d2779f88fc8d5b016f8668be9e231e745640096d35dd5f53b0ae2, -0x756586b0f3227ab0df6f4b7362786916bd89f353d0739fffa534368d8d793816, -0x710108dddc39e579dcf0819f9ad107b3c56d1713530dd94325db1d853a675a37, -0x8862b5f428ce5da50c89afb50aa779bb2c4dfe60e6f6a070b3a0208a4a970fe5, -0x54a9cd342fa3a4bf685c01d1ce84f3068b0d5b6a58ee22dda8fbac4908bb9560, -0x0fa3800efeaddd28247e114a1cf0f86b9014ccae9c3ee5f8488168b1103c1b44, -0xbb393428b7ebfe2eda218730f93925d2e80c020d41a29f4746dcbb9138f7233a, -0x7b42710942ef38ef2ff8fe44848335f26189c88c22a49fda84a51512ac68cd5d, -0x90e99786a3e8b04db95ccd44d01e75558d75f3ddd12a1e9a2c2ce76258bf4813, -0x3f6f71e40251728aa760763d25deeae54dc3a9b53807c737deee219120a2230a, -0xe56081a7933c6eaf4ef2c5a04e21ab8a3897785dd83a34719d1b62d82cfd00c2, -0x76cc54fa15f53e326575a9a2ac0b8ed2869403b6b6488ce4f3934f17db0f6bee, -0x1cd9cd1d882ea3830e95162b5de4beb5ddff34fdbf7aec64e83b82a6d11b417c, -0xb8ca8ae36d717c448aa27405037e44d9ee28bb8c6cc538a5d22e4535c8befd84, -0x5c4492108c25f873a23d5fd7957b3229edc22858e8894febe7428c0831601982, -0x907bcd75e7465e9791dc34e684742a2c0dc7007736313a95070a7e6b961c9c46, -0xe7134b1511559e6b2440672073fa303ec3915398e75086149eb004f55e893214, -0x2ddc2415e4753bfc383d48733e8b2a3f082883595edc5515514ebb872119af09, -0xf2ad0f76b08ffa1eee62228ba76f4982fab4fbede5d4752c282c3541900bcd5b, -0x0a84a6b15abd1cbc2da7092bf7bac418b8002b7000236dfba7c8335f27e0f1d4, -0x97404e02b9ff5478c928e1e211850c08cc553ebac5d4754d13efd92588b1f20d, -0xfa6ca3bcff1f45b557cdec34cb465ab06ade397e9d9470a658901e1f0f124659, -0x5bd972d55f5472e5b08988ee4bccc7240a8019a5ba338405528cc8a38b29bc21, -0x52952e4f96c803bb76749800891e3bfe55f7372facd5b5a587a39ac10b161bcc, -0xf96731ae09abcad016fd81dc4218bbb5b2cb5fe2e177a715113f381814007314, -0xe7d79e07cf9f2b52623491519a21a0a3d045401a5e7e10dd8873a85076616326, -0xe4892f3777a4614ee6770b22098eaa0a3f32c5c44b54ecedacd69789d676dffe, -0x20c932574779e2cc57780933d1dc6ce51a5ef920ce5bf681f7647ac751106367, -0x057252c573908e227cc07797117701623a4835f4b047dcaa9678105299e48e70, -0x20bad780930fa2a036fe1dea4ccbf46ac5b3c489818cdb0f97ae49d6e2f11fbf, -0xc0d7dd26ffecdb098585a1694e45a54029bb1e31c7c5209289058efebb4cc91b, -0x9a8744beb1935c0abe4b11812fc02748ef7c8cb650db3024dde3c5463e9d8714, -0x8ce6eea4585bbeb657b326daa4f01f6aef34954338b3ca42074aedd1110ba495, -0x1c85b43f5488b370721290d2faea19d9918d094c99963d6863acdfeeca564363, -0xe88a244347e448349e32d0525b40b18533ea227a9d3e9b78a9ff14ce0a586061, -0x352ca61efc5b8ff9ee78e738e749142dd1606154801a1449bbb278fa6bcc3dbe, -0xa066926f9209220b24ea586fb20eb8199a05a247c82d7af60b380f6237429be7, -0x3052337ccc990bfbae26d2f9fe5d7a4eb8edfb83a03203dca406fba9f4509b6e, -0x343ce573a93c272688a068d758df53c0161aa7f9b55dec8beced363a38b33069, -0x0f16b5593f133b58d706fe1793113a10750e8111eadee65301df7a1e84f782d3, -0x808ae8539357e85b648020f1e9d255bc4114bee731a6220d7c5bcb5b85224e03, -0x3b2bd97e31909251752ac57eda6015bb05b85f2838d475095cfd146677430625, -0xe4f857c93b2d8b250050c7381a6c7c660bd29066195806c8ef11a2e6a6640236, -0x23d91589b5070f443ddcefa0838c596518d54928119251ecf3ec0946a8128f52, -0xb72736dfad52503c7f5f0c59827fb6ef4ef75909ff9526268abc0f296ee37296, -0x80a8c66436d86b8afe87dde7e53a53ef87e057a5d4995963e76d159286de61b6, -0xbec92c09ee5e0c84d5a8ba6ca329683ff550ace34631ea607a3a21f99cd36d67, -0x83c97c9807b9ba6d9d914ae49dabdb4c55e12e35013f9b179e6bc92d5d62222b, -0x8d9c79f6af3920672dc4cf97a297c186e75083d099aeb5c1051207bad0c98964, -0x2aaa5944a2bd852b0b1be3166e88f357db097b001c1a71ba92040b473b30a607, -0x46693d27ec4b764fbb516017c037c441f4558aebfe972cdcd03da67c98404e19, -0x903b25d9e12208438f203c9ae2615b87f41633d5ffda9cf3f124c1c3922ba08f, -0x3ec23dc8bc1b49f5c7160d78008f3f235252086a0a0fa3a7a5a3a53ad29ec410, -0xa1fe74ceaf3cccd992001583a0783d7d7b7a245ea374f369133585b576b9c6d8, -0xb2d6b0fe4932a2e06b99531232398f39a45b0f64c3d4ebeaaebc8f8e50a80607, -0xe19893353f9214eebf08e5d83c6d44c24bffe0eceee4dc2e840d42eab0642536, -0x5b798e4bc099fa2e2b4b5b90335c51befc9bbab31b4dd02451b0abd09c06ee79, -0xbab2cdec1553a408cac8e61d9e6e19fb8ccfb48efe6d02bd49467a26eeeca920, -0x1c1a544c28c38e5c423fe701506693511b3bc5f2af9771b9b2243cd8d41bebfc, -0x704d6549d99be8cdefeec9a58957f75a2be4af7bc3dc4655fa606e7f3e03b030, -0x051330f43fe39b08ed7d82d68c49b36a8bfa31357b546bfb32068712df89d190, -0xe69174c7b03896461cab2dfaab33d549e3aac15e6b0f6f6f466fb31dae709b9b, -0xe5f668603e0ddbbcde585ac41c54c3c4a681fffb7a5deb205344de294758e6ac, -0xca70d5e4c3a81c1f21f246a3f52c41eaef9a683f38eb7c512eac8b385f46cbcd, -0x3173a6b882b21cd147f0fc60ef8f24bbc42104caed4f9b154f2d2eafc3a56907, -0xc71469c192bf5cc36242f6365727f57a19f924618b8a908ef885d8f459833cc3, -0x59c596fc388afd8508bd0f5a1e767f3dda9ed30f6646d15bc59f0b07c4de646f, -0xb200faf29368581f551bd351d357b6fa8cbf90bdc73b37335e51cad36b4cba83, -0x275cede69b67a9ee0fff1a762345261cb20fa8191470159cc65c7885cfb8313c, -0x0ce4ef84916efbe1ba9a0589bed098793b1ea529758ea089fd79151cc9dc7494, -0x0f08483bb720e766d60a3cbd902ce7c9d835d3f7fdf6dbe1f37bcf2f0d4764a2, -0xb30a73e5db2464e6da47d10667c82926fa91fceb337d89a52db5169008bc6726, -0x6b9c50fed1cc404bf2dd6fffbfd18e30a4caa1500bfeb080aa93f78d10331aaf, -0xf17c84286df03ce175966f560600dd562e0f59f18f1d1276b4d8aca545d57856, -0x11455f2ef96a6b2be69854431ee219806008eb80ea38c81e45b2e58b3f975a20, -0x9a61e03e2157a5c403dfcde690f7b7d704dd56ea1716cf14cf7111075a8d6491, -0x30312c910ce6b39e00dbaa669f0fb7823a51f20e83eaeb5afa63fb57668cc2f4, -0x17c18d261d94fba82886853a4f262b9c8b915ed3263b0052ece5826fd7e7d906, -0x2d8f6ea0f5b9d0e4bc1478161f5ed2ad3d8495938b414dcaec9548adbe572671, -0x19954625f13d9bab758074bf6dee47484260d29ee118347c1701aaa74abd9848, -0x842ef2ad456e6f53d75e91e8744b96398df80350cf7af90b145fea51fbbcf067, -0x34a8b0a76ac20308aa5175710fb3e75c275b1ff25dba17c04e3a3e3c48ca222c, -0x58efcbe75f32577afe5e9ff827624368b1559c32fcca0cf4fd704af8ce019c63, -0x411b4d242ef8f14d92bd8b0b01cb4fa3ca6f29c6f9073cfdd3ce614fa717463b, -0xf76dbda66ede5e789314a88cff87ecb4bd9ca418c75417d4d920e0d21a523257, -0xd801821a0f87b4520c1b003fe4936b6852c410ee00b46fb0f81621c9ac6bf6b4, -0x97ad11d6a29c8cf3c548c094c92f077014de3629d1e9053a25dbfaf7eb55f72d, -0xa87012090cd19886d49521d564ab2ad0f18fd489599050c42213bb960c9ee8ff, -0x8868d8a26e758d50913f2bf228da0444a206e52853bb42dd8f90f09abe9c859a, -0xc257fb0cc9970e02830571bf062a14540556abad2a1a158f17a18f14b8bcbe95, -0xfe611ce27238541b14dc174b652dd06719dfbcda846a027f9d1a9e8e9df2c065, -0xc9b25ea410f420cc2d4fc6057801d180c6cab959bce56bf6120f555966e6de6d, -0x95437f0524ec3c04d4132c83be7f1a603e6f4743a85ede25aa97a1a4e3f3f8fc, -0x82a12910104065f35e983699c4b9187aed0ab0ec6146f91728901efecc7e2e20, -0x6622dd11e09252004fb5aaa39e283333c0686065f228c48a5b55ee2060dbd139, -0x89a2879f25733dab254e4fa6fddb4f04b8ddf018bf9ad5c162aea5c858e6faaa, -0x8a71b62075a6011fd9b65d956108fa79cc9ebb8f194d64d3105a164e01cf43a6, -0x103f4fe9ce211b6452181371f0dc4a30a557064b684645a4495136f4ebd0936a, -0x97914adc5d7ce80147c2f44a6b29d0b495d38dedd8cc299064abcc62ed1ddabc, -0x825c481da6c836a8696d7fda4b0563d204a9e7d9e4c47b46ded26db3e2d7d734, -0xf8c0637ba4c0a383229f1d730db733bc11d6a4e33214216c23f69ec965dcaaad, -0xaed3bdaf0cb12d37764d243ee0e8acdefc399be2cabbf1e51dc43454efd79cbd, -0xe8427f56cc5cec8554e2f5f586b57adccbea97d5fc3ef7b8bbe97c2097cf848c, -0xba4ad0abd5c14d526357fd0b6f8676ef6126aeb4a6d80cabe1f1281b9d28246c, -0x4cff20b72e2ab5af3fafbf9222146949527c25f485ec032f22d94567ff91b22f, -0x0d32925d89dd8fed989912afcbe830a4b5f8f7ae1a3e08ff1d3a575a77071d99, -0xe51a1cbeae0be5d2fdbc7941aea904d3eade273f7477f60d5dd6a12807246030, -0xfb8615046c969ef0fa5e6dc9628c8a9880e86a5dc2f6fc87aff216ea83fcf161, -0x64dd705e105c88861470d112c64ca3d038f67660a02d3050ea36c34a9ebf47f9, -0xb6ad148095c97528180f60fa7e8609bf5ce92bd562682092d79228c2e6f0750c, -0x5bae0cd81f3bd0384ca3143a72068e6010b946462a73299e746ca639c026781c, -0xc39a0fc7764fcfc0402b12fb0bbe78fe3633cbfb33c7f849279585a878a26d7c, -0x2b752fda1c0c53d685cc91144f78d371db6b766725872b62cc99e1234cca8c1a, -0x40ee6b9635d87c95a528757729212a261843ecb06d975de91352d43ca3c7f196, -0x75e2005d3726cf8a4bb97ea5287849a361e3f8fdfadc3c1372feed1208c89f6b, -0x0976f8ab556153964b58158678a5297da4d6ad92e284da46052a791ee667aee4, -0xdbeef07841e41e0672771fb550a5b9233ae8e9256e23fa0d34d5ae5efe067ec8, -0xa890f412ab6061c0c5ee661e80d4edc5c36b22fb79ac172ddd5ff26a7dbe9751, -0xb666ae07f9276f6d0a33f9efeb3c5cfcba314fbc06e947563db92a40d7a341e8, -0x83a082cf97ee78fbd7f31a01ae72e40c2e980a6dab756161544c27da86043528, -0xfa726a919c6f8840c456dc77b0fec5adbed729e0efbb9317b75f77ed479c0f44, -0xa8606800c54faeab2cbc9d85ff556c49dd7e1a0476027e0f7ce2c1dc2ba7ccbf, -0x2796277836ab4c17a584c9f6c7778d10912cb19e541fb75453796841e1f6cd1c, -0xf648b8b3c7be06f1f8d9cda13fd6d60f913e5048a8e0b283b110ca427eeb715f, -0xa21d00b8fdcd77295d4064e00fbc30bed579d8255e9cf3a9016911d832390717, -0xe741afcd98cbb3bb140737ed77bb968ac60d5c00022d722f9f04f56e97235dc9, -0xbeecc9638fac39708ec16910e5b02c91f83f6321f6eb658cf8a96353cfb49806, -0x912eee6cabeb0fed8d6e6ca0ba61977fd8e09ea0780ff8fbec995e2a85e08b52, -0xc665bc0bb121a1229bc56ecc07a7e234fd24c523ea14700aa09e569b5f53ad33, -0x39501621c2bdff2f62ab8d8e3fe47fe1701a98c665697c5b750ee1892f11846e, -0x03d32e16c3a6c913daefb139f131e1e95a742b7be8e20ee39b785b4772a50e44, -0x4f504eb46a82d440f1c952a06f143994bc66eb9e3ed865080cd9dfc6d652b69c, -0xad753dc8710a46a70e19189d8fc7f4c773e4d9ccc7a70c354b574fe377328741, -0xf7f5464a2d723b81502adb9133a0a4f0589b4134ca595a82e660987c6b011610, -0x216b60b1c3e3bb4213ab5d43e04619d13e1ecedbdd65a1752bda326223e3ca3e, -0x763664aa96d27b6e2ac7974e3ca9c9d2a702911bc5d550d246631965cf2bd4a2, -0x292b5c8c8431b040c04d631f313d4e6b67b5fd3d4b8ac9f2edb09d13ec61f088, -0x80db43c2b9e56eb540592f15f5900222faf3f75ce62e78189b5aa98c54568a5e, -0x1b5fdf8969bcd4d65e86a2cefb3a673e18d587843f4f50db4e3ee77a0ba2ef1c, -0x11e237953fff3e95e6572da50a92768467ffdfd0640d3384aa1c486357e7c24a, -0x1fabd4faa8dba44808cc87d0bc389654a98496745578f3d17d134adc7f7b10f3, -0x5eca4aa96f20a56197772ae6b600762154ca9d2702cab12664ea47cbff1a440c, -0x0b4234f5bb02abcf3b5ce6c44ea85f55ec7db98fa5a7b90abef6dd0df034743c, -0x316761e295bf350313c4c92efea591b522f1df4211ce94b22e601f30aefa51ef, -0xe93a55ddb4d7dfe02598e8f909ff34b3de40a1c0ac8c7fba48cb604ea60631fb, -0xe6e6c877b996857637f8a71d0cd9a6d47fdeb03752c8965766f010073332b087, -0xa4f95c8874e611eddd2c4502e4e1196f0f1be90bfc37db35f8588e7d81d34aeb, -0x9351710a5633714bb8b2d226e15ba4caa6f50f56c5508e5fa1239d5cc6a7e1aa, -0x8d0aef52ec7266f37adb572913a6213b8448caaf0384008373dec525ae6cdff1, -0x718e24c3970c85bcb14d2763201812c43abac0a7f16fc5787a7a7b2f37288586, -0x3600ce44cebc3ee46b39734532128eaf715c0f3596b554f8478b961b0d6e389a, -0x50dd1db7b0a5f6bd2d16252f43254d0f5d009e59f61ebc817c4bbf388519a46b, -0x67861ed00f5fef446e1f4e671950ac2ddae1f3b564f1a6fe945e91678724ef03, -0x0e332c26e169648bc20b4f430fbf8c26c6edf1a235f978d09d4a74c7b8754aad, -0x6c9901015adf56e564dfb51d41a82bde43fb67273b6911c9ef7fa817555c9557, -0x53c83391e5e0a024f68d5ade39b7a769f10664e12e4942c236398dd5dbce47a1, -0x78619564f0b2399a9fcb229d938bf1e298d62b03b7a37fe6486034185d7f7d27, -0x4625f15381a8723452ec80f3dd0293c213ae35de737c508f42427e1735398c3a, -0x69542425ddb39d3d3981e76b41173eb1a09500f11164658a3536bf3e292f8b6a, -0x82ac4f5bb40aece7d6706f1bdf4dfba5c835c09afba6446ef408d8ec6c09300f, -0x740f9180671091b4c5b3ca59b9515bd0fc751f48e488a9f7f4b6848602490e21, -0x9a04b08b4115986d8848e80960ad67490923154617cb82b3d88656ec1176c24c, -0xf9ffe528eccffad519819d9eef70cef317af33899bcaee16f1e720caf9a98744, -0x46da5e1a14b582b237f75556a0fd108c4ea0d55c0edd8f5d06c59a42e57410df, -0x098f3429c8ccda60c3b5b9755e5632dd6a3f5297ee819bec8de2d8d37893968a, -0x1a5b91af6025c11911ac072a98b8a44ed81f1f3c76ae752bd28004915db6f554, -0x8bed50c7cae549ed4f8e05e02aa09b2a614c0af8eec719e4c6f7aee975ec3ec7, -0xd86130f624b5dcc116f2dfbb5219b1afde4b7780780decd0b42694e15c1f8d8b, -0x4167aa9bc0075f624d25d40eb29139dd2c452ebf17739fab859e14ac6765337a, -0xa258ce5db20e91fb2ea30d607ac2f588bdc1924b21bbe39dc881e19889a7f5c6, -0xe5ef8b5ab3cc8894452d16dc875b69a55fd925808ac7cafef1cd19485d0bb50a, -0x120df2b3975d85b6dfca56bb98a82025ade5ac1d33e4319d2e0105b8de9ebf58, -0xc964291dd2e0807a468396ebba3d59cfe385d949f6d6215976fc9a0a11de209a, -0xf23f14cb709074b79abe166f159bc52b50de687464df6a5ebf112aa953c95ad5, -0x622c092c9bd7e30f880043762e26d8e9c73ab7c0d0806f3c5e472a4152b35a93, -0x8a5f090662731e7422bf651187fb89812419ab6808f2c62da213d6944fccfe9f, -0xfbea3c0d92e061fd2399606f42647d65cc54191fa46d57b325103a75f5c22ba6, -0x2babfbcc08d69b52c3747ddc8dcad4ea5511edabf24496f3ff96a1194d6f680e, -0x4d3d019c28c779496b616d85aee201a3d79d9eecf35f728d00bcb12245ace703, -0xe76fcee1f08325110436f8d4a95476251326b4827399f9b2ef7e12b7fb9c4ba1, -0x4884d9c0bb4a9454ea37926591fc3eed2a28356e0506106a18f093035638da93, -0x74c3f303d93d4cc4f0c1eb1b4378d34139220eb836628b82b649d1deb519b1d3, -0xacb806670b278d3f0c84ba9c7a68c7df3b89e3451731a55d7351468c7c864c1c, -0x8660fb8cd97e585ea7a41bccb22dd46e07eee8bbf34d90f0f0ca854b93b1ebee, -0x2fc9c89cdca71a1c0224d469d0c364c96bbd99c1067a7ebe8ef412c645357a76, -0x8ec6d5ab6ad7135d66091b8bf269be44c20af1d828694cd8650b5479156fd700, -0x50ab4776e8cabe3d864fb7a1637de83f8fbb45d6e49645555ffe9526b27ebd66, -0xbf39f5e17082983da4f409f91c7d9059acd02ccbefa69694aca475bb8d40b224, -0x3135b3b981c850cc3fe9754ec6af117459d355ad6b0915beb61e84ea735c31bf, -0xa7971dab52ce4bf45813223b0695f8e87f64b614c9c5499faac6f842e5c41be9, -0x9e480f5617323ab104b4087ac4ef849a5da03427712fb302ac085507c77d8f37, -0x57a6d474654d5e8d408159be39ad0e7026e6a4c6a6543e23a63d30610dc8dfc1, -0x09eb3e01a5915a4e26d90b4c58bf0cf1e560fdc8ba53faed9d946ad3e9bc78fa, -0x29c6d25da80a772310226b1b89d845c7916e4a4bc94d75aa330ec3eaa14b1e28, -0x1a1ccfee11edeb989ca02e3cb89f062612a22a69ec816a625835d79370173987, -0x1cb63dc541cf7f71c1c4e8cabd2619c3503c0ea1362dec75eccdf1e9efdbfcfc, -0xac9dff32a69e75b396a2c250e206b36c34c63b955c9e5732e65eaf7ccca03c62, -0x3e1b4f0c3ebd3d38cec389720147746774fc01ff6bdd065f0baf2906b16766a8, -0x5cc8bed25574463026205e90aad828521f8e3d440970d7e810d1b46849681db5, -0x255185d264509bd3a768bb0d50b568e66eb1fec96d573e33aaacc716d7c8fb93, -0xe81b86ba631973918a859ff5995d7840b12511184c2865401f2693a71b9fa07e, -0x61e67e42616598da8d36e865b282127c761380d3a56d26b8d35fbbc7641433c5, -0x60c62ffef83fe603a34ca20b549522394e650dad5510ae68b6e074f0cd209a56, -0x78577f2caf4a54f6065593535d76216f5f4075af7e7a98b79571d33b1822920c, -0xfd4cb354f2869c8650200de0fe06f3d39e4dbebf19b0c1c2677da916ea84f44d, -0x453769cef6ff9ba2d5c917982a1ad3e2f7e947d9ea228857556af0005665e0b0, -0xe567f93f8f88bf1a6b33214f17f5d60c5dbbb531b4ab21b8c0b799b6416891e0, -0x7e65a39a17f902a30ceb2469fe21cba8d4e0da9740fcefd5c647c81ff1ae95fa, -0x03e4a7eea0cd6fc02b987138ef88e8795b5f839636ca07f6665bbae9e5878931, -0xc3558e2b437cf0347cabc63c95fa2710d3f43c65d380feb998511903f9f4dcf0, -0xe3a615f80882fb5dfbd08c1d7a8b0a4d3b651d5e8221f99b879cb01d97037a9c, -0xb56db4a5fea85cbffaee41f05304689ea321c40d4c108b1146fa69118431d9b2, -0xab28e1f077f18117945910c235bc9c6f9b6d2b45e9ef03009053006c637e3e26, -0xefcabc1d5659fd6e48430dbfcc9fb4e08e8a9b895f7bf9b3d6c7661bfc44ada2, -0xc7547496f212873e7c3631dafaca62a6e95ac39272acf25a7394bac6ea1ae357, -0xc482013cb01bd69e0ea9f447b611b06623352e321469f4adc739e3ee189298eb, -0x5942f42e91e391bb44bb2c4d40da1906164dbb6d1c184f00fa62899baa0dba2c, -0xb4bcb46c80ad4cd603aff2c1baf8f2c896a628a46cc5786f0e58dae846694677, -0xd0a7305b995fa8c317c330118fee4bfef9f65f70b54558c0988945b08e90ff08, -0x687f801b7f32fdfa7d50274cc7b126efedbdae8de154d36395d33967216f3086, -0xeb19ec10ac6c15ffa619fa46792971ee22a9328fa53bd69a10ed6e9617dd1bbf, -0xa2bb3f0367f62abdb3a9fa6da34b20697cf214a4ff14fd42826da140ee025213, -0x070a76511f32c882374400af59b22d88974a06fbc10d786dd07ca7527ebd8b90, -0x8f195689537b446e946b376ec1e9eb5af5b4542ab47be550a5700fa5d81440d5, -0x10cc09778699fc8ac109e7e6773f83391eeba2a6db5226fbe953dd8d99126ca5, -0x8cc839cb7dc84fd3b8c0c7ca637e86a2f72a8715cc16c7afb597d12da717530b, -0xa32504e6cc6fd0ee441440f213f082fcf76f72d36b5e2a0f3b6bdd50cdd825a2, -0x8f45151db8878e51eec12c450b69fa92176af21a4543bb78c0d4c27286e74469, -0x23f5c465bd35bcd4353216dc9505df68324a27990df9825a242e1288e40a13bb, -0x35f409ce748af33c20a6ae693b8a48ba4623de9686f9834e22be4410e637d24f, -0xb962e5845c1db624532562597a99e2acc5e434b97d8db0725bdeddd71a98e737, -0x0f8364f99f43dd52b4cfa9e426c48f7b6ab18dc40a896e96a09eceebb3363afe, -0xa842746868da7644fccdbb07ae5e08c71a6287ab307c4f9717eadb414c9c99f4, -0xa59064c6b7fe7d2407792d99ed1218d2dc2f240185fbd8f767997438241b92e9, -0xb6ea0d58e8d48e05b9ff4d75b2ebe0bd9752c0e2691882f754be66cdec7628d3, -0xf16b78c9d14c52b2b5156690b6ce37a5e09661f49674ad22604c7d3755e564d1, -0xbfa8ef74e8a37cd64b8b4a4260c4fc162140603f9c2494b9cf4c1e13de522ed9, -0xf4b89f1776ebf30640dc5ec99e43de22136b6ef936a85193ef940931108e408a, -0xefb9a4555d495a584dbcc2a50938f6b9827eb014ffae2d2d0aae356a57894de8, -0x0627a466d42a26aca72cf531d4722e0e5fc5d491f4527786be4e1b641e693ac2, -0x7d10d21542de3d8f074dbfd1a6e11b3df32c36272891aae54053029d39ebae10, -0x0f21118ee9763f46cc175a21de876da233b2b3b62c6f06fa2df73f6deccf37f3, -0x143213b96f8519c15164742e2350cc66e814c9570634e871a8c1ddae4d31b6b5, -0x8d2877120abae3854e00ae8cf5c8c95b3ede10590ab79ce2be7127239507e18d, -0xaccd0005d59472ac04192c059ed9c10aea42c4dabec9e581f6cb10b261746573, -0x67bc8dd5422f39e741b9995e6e60686e75d6620aa0d745b84191f5dba9b5bb18, -0x11b8e95f6a654d4373cefbbac29a90fdd8ae098043d1969b9fa7885318376b34, -0x431a0b8a6f08760c942eeff5791e7088fd210f877825ce4dcabe365e03e4a65c, -0x704007f11bae513f428c9b0d23593fd2809d0dbc4c331009856135dafec23ce4, -0xc06dee39a33a05e30c522061c1d9272381bde3f9e42fa9bd7d5a5c8ef11ec6ec, -0x66b4157baaae85db0948ad72882287a80b286df2c40080b8da4d5d3db0a61bd2, -0xef1983b1906239b490baaaa8e4527f78a57a0a767d731f062dd09efb59ae8e3d, -0xf26d0d5c520cce6688ca5d51dee285af26f150794f2ea9f1d73f6df213d78338, -0x8b28838382e6892f59c42a7709d6d38396495d3af5a8d5b0a60f172a6a8940bd, -0x261a605fa5f2a9bdc7cffac530edcf976e7ea7af4e443b625fe01ed39dad44b6] -compressed_lamport_PK = 0xdd635d27d1d52b9a49df9e5c0c622360a4dd17cba7db4e89bce3cb048fb721a5 -child_SK = 20397789859736650942317412262472558107875392172444076792671091975210932703118 -``` - -## Implementation - -* [Python](https://github.com/ethereum/eth2.0-deposit-cli) - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2333.md diff --git a/EIPS/eip-2334.md b/EIPS/eip-2334.md index 76a9b198d3941d..1ef3c8d3734535 100644 --- a/EIPS/eip-2334.md +++ b/EIPS/eip-2334.md @@ -1,104 +1,7 @@ --- eip: 2334 -title: BLS12-381 Deterministic Account Hierarchy -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2338 -status: Stagnant -type: Standards Track category: ERC -created: 2019-09-30 -requires: 2333 +status: Moved --- -## Simple Summary - -This EIP defines the purpose of a given key, or family thereof, within a tree of keys. When combined with [EIP-2333](./eip-2333.md), the combination of a seed and knowledge of the desired purpose of a key is sufficient to determine a key pair. - -## Abstract - -A standard for allocating keys generated by [EIP-2333](./eip-2333.md) to a specific purpose. It defines a `path` which is a string that parses into the indices to be used when traversing the tree of keys that [EIP-2333](./eip-2333.md) generates. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted [BLS signatures over BLS12-381](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -Ethereum 2.0 alongside many other projects will use BLS signatures over BLS12-381, an [IETF proposed standard](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). This new scheme requires a new key derivation mechanism, which is established within [EIP-2333](./eip-2333.md). This new scheme is incompatible with the current form of this specification ([BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) due to the: exclusive use of hardened keys, the increased number of keys per level, not using [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) for key derivation. It is therefore necessary to establish a new *path* for traversing the [EIP-2333](./eip-2333.md) key-tree. - -The path structure specified in this EIP aims to be more general than [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) by not having UTXO-centric features [which gave rise to the 4 different types of wallet paths being used within Ethereum 1.0](https://github.com/ethereum/EIPs/issues/84#issuecomment-292324521) and gave rise to (draft) [EIP-600](./eip-600.md) & [EIP-601](./eip-601.md) - -## Specification - -### Path - -The path traversed through the tree of keys is defined by integers (which indicate the sibling index) separated by `/` which denote ancestor relations. There are 4 levels (plus the master node) in the path and at least 4 (5 including the master node) MUST be used. - -```text -m / purpose / coin_type / account / use -``` - -#### Notation - -The notation used within the path is specified within the [EIP-2333](./eip-2333.md), but is summarized again below for convenience. - -* `m` Denotes the master node (or root) of the tree -* `/` Separates the tree into depths, thus `i / j` signifies that `j` is a child of `i` - -### Purpose - -The `purpose` is set to `12381` which is the name of the new curve (BLS12-381). In order to be in compliance with this standard, the [EIP-2333](./eip-2333.md) MUST be implemented as the KDF and therefore, the purpose `12381` MAY NOT be used unless this is the case. - -### Coin Type - -The `coin_type` here reflects the coin number for an individual coin thereby acting as a means of separating the keys used for different chains. - -### Account - -`account` is a field that provides the ability for a user to have distinct sets of keys for different purposes, if they so choose. This is the level at which different accounts for a single user SHOULD to be implemented. - -### Use - -This level is designed to provide a set of related keys that can be used for any purpose. The idea being that a single account has many uses which are related yet should remain separate for security reasons. It is required to support this level in the tree, although, for many purposes it will remain `0`. - -### Eth2 Specific Parameters - -#### Coin type - -The coin type used for the BLS12-381 keys in Ethereum 2 is `3600`. - -#### Validator keys - -Each Eth2 validator has two keys, one for withdrawals and transfers (called the *withdrawal key*), and the other for performing their duties as a validator (henceforth referred to as the *signing key*). - -The path for withdrawal keys is `m/12381/3600/i/0` where `i` indicates the `i`th set of validator keys. - -The path for the signing key is `m/12381/3600/i/0/0` where again, `i` indicates the `i`th set of validator keys. Another way of phrasing this is that the signing key is the `0`th child of the associated withdrawal key for that validator. - -**Note:** If the above description of key paths is not feasible in a specific use case (eg. with secret-shared or custodial validators), then the affected keys may be omitted and derived via another means. Implementations of this EIP, must endeavour to use the appropriate keys for the given use case to the extent that is reasonably possible. (eg, in the case of custodial staking, the user making the deposits will follow this standard for their withdrawal keys which has no bearing on how the service provide derives the corresponding signing keys.) - -## Rationale - -`purpose`, `coin_type`, and `account` are widely-adopted terms as per [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) and therefore reusing these terms and their associated meanings makes sense. - -The purpose needs to be distinct from these standards as the KDF and path are not inter-compatible and `12381` is an obvious choice. - -`account` separates user activity into distinct categories thereby allowing users to separate their concerns however they desire. - -`use` will commonly be determined at the application level providing distinct keys for non-intersecting use cases. - -### Eth2 Specific Parameters - -A new coin type is chosen for Eth2 keys to help ensure a clean separation between Eth2 and Eth1 keys. Although the distinction between Eth1 ETH and Eth2 ETH is subtle, they are distinct entities and there are services which only distinguish between coins by their coin name (eg. [ENS' multichain address resolution](./eip-2304.md)). `3600` is chosen specifically because it is the square of the Eth1's `coin_type` (`3600==60^2`) thereby signaling that it is second instantiation of Ether the currency. - -The primary reason validators have separate signing and withdrawal keys is to allow for the different security concerns of actions within Eth2. The signing key is given to the validator client where it signs messages as per the requirements of being a validator, it is therefore a "hot key". If this key is compromised, the worst that can happen (locally) is that a slashable message is signed, resulting in the validator being slashed and forcibly exited. The withdrawal key is only needed when a validator wishes to perform an action not related to validating and has access to the full funds at stake for that validator. The withdrawal key therefore has higher security concerns and should be handled as a "cold key". By having the signing key be a child of the withdrawal key, secure storage of the withdrawal key is sufficient to recover the signing key should the need arise. - -## Backwards Compatibility - -[BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) are the commonly used standards for this purpose within Ethereum 1.0, however they have not been `Accepted` as standards as yet. Due to the use of a new KDF within [EIP-2333](./eip-2333.md), a new path standard is required. This EIP implements this, with minor changes. - -`purpose` `12381` paths do not support hardened keys and therefore the `'` character is invalid. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2334.md diff --git a/EIPS/eip-2335.md b/EIPS/eip-2335.md index 43ca6240e06a81..31c28f3c0cb014 100644 --- a/EIPS/eip-2335.md +++ b/EIPS/eip-2335.md @@ -1,301 +1,7 @@ --- eip: 2335 -title: BLS12-381 Keystore -author: Carl Beekhuizen -discussions-to: https://github.com/ethereum/EIPs/issues/2339 -status: Stagnant -type: Standards Track category: ERC -created: 2019-09-30 -requires: 2333, 2334 +status: Moved --- -## Simple Summary - -A JSON format for the storage and interchange of BLS12-381 private keys. - -## Abstract - -A keystore is a mechanism for storing private keys. It is a JSON file that encrypts a private key and is the standard for interchanging keys between devices as until a user provides their password, their key is safe. - -## A note on purpose - -This specification is designed not only to be an Ethereum 2.0 standard, but one that is adopted by the wider community who have adopted the BLS12-381 signature standard. It is therefore important also to consider the needs of the wider industry along with those specific to Ethereum. As a part of these considerations, it is the intention of the author that this standard eventually migrate to a more neutral repository in the future. - -## Motivation - -The secure storage and exchange of keys is a vital component of the user experience as people are expected to hold their own keys. It allows users to control access to individual keys and their use by applications. - -In Ethereum 1, [the Web3 Secret Storage Definition](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) fulfills these requirements, however it is not perfectly suitable for these purposes moving forward. Specifically the problems with the existing standard are: - -* __The use of Keccak256.__ Eth1 keystores use Keccak for their checksum, a sensible choice considering its usage within Ethereum 1. BLS12-381 [signatures](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-00), [keys (EIP-2333)](./eip-2333.md), and key-storage are inter-chain standards, the establishment and proliferation of which hinges on them being neutral to all chains, something which Keccak is not. - -* __A lack of abstraction.__ Eth1 keystores are a result of an iterative design process whereby functionality was added and modified as needed without considering how abstractions could simplify the notion of different properties. - -## Specification - -The process of decrypting the secret held within a keystore can be broken down into 3 sub-processes: obtaining the decryption key, verifying the password and decrypting the secret. Each process has its own functions which can be selected from as well as parameters required for the function all of which are specified within the keystore file itself. - -### Password requirements - -The password is a string of arbitrary unicode characters. The password is first converted to its NFKD representation, then the control codes (specified below) are stripped from the password and finally it is UTF-8 encoded. - -#### Control codes removal - -The C0, C1, and `Delete` control codes are not valid characters in the password and should therefore be stripped from the password. C0 are the control codes between `0x00` - `0x1F` (inclusive) and C1 codes lie between `0x80` and `0x9F` (inclusive). `Delete`, commonly known as "backspace", is the UTF-8 character `7F` which must also be stripped. Note that space (`Sp` UTF-8 `0x20`) is a valid character in passwords despite it being a pseudo-control character. - -### Modules - -This standard makes use of the notion of a _module_ which serves to represent, in an abstract sense, the different  cryptographic constructions and corresponding parameters for each component of the keystore. The idea being that components can be swapped out without affecting the rest of the specification should the need arise. - -A module is comprised of a `function`, which defines which cryptographic construct is being used, `params`, the parameters required by the function, and `message` the primary input to the function. - -### Decryption key - -The decryption key is an intermediate key which is used both to verify the user-supplied password is correct, as well as for the final secret decryption. This key is simply derived from the password, the `function`, and the `params` specified by the`kdf` module as per the keystore file. - -| KDF | `"function"` | `"params"` | `"message"` | Definition | -|----------------|--------------|------------------------------------------------------------------------------------------|-------------|--------------------------------------------------| -| PBKDF2-SHA-256 | `"pbkdf2"` |
  • `"c"`
  • `"dklen"`
  • `"prf: "hmac-sha256"`
  • `"salt"`
| | [RFC 2898](https://www.ietf.org/rfc/rfc2898.txt) | -| scrypt | `"scrypt"` |
  • `"dklen"`
  • `"n"`
  • `"p"`
  • `"r"`
  • `"salt"`
| | [RFC 7914](https://tools.ietf.org/html/rfc7914) | - -### Password verification - -The password verification step verifies that the password is correct with respect to the `checksum.message`, `cipher.message`, and `kdf`. This is done by appending the `cipher.message` to the 2nd 16 bytes of the decryption key, obtaining its SHA256 hash and verifying whether it matches the `checksum.message`. - -#### Inputs - -* `decryption_key`, the octet string obtained from decryption key process -* `cipher_message`, the octet string obtained from keystore file from `crypto.cipher.message` -* `checksum_message`, the octet string obtained from keystore file from `crypto.checksum.message` - -#### Outputs - -* `valid_password`, a boolean value indicating whether the password is valid - -#### Definitions - -* `a[0:3]` returns a slice of `a` including octets 0, 1, 2 -* `a | b` is the concatenation of `a` with `b` - -#### Procedure - -```text -0. DK_slice = decryption_key[16:32] -1. pre_image = DK_slice | cipher_message -2. checksum = SHA256(pre_image) -3. valid_password = checksum == checksum_message -4. return valid_password -``` - -| Hash | `"function"` | `"params"` | `"message"` | Definition | -|------------|-----------------|------------|-------------|-------------------------------------------------| -| SHA-256 | `"sha256"` | | | [RFC 6234](https://tools.ietf.org/html/rfc6234) | - -### Secret decryption - -The `cipher.function` encrypts the secret using the decryption key, thus to decrypt it, the decryption key along with the `cipher.function` and `cipher.params` must be used. If the `decryption_key` is longer than the key size required by the cipher, it is truncated to the correct number of bits. In the case of aes-128-ctr, only the first 16 bytes of the `decryption_key` are used as the AES key. - -| Cipher | `"function"` | `"params"` | `"message"` | Definition | -|----------------------|-----------------|--------------------------|-------------|-------------------------------------------------| -| AES-128 Counter Mode | `"aes-128-ctr"` |
  • `"iv"`
| | [RFC 3686](https://tools.ietf.org/html/rfc3686) | - -## Description - -This field is an optional field to help explain the purpose and identify a particular keystores in a user-friendly manner. While this field can, and should, be used to help distinguish keystores from one-another, the `description` **is not necessarily unique**. - -## PubKey - -The `pubkey` is the public key associated with the the private key secured within the keystore. It is stored here to improve user experience and security which is achieved by not requiring users to enter their password just to obtain their public keys. This field is required if the secret being stored within the keystore is a private key. The encoding of the `pubkey` is specified in the in the appropriate signature standard (eg. [BLS12-381 signature standard](https://tools.ietf.org/html/draft-irtf-cfrg-bls-signature-00)), but can be seen as a byte-string in the abstract and should be directly compatible with the appropriate signature library. - -## Path - -The `path` indicates where in the key-tree a key originates from. It is a string defined by [EIP-2334](./eip-2334.md), if no path is known or the path is not relevant, the empty string, `""` indicates this. The `path` can specify an arbitrary depth within the tree and the deepest node within the tree indicates the depth of the key stored within this file. - -## UUID - -The `uuid` provided in the keystore is a randomly generated UUID as specified by [RFC 4122](https://tools.ietf.org/html/rfc4122). It is used as a 128-bit proxy for referring to a particular set of keys or account. - -## Version - -The `version` is set to `4`. - -## JSON schema - -The keystore, at its core, is constructed with modules which allow for the configuration of the cryptographic constructions used password hashing, password verification and secret decryption. Each module is composed of: `function`, `params`, and `message` which corresponds with which construction is to be used, what the configuration for the construction is, and what the input is. - -```json -{ - "$ref": "#/definitions/Keystore", - "definitions": { - "Keystore": { - "type": "object", - "properties": { - "crypto": { - "type": "object", - "properties": { - "kdf": { - "$ref": "#/definitions/Module" - }, - "checksum": { - "$ref": "#/definitions/Module" - }, - "cipher": { - "$ref": "#/definitions/Module" - } - } - }, - "description": { - "type": "string" - }, - "pubkey": { - "type": "string" - }, - "path": { - "type": "string" - }, - "uuid": { - "type": "string", - "format": "uuid" - }, - "version": { - "type": "integer" - } - }, - "required": [ - "crypto", - "path", - "uuid", - "version" - ], - "title": "Keystore" - }, - "Module": { - "type": "object", - "properties": { - "function": { - "type": "string" - }, - "params": { - "type": "object" - }, - "message": { - "type": "string" - } - }, - "required": [ - "function", - "message", - "params" - ] - } - } -} -``` - -## Rationale - -The rationale behind the design of this specification is largely the same as that behind the [Ethereum 1 keystore definition](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) except for the lack of support for Keccak (explained in [motivation above](#motivation)) and the notion of modules. - -Modules provide a very useful level of abstraction which allow the Key-Derivation-Function, Checksum, and Cipher to be thought of as instances of the same thing allowing for their substitution with minimal effort. - -The `version` is set to 4 to prevent collisions with the existing Ethereum keystore standard. - -## Backwards Compatibility - -This specification is not backwards compatible with the [existing keystore standard](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) due to the lack of Keccak256 checksums as explained above. While this format is capable of supporting Keccak checksums via the Checksum module, it would defeat the purpose of this standard to include it as this standard could no longer be considered neutral with respect to other projects in the industry. - -## Test Cases - -### Scrypt Test Vector - -Password `"𝔱𝔢𝔰𝔱𝔭𝔞𝔰𝔰𝔴𝔬𝔯𝔡🔑"` -Encoded Password: `0x7465737470617373776f7264f09f9491` -Secret `0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f` - -```json -{ - "crypto": { - "kdf": { - "function": "scrypt", - "params": { - "dklen": 32, - "n": 262144, - "p": 1, - "r": 8, - "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" - }, - "message": "" - }, - "checksum": { - "function": "sha256", - "params": {}, - "message": "d2217fe5f3e9a1e34581ef8a78f7c9928e436d36dacc5e846690a5581e8ea484" - }, - "cipher": { - "function": "aes-128-ctr", - "params": { - "iv": "264daa3f303d7259501c93d997d84fe6" - }, - "message": "06ae90d55fe0a6e9c5c3bc5b170827b2e5cce3929ed3f116c2811e6366dfe20f" - } - }, - "description": "This is a test keystore that uses scrypt to secure the secret.", - "pubkey": "9612d7a727c9d0a22e185a1c768478dfe919cada9266988cb32359c11f2b7b27f4ae4040902382ae2910c15e2b420d07", - "path": "m/12381/60/3141592653/589793238", - "uuid": "1d85ae20-35c5-4611-98e8-aa14a633906f", - "version": 4 -} -``` - -### PBKDF2 Test Vector - -Password `"𝔱𝔢𝔰𝔱𝔭𝔞𝔰𝔰𝔴𝔬𝔯𝔡🔑"` -Encoded Password: `0x7465737470617373776f7264f09f9491` -Secret `0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f` - -```json -{ - "crypto": { - "kdf": { - "function": "pbkdf2", - "params": { - "dklen": 32, - "c": 262144, - "prf": "hmac-sha256", - "salt": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" - }, - "message": "" - }, - "checksum": { - "function": "sha256", - "params": {}, - "message": "8a9f5d9912ed7e75ea794bc5a89bca5f193721d30868ade6f73043c6ea6febf1" - }, - "cipher": { - "function": "aes-128-ctr", - "params": { - "iv": "264daa3f303d7259501c93d997d84fe6" - }, - "message": "cee03fde2af33149775b7223e7845e4fb2c8ae1792e5f99fe9ecf474cc8c16ad" - } - }, - "description": "This is a test keystore that uses PBKDF2 to secure the secret.", - "pubkey": "9612d7a727c9d0a22e185a1c768478dfe919cada9266988cb32359c11f2b7b27f4ae4040902382ae2910c15e2b420d07", - "path": "m/12381/60/0/0", - "uuid": "64625def-3331-4eea-ab6f-782f3ed16a83", - "version": 4 -} -``` - -## Implementation - -Implementations exist in the following languages: - -* [Python3](https://github.com/ethereum/eth2.0-deposit-cli) -* [TypeScript](https://github.com/nodefactoryio/bls-keystore) -* [Go](https://github.com/wealdtech/go-eth2-wallet-encryptor-keystorev4/) - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2335.md diff --git a/EIPS/eip-2386.md b/EIPS/eip-2386.md index f09e375c76fe54..a942265254e8ed 100644 --- a/EIPS/eip-2386.md +++ b/EIPS/eip-2386.md @@ -1,201 +1,7 @@ --- eip: 2386 -title: Ethereum 2 Hierarchical Deterministic Walletstore -author: Jim McDonald -discussions-to: https://ethereum-magicians.org/t/eip-2386-walletstore/3792 -status: Stagnant -type: Standards Track category: ERC -created: 2019-11-21 -requires: 2334, 2335 +status: Moved --- -## Simple Summary - -A JSON format for the storage and retrieval of Ethereum 2 hierarchical deterministic (HD) wallet definitions. - -## Abstract - -Ethereum has the concept of keystores: pieces of data that define a key (see [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335) for details). This adds the concept of walletstores: stores that define wallets and how keys in said wallets are created. - -## Motivation - -Hierarchical deterministic wallets create keys from a _seed_ and a _path_. The seed needs to be accessible to create new keys, however it should also be protected to the same extent as private keys to stop it from becoming an easy attack vector. The path, or at least the variable part of it, needs to be stored to ensure that keys are not duplicated. Providing a standard method to do this can promote interoperability between wallets and similar software. - -Given that a wallet has an amount of data and metadata that is useful when accessing existing keys and creating new keys, standardizing this information and how it is stored allows it to be portable between different wallet providers with minimal effort. - -## Specification - -The elements of a hierarchical deterministic walletstore are as follows: - -### UUID - -The `uuid` provided in the walletstore is a randomly-generated type 4 UUID as specified by [RFC 4122](https://tools.ietf.org/html/rfc4122). It is intended to be used as a 128-bit proxy for referring to a particular wallet, used to uniquely identify wallets. - -This element MUST be present. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Name - -The `name` provided in the walletstore is a UTF-8 string. It is intended to serve as the user-friendly accessor. The only restriction on the name is that it MUST NOT start with the underscore (`_`) character. - -This element MUST be present. It MUST be a string. - -### Version - -The `version` provided is the version of the walletstore. - -This element MUST be present. It MUST be the integer `1`. - -### Type - -The `type` provided is the type of wallet. This informs mechanisms such as key generation. - -This element MUST be present. It MUST be the string `hierarchical deterministic`. - -### Crypto - -The `crypto` provided is the secure storage of a secret for wallets that require this information. For hierarchical deterministic wallets this is the seed from which they calculate individual private keys. - -This element MUST be present. It MUST be an object that follows the definition described in [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335). - -### Next Account - -The `nextaccount` provided is the index to be supplied to the path `m/12381/60//0` when creating a new private key from the seed. The path follows [EIP-2334](https://eips.ethereum.org/EIPS/eip-2334). - -This element MUST be present if the wallet type requires it. It MUST be a non-negative integer. - -### JSON schema - -The walletstore follows a similar format to that of the keystore described in [EIP-2335](https://eips.ethereum.org/EIPS/eip-2335). - -```json -{ - "$ref": "#/definitions/Walletstore", - "definitions": { - "Walletstore": { - "type": "object", - "properties": { - "crypto": { - "type": "object", - "properties": { - "kdf": { - "$ref": "#/definitions/Module" - }, - "checksum": { - "$ref": "#/definitions/Module" - }, - "cipher": { - "$ref": "#/definitions/Module" - } - } - }, - "name": { - "type": "string" - }, - "nextaccount": { - "type": "integer" - }, - "type": { - "type": "string" - }, - "uuid": { - "type": "string", - "format": "uuid" - }, - "version": { - "type": "integer" - } - }, - "required": [ - "name", - "type", - "uuid", - "version" - "crypto" - "nextaccount" - ], - "title": "Walletstore" - }, - "Module": { - "type": "object", - "properties": { - "function": { - "type": "string" - }, - "params": { - "type": "object" - }, - "message": { - "type": "string" - } - }, - "required": [ - "function", - "message", - "params" - ] - } - } -} -``` - -## Rationale - -A standard for walletstores, similar to that for keystores, provides a higher level of compatibility between wallets and allows for simpler wallet and key interchange between them. - -## Test Cases - -### Test Vector - -Password `'testpassword'` -Seed `0x147addc7ec981eb2715a22603813271cce540e0b7f577126011eb06249d9227c` - -```json -{ - "crypto": { - "checksum": { - "function": "sha256", - "message": "8bdadea203eeaf8f23c96137af176ded4b098773410634727bd81c4e8f7f1021", - "params": {} - }, - "cipher": { - "function": "aes-128-ctr", - "message": "7f8211b88dfb8694bac7de3fa32f5f84d0a30f15563358133cda3b287e0f3f4a", - "params": { - "iv": "9476702ab99beff3e8012eff49ffb60d" - } - }, - "kdf": { - "function": "pbkdf2", - "message": "", - "params": { - "c": 16, - "dklen": 32, - "prf": "hmac-sha256", - "salt": "dd35b0c08ebb672fe18832120a55cb8098f428306bf5820f5486b514f61eb712" - } - } - }, - "name": "Test wallet 2", - "nextaccount": 0, - "type": "hierarchical deterministic", - "uuid": "b74559b8-ed56-4841-b25c-dba1b7c9d9d5", - "version": 1 -} -``` - -## Implementation - -A Go implementation of the hierarchical deterministic wallet can be found at [https://github.com/wealdtech/go-eth2-wallet-hd](https://github.com/wealdtech/go-eth2-wallet-hd). - -## Security Considerations - -The seed stored in the `crypto` section of the wallet can be used to generate any key along the derived path. As such, the security of all keys generated by HD wallets is reduced to the security of the passphrase and strength of the encryption used to protect the seed, regardless of the security of the passphrase and strength of the encryption used to protect individual keystores. - -It is possible to work with only the walletstore plus an index for each key, in which case stronger passphrases can be used as decryption only needs to take place once. It is also possible to use generated keystores without the walletstore, in which case a breach of security will expose only the keystore. - -An example high-security configuration may involve the walletstore existing on an offline computer, from which keystores are generated. The keystores can then be moved individually to an online computer to be used for signing. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2386.md diff --git a/EIPS/eip-2390.md b/EIPS/eip-2390.md index 4d87272c0810ad..9ab3fca65cf6d3 100644 --- a/EIPS/eip-2390.md +++ b/EIPS/eip-2390.md @@ -1,316 +1,7 @@ --- eip: 2390 -title: Geo-ENS -author: James Choncholas (@james-choncholas) -discussions-to: https://github.com/ethereum/EIPs/issues/2959 -status: Stagnant -type: Standards Track category: ERC -created: 2019-11-15 -requires: 137, 165, 1062, 1185 +status: Moved --- -## Simple Summary -GeoENS brings geographic split horizon capabilities to ENS. It's GeoDNS for ENS! - -## Abstract -This EIP specifies an ENS resolver interface for geographically split horizon DNS. -Geographic split horizon DNS returns resource records that are specific to an end -user's location. -This technique is commonly used by CDNs to direct traffic to content caches nearest users. -Geographic split horizon resolution is primarily geared towards ENS -resolvers storing DNS resource records [EIP-1185](./eip-1185.md), although the technique could be -used on other interfaces like IPFS content hash storage [EIP-1062](./eip-1062.md). - -## Motivation -There are many use cases for traditional GeoDNS systems, like Amazon's Route53, -in the centralized web. -These use cases include proximity-based load balancing and serving content -specific to the geographic location of the query. -Unfortunately the ENS specification does not provide a mechanism for -geo-specific resolution. -ENS can respond to queries with IP addresses (as described in [EIP-1185](./eip-1185.md)) -however there is no way to respond to geo-specific queries. -This EIP proposes a standard to give the ENS system geo-proximal awareness -to serve a similar purpose as GeoDNS. - -GeoENS can do more than DNS-based solutions. -In addition to geographic split horizon DNS, GeoENS can be used for the following: - - Locating digital resources (like smart contracts) that represent physical objects in the real world. - - Smart contract managing access to a physical object associated with a specific location. - - ENS + IPFS web hosting (as described in [EIP-1062](./eip-1062.md)) with content translated to the native language of the query source. - - Tokenizing objects with a physical location. - -Because of the decentralized nature of ENS, geo-specific resolution is different than traditional GeoDNS. -GeoDNS works as follows. DNS queries are identified by their source IP address. -This IP is looked up in a database like [GeoIP2](https://www.maxmind.com/en/geoip2-services-and-databases) -from MaxMind which maps the IP address to a location. -This method of locating the source of a query is error prone and unreliable. -If the GeoIP database is out of date, queried locations can be vastly different than their true location. -GeoENS does not rely on a database because the user includes a location in their query. - -It follows that queries can be made by users for any location, not just their location. -Traditional DNS will only return the resource assigned to a query's provenance. -GeoENS does not correlate a query's provinance with a location, allowing the -entire globe to be queried from a single location. - -An additional shortcoming of traditional DNS is the fact that there is no way to return a list of servers in a certain proximity. -This is paramount for uses cases that require discovering the resource with the lowest latency. -GeoENS allows a list of resources, like IP addresses, to be gathered within a specific location. -Then a client to determine themselves which resource has the lowest latency. - -Lastly, publicly facing GeoDNS services do not give fine granularity control -over geographic regions for GeoDNS queries. -Cloud based DNS services like [Amazon's Route 53](https://aws.amazon.com/route53/) -only allow specifying geographic regions at the granularity of a State in -the United States. -GeoENS on the other hand gives 8 characters of geohash resolution which -corresponds to +-20 meter accuracy. - -## Specification -This EIP proposes a new interface to ENS resolvers such that geo-spacial information -can be recorded and retrieved from the blockchain. -The interface changes are described below for "address resolvers" described in EIP137 -however the idea applies to any record described in EIP1185 and EIP1062, namely DNS -Resolvers, Text Resolvers, ABI Resolvers, etc. - -### What is a geohash? -A [Geohash](https://en.m.wikipedia.org/wiki/Geohash#Algorithm_and_example) -is an interleaving of latitude and longitude bits, whose -length determines it's precision. -Geohashes are typically encoded in base 32 characters. - -### function setGeoAddr(bytes32 node, string calldata geohash, address addr) external authorised(node) -Sets a resource (contract address, IP, ABI, TEXT, etc.) by node and geohash. -Geohashes must be unique per address and are exactly 8 characters long. -This leads to an accuracy of +-20 meters. -Write default initialized resource value, `address(0)`, to remove a resource from the resolver. - -### function geoAddr(bytes32 node, string calldata geohash) external view returns (address[] memory ret) -Query the resolver contract for a specific node and location. -All resources (contract addresses, IP addresses, ABIs, TEXT records, etc.) matching -the node and prefix geohash provided are returned. -This permits querying by exact geohash of 8 characters to return the content at that location, -or querying by geographic bounding box described by a geohash of less than 8 character precision. - -Any type of geohash can be used including [Z-order](https://en.wikipedia.org/wiki/Z-order_curve) -[Hilbert](https://en.wikipedia.org/wiki/Hilbert_curve) or the more accurate -[S2 Geometry](https://s2geometry.io/devguide/s2cell_hierarchy.html) library -from Google. -There are also ways to search the geographic data using geohashes without -always ending up with a rectangular query region. -[Searching circular shaped regions](https://github.com/ashwin711/proximityhash) is -slightly more complex as it requires multiple queries. - -## Rationale -The proposed implementation uses a sparse [Quadtree](https://dl.acm.org/doi/10.1007/BF00288933) trie as an index for -resource records as it has low storage overhead and good search performance. -The leaf nodes of the tree store resource records while non-leaves represent one geohash character. -Each node in the tree at depth d corresponds to a geohash of precision d. -The tree has depth 8 because the maximum precision of a geohash is 8 characters. -The tree has fanout 32 because the radix of a geohash character is 32. -The path to get to a leaf node always has depth 8 and the leaf contains the content (like IP address) -of the geohash represented by the path to the leaf. -The tree is sparse as 71% of the Earth's surface is covered by water. -The tree facilitates common traversal algorithms (DFS, BFS) to return -lists of resource records within a geographic bounding box. - -## Backwards Compatibility -This EIP does not introduce issues with backwards compatibility. - -## Test Cases -See https://github.com/james-choncholas/resolvers/blob/master/test/TestPublicResolver.js - -## Implementation -This address resolver, written in Solidity, implements the specifications outlined above. -The same idea presented here can be applied to other resolver interfaces as specified in EIP137. -Note that geohashes are passed and stored using 64 bit unsigned integers. -Using integers instead of strings for geohashes is more performant, especially in the `geomap` mapping. -For comparison purposes, see https://github.com/james-choncholas/geoens/tree/master/contracts/StringOwnedGeoENSResolver.sol for the inefficient string implementation. - - -```solidity -pragma solidity ^0.5.0; - -import "../ResolverBase.sol"; - -contract GeoENSResolver is ResolverBase { - bytes4 constant ERC2390 = 0x8fbcc5ce; - uint constant MAX_ADDR_RETURNS = 64; - uint constant TREE_VISITATION_QUEUESZ = 64; - uint8 constant ASCII_0 = 48; - uint8 constant ASCII_9 = 57; - uint8 constant ASCII_a = 97; - uint8 constant ASCII_b = 98; - uint8 constant ASCII_i = 105; - uint8 constant ASCII_l = 108; - uint8 constant ASCII_o = 111; - uint8 constant ASCII_z = 122; - - struct Node { - address data; // 0 if not leaf - uint256 parent; - uint256[] children; // always length 32 - } - - // A geohash is 8, base-32 characters. - // A geomap is stored as tree of fan-out 32 (because - // geohash is base 32) and height 8 (because geohash - // length is 8 characters) - mapping(bytes32=>Node[]) private geomap; - - event GeoENSRecordChanged(bytes32 indexed node, bytes8 geohash, address addr); - - // only 5 bits of ret value are used - function chartobase32(byte c) pure internal returns (uint8 b) { - uint8 ascii = uint8(c); - require( (ascii >= ASCII_0 && ascii <= ASCII_9) || - (ascii > ASCII_a && ascii <= ASCII_z)); - require(ascii != ASCII_a); - require(ascii != ASCII_i); - require(ascii != ASCII_l); - require(ascii != ASCII_o); - - if (ascii <= (ASCII_0 + 9)) { - b = ascii - ASCII_0; - - } else { - // base32 b = 10 - // ascii 'b' = 0x60 - // note base32 skips the letter 'a' - b = ascii - ASCII_b + 10; - - // base32 also skips the following letters - if (ascii > ASCII_i) - b --; - if (ascii > ASCII_l) - b --; - if (ascii > ASCII_o) - b --; - } - require(b < 32); // base 32 can't be larger than 32 - return b; - } - - function geoAddr(bytes32 node, bytes8 geohash, uint8 precision) external view returns (address[] memory ret) { - bytes32(node); // single node georesolver ignores node - assert(precision <= geohash.length); - - ret = new address[](MAX_ADDR_RETURNS); - if (geomap[node].length == 0) { return ret; } - uint ret_i = 0; - - // walk into the geomap data structure - uint pointer = 0; // not actual pointer but index into geomap - for(uint8 i=0; i < precision; i++) { - - uint8 c = chartobase32(geohash[i]); - uint next = geomap[node][pointer].children[c]; - if (next == 0) { - // nothing found for this geohash. - // return early. - return ret; - } else { - pointer = next; - } - } - - // pointer is now node representing the resolution of the query geohash. - // DFS until all addresses found or ret[] is full. - // Do not use recursion because blockchain... - uint[] memory indexes_to_visit = new uint[](TREE_VISITATION_QUEUESZ); - indexes_to_visit[0] = pointer; - uint front_i = 0; - uint back_i = 1; - - while(front_i != back_i) { - Node memory cur_node = geomap[node][indexes_to_visit[front_i]]; - front_i ++; - - // if not a leaf node... - if (cur_node.data == address(0)) { - // visit all the chilins - for(uint i=0; i MAX_ADDR_RETURNS) break; - } - } - - return ret; - } - - // when setting, geohash must be precise to 8 digits. - function setGeoAddr(bytes32 node, bytes8 geohash, address addr) external authorised(node) { - bytes32(node); // single node georesolver ignores node - - // create root node if not yet created - if (geomap[node].length == 0) { - geomap[node].push( Node({ - data: address(0), - parent: 0, - children: new uint256[](32) - })); - } - - // walk into the geomap data structure - uint pointer = 0; // not actual pointer but index into geomap - for(uint i=0; i < geohash.length; i++) { - - uint8 c = chartobase32(geohash[i]); - - if (geomap[node][pointer].children[c] == 0) { - // nothing found for this geohash. - // we need to create a path to the leaf - geomap[node].push( Node({ - data: address(0), - parent: pointer, - children: new uint256[](32) - })); - geomap[node][pointer].children[c] = geomap[node].length - 1; - } - pointer = geomap[node][pointer].children[c]; - } - - Node storage cur_node = geomap[node][pointer]; // storage = get reference - cur_node.data = addr; - - emit GeoENSRecordChanged(node, geohash, addr); - } - - function supportsInterface(bytes4 interfaceID) public pure returns (bool) { - return interfaceID == ERC2390 || super.supportsInterface(interfaceID); - } -} -``` - -## Security Considerations -This contract has similar functionality to ENS Resolvers - refer there for security considerations. -Additionally, this contract has a dimension of data privacy. -Users query via the geoAddr function specifying a geohash of less than 8 characters -which defines the query region. -Users who run light clients leak the query region to their connected full-nodes. -Users who rely on nodes run by third parties (like Infura) will also leak -the query region. -Users who run their own full node or have access to a trusted full node do -not leak any location data. - -Given the way most location services work, the query region is likely to contain -the user's actual location. -The difference between API access, light, and full nodes has always had -an impact on privacy but now the impact is underscored by the involvement -of coarse granularity user location. - - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2390.md diff --git a/EIPS/eip-2400.md b/EIPS/eip-2400.md index 1978fd56b03e0b..a6d286dd35b776 100644 --- a/EIPS/eip-2400.md +++ b/EIPS/eip-2400.md @@ -1,100 +1,7 @@ --- eip: 2400 -title: Transaction Receipt URI -description: URI format for submitted transactions with complete information for transaction decoding -author: Ricardo Guilherme Schmidt (@3esmit), Eric Dvorsak (@yenda) -discussions-to: https://ethereum-magicians.org/t/eip-2400-transaction-receipt-uri/ -status: Stagnant -type: Standards Track category: ERC -created: 2019-11-05 -requires: 155, 681 +status: Moved --- -## Abstract -A transaction hash is not very meaningful on its own, because it looks just like any other hash, and it might lack important information for reading a transaction. - -This standard includes all needed information for displaying a transaction and its details, such as `chainId`, `method` signature called, and `events` signatures emitted. - -## Motivation - -Interoperability between ethereum clients, allowing different systems to agree on a standard way of representing submitted transactions hashes, optionally with necessary information for decoding transaction details. - -### Use-cases - -Transaction Receipt URIs embedded in QR-codes, hyperlinks in web-pages, emails or chat messages provide for robust cross-application signaling between very loosely coupled applications. A standardized URI format allows for instant invocation of the user’s preferred transaction explorer application. Such as: - -- In web3 (dapps, mining pools, exchanges), links would automatically open user's preferred transaction explorer; -- In wallets, for users sharing transaction receipts easier; -- In chat applications, as a reply to an [EIP-681] transaction request; -- In crypto vending machines, a QRCode can be displayed when transactions are submitted; -- Anywhere transaction receipts are presented to users. - -## Specification - -### Syntax - -Transaction receipt URLs contain "ethereum" in their schema (protocol) part and are constructed as follows: - - receipt = schema_part transaction_hash [ "@" chain_id ] [ "?" parameters ] - schema_part = "ethereum:tx-" - transaction_hash = "0x" 64*HEXDIG - chain_id = 1*DIGIT - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = "method" / "events" - value = function_signature / event_list - function_signature = function_name "(" TYPE *( "," TYPE) ")" - function_name = STRING - event_list = event_signature *( ";" event_signature ) - event_signature = event_name "(" event_type *( "," event_type) ")" - event_name = STRING - event_type = ["!"] TYPE - - -Where `TYPE` is a standard ABI type name, as defined in Ethereum Contract ABI specification. `STRING` is a URL-encoded unicode string of arbitrary length. - -The exclamation symbol (`!`), in `event_type`, is used to identify indexed event parameters. - -### Semantics - -`transaction_hash` is mandatory. The hash must be looked up in the corresponding `chain_id` transaction history, if not found it should be looked into the pending transaction queue and rechecked until is found. If not found anequivalent error as "transaction not found error" should be shown instead of the transaction. When the transaction is pending, it should keep checking until the transaction is included in a block and becomes "unrevertable" (usually 12 blocks after transaction is included). - - -`chain_id` is specified by [EIP-155] optional and contains the decimal chain ID, such that transactions on various test and private networks can be represented as well. If no `chain_id` is present, the $ETH/mainnet (`1`) is considered. - -If `method` is not present, this means that the transaction receipt URI does not specify details, or that it was a transaction with no calldata. When present it needs to be validated by comparing the first 4 bytes of transaction calldata with the first 4 bytes of the keccak256 hash of `method`, if invalid, an equivalent error as "method validation error" must be shown instead of the transaction. - -If `events` is not present, this means that the transaction receipt URI does not specify details, or that the transaction did not raised any events. Pending and failed transactions don't validate events, however, when transaction is successful (or changes from pending to success) and events are present in URI, each event in the `event_list` must occur at least once in the transaction receipt event logs, otherwise an equivalent error as "event validation error: {event(s) [$event_signature, ...] not found}" should be shown instead of the transaction. A URI might contain the event signature for all, some or none of the raised events. - -#### Examples - -##### Simple ETH transfer: -`ethereum:tx-0x1143b5e38fe3cf585fb026fb9b5ce35c85a691786397dc8a23a07a62796d8172@1` - -##### Standard Token transfer: - -`ethereum:tx-0x5375e805b0c6afa20daab8d37352bf09a533efb03129ba56dee869e2ce4f2f92@1?method="transfer(address,uint256)"&events="Transfer(!address,!address,uint256)"` - -##### Complex contract transaction: - -`ethereum:tx-0x4465e7cce3c784f264301bfe26fc17609855305213ec74c716c7561154b76fec@1?method="issueAndActivateBounty(address,uint256,string,uint256,address,bool,address,uint256)"&events="Transfer(!address,!address,uint256);BountyIssued(uint256);ContributionAdded(uint256,!address,uint256);BountyActivated(uint256,address)"` - -## Rationale - -The goal of this standard envolves only the transport of submitted transactions, and therefore transaction data must be loaded from blockchain or pending transaction queue, which also serves as a validation of the transaction existence. - -Transaction hash not found is normal in fresh transactions, but can also mean that effectively a transaction was never submitted or have been replaced (through "higher gasPrice" nonce override or through an uncle/fork). - -In order to decode transaction parameters and events, a part of the ABI is required. The transaction signer have to know the ABI to sign a transaction, and is also who is creating a transaction receipt, so the transaction receipt can optionally be shared with the information needed to decode the transaction call data and it's events. - -## Backwards Compatibility - -Future upgrades that are partially or fully incompatible with this proposal must use a prefix other than `tx-` that is separated by a dash (-) character from whatever follows it. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - -[EIP-155]: ./eip-155.md -[EIP-681]: ./eip-681.md +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2400.md diff --git a/EIPS/eip-2470.md b/EIPS/eip-2470.md index 406c749f587cc7..65bf8a1aa85fc8 100644 --- a/EIPS/eip-2470.md +++ b/EIPS/eip-2470.md @@ -1,197 +1,7 @@ --- eip: 2470 -title: Singleton Factory -author: Ricardo Guilherme Schmidt (@3esmit) -discussions-to: https://ethereum-magicians.org/t/erc-2470-singleton-factory/3933 -status: Stagnant -type: Standards Track category: ERC -created: 2020-01-15 -requires: 1014 +status: Moved --- -## Simple Summary - -Some DApps needs one, and only one, instance of an contract, which have the same address on any chain. - -A permissionless factory for deploy of keyless deterministic contracts addresses based on its bytecode. - -## Abstract - -Some contracts are designed to be Singletons which have the same address no matter what chain they are, which means that should exist one instance for all, such as [EIP-1820] and [EIP-2429]. These contracts are usually deployed using a method known as [Nick]'s method, so anyone can deploy those contracts on any chain and they have a deterministic address. -This standard proposes the creation of a CREATE2 factory using this method, so other projects requiring this feature can use this factory in any chain with the same setup, even in development chains. - -## Motivation - -Code reuse, using the factory becomes easier to deploy singletons. - -## Specification - -### [ERC-2470] Singleton Factory - -> This is an exact copy of the code of the [ERC2470 factory smart contract]. - -```solidity -pragma solidity 0.6.2; - - -/** - * @title Singleton Factory (EIP-2470) - * @notice Exposes CREATE2 (EIP-1014) to deploy bytecode on deterministic addresses based on initialization code and salt. - * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) - */ -contract SingletonFactory { - /** - * @notice Deploys `_initCode` using `_salt` for defining the deterministic address. - * @param _initCode Initialization code. - * @param _salt Arbitrary value to modify resulting address. - * @return createdContract Created contract address. - */ - function deploy(bytes memory _initCode, bytes32 _salt) - public - returns (address payable createdContract) - { - assembly { - createdContract := create2(0, add(_initCode, 0x20), mload(_initCode), _salt) - } - } -} -// IV is a value changed to generate the vanity address. -// IV: 6583047 -``` - -### Deployment Transaction - -Below is the raw transaction which MUST be used to deploy the smart contract on any chain. - -``` -0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470 -``` - -The strings of `2470`'s at the end of the transaction are the `r` and `s` of the signature. -From this deterministic pattern (generated by a human), anyone can deduce that no one knows the private key for the deployment account. - -### Deployment Method - -This contract is going to be deployed using the keyless deployment method---also known as [Nick]'s method---which relies on a single-use address. -(See [Nick's article] for more details). This method works as follows: - -1. Generate a transaction which deploys the contract from a new random account. - - This transaction MUST NOT use [EIP-155] in order to work on any chain. - - This transaction MUST have a relatively high gas price to be deployed on any chain. In this case, it is going to be 100 Gwei. - -2. Forge a transaction with the following parameters: - ```js - { - nonce: 0, - gasPrice: 100000000000, - value: 0, - data: '0x608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c63430006020033', - gasLimit: 247000, - v: 27, - r: '0x247000', - s: '0x2470' - } - ``` - > The `r` and `s` values, made of starting `2470`, are obviously a human determined value, instead of a real signature. - -3. We recover the sender of this transaction, i.e., the single-use deployment account. - - > Thus we obtain an account that can broadcast that transaction, but we also have the warranty that nobody knows the private key of that account. - -4. Send exactly 0.0247 ether to this single-use deployment account. - -5. Broadcast the deployment transaction. - - > Note: 247000 is the double of gas needed to deploy the smart contract, this ensures that future changes in OPCODE pricing are unlikely to cause this deploy transaction to fail out of gas. A left over will sit in the address of about 0.01 ETH will be forever locked in the single use address. - -The resulting transaction hash is `0x803351deb6d745e91545a6a3e1c0ea3e9a6a02a1a4193b70edfcd2f40f71a01c`. - -This operation can be done on any chain, guaranteeing that the contract address is always the same and nobody can use that address with a different contract. - - -### Single-use Factory Deployment Account - -![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAB0UlEQVR4nO3asW1CQRBAQdpyCa6CIpxTjgujDGTJNEC2QqvjTbDx33c3P7vL79f1fzLf98dobn8/o5nuP53p/tPzm+5/AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4CMBnH6B0/23L2AbEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ8JYPsCtw+w3g9AvB+AeD8A8X4A4v0AxPsBiPcDEO8HIN4PQLwfgHg/APF+AOL9AMT7AYj3AxDvP/5ByOkApt/PvwgCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgJYDtA9w+gO0fYHsAAGB/CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAdALYfNExnun+9H4B4PwDxfgDi/QDE+wGI9wMQ7wcg3g9AvB+AeD8A8X4A4v0AxPsBiPcDEO8HIN4/fhCy/aDidADb5wcAAGcHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO8CsH2ApwPY/j4Ah+8PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPB6nlegoDNgrfyiAAAAAElFTkSuQmCC) - -`0xBb6e024b9cFFACB947A71991E386681B1Cd1477D` - -This account is generated by reverse engineering it from its signature for the transaction. -This way no one knows the private key, but it is known that it is the valid signer of the deployment transaction. - -> To deploy the registry, 0.0247 ether MUST be sent to this account *first*. - -### Factory Contract Address -![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAABn0lEQVR4nO3coRECMRRF0S2GutCUQzd4WqAMLB4qQGWYP+EecXXeZo/OcTrf35Ndbq+l7F/rmB6w+wXuvh+A+H4A4vsBiO8HIL4fgPh+AOL7AYjvByC+H4D4fgDi+wGI7wcgvh+A+H4A4vuXAUxfwPX5GG33+wMAgL0/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgGYHrA9A+cbhoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wlgesD0+bvvXz0fgM33AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB8ATB9gZoNgHgAxAMgHgDxAIgHQDwA4gEQD4B4AMQDIB4A8QCIB0A8AOId0w8caK3V/wfA5gEQD4B4AMQDIB4A8QCIB0A8AOIBEA+AeADEAyAeAPEAiAdAPADiARAPgHgAxAMgHgDxAIgHQDwA4gEQD4B4AMQDIB4A8QCItwxg+oECDT8QMT1AAAgAASAABIAAEAACQAAIAAEgAASAANAv+gDxVDRR1CVqRAAAAABJRU5ErkJggg==) - -`0xce0042B868300000d44A59004Da54A005ffdcf9f` - -The contract has the address above for every chain on which it is deployed. -### ABI for SingletonFactory: -```json -[ - { - "constant": false, - "inputs": [ - { - "internalType": "bytes", - "name": "_initCode", - "type": "bytes" - }, - { - "internalType": "bytes32", - "name": "_salt", - "type": "bytes32" - } - ], - "name": "deploy", - "outputs": [ - { - "internalType": "address payable", - "name": "createdContract", - "type": "address" - } - ], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - } -] -``` - -## Rationale - -SingletonFactory does not allow sending value on create2, this was done to prevent different results on the created object. -SingletonFactory allows user defined salt to facilitate the creation of vanity addresses for other projects. If vanity address is not necessary, salt `bytes(0)` should be used. -Contracts that are constructed by the SingletonFactory MUST not use `msg.sender` in their constructor, all variables must came through initialization data. This is intentional, as if allowing a callback after creation to aid initialization state would lead to contracts with same address (but different chains) to have the same address but different initial state. -The resulting address can be calculated in chain by any contract using this formula: `address(keccak256(bytes1(0xff), 0xce0042B868300000d44A59004Da54A005ffdcf9f, _salt, keccak256(_code)) << 96)` or in javascript using https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/README.md#const-generateaddress2. - -## Backwards Compatibility - -Does not apply as there are no past versions of Singleton Factory being used. - -## Test Cases - -TBD - -## Implementation - -https://github.com/3esmit/ERC2470 - -## Security Considerations - -Some contracts can possibly not support being deployed on any chain, or require a different address per chain, that can be safely done by using comparison in [EIP-1344] in constructor. -Account contracts are singletons in the point of view of each user, when wallets want to signal what chain id is intended, [EIP-1191] should be used. -Contracts deployed on factory must not use `msg.sender` in constructor, instead use constructor parameters, otherwise the factory would end up being the controller/only owner of those. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[EIP-155]: ./eip-155.md -[EIP-1191]: ./eip-1191.md -[EIP-1344]: ./eip-1344.md -[EIP-1820]: ./eip-1820.md -[EIP-2429]: https://gitlab.com/status-im/docs/EIPs/blob/secret-multisig-recovery/EIPS/eip-2429.md -[Nick's article]: https://medium.com/@weka/how-to-send-ether-to-11-440-people-187e332566b7 -[Nick]: https://github.com/Arachnid/ - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2470.md diff --git a/EIPS/eip-2477.md b/EIPS/eip-2477.md index 6a76dc903eb23b..e5a527b1ae2863 100644 --- a/EIPS/eip-2477.md +++ b/EIPS/eip-2477.md @@ -1,325 +1,7 @@ --- eip: 2477 -title: Token Metadata Integrity -author: Kristijan Sedlak (@xpepermint), William Entriken , Witek Radomski -discussions-to: https://github.com/ethereum/EIPs/issues/2483 -type: Standards Track category: ERC -status: Stagnant -created: 2020-01-02 -requires: 165, 721, 1155 +status: Moved --- -## Simple Summary - -This specification defines a mechanism by which clients may verify that a fetched token metadata document has been delivered without unexpected manipulation. - -This is the Web3 counterpart of the W3C Subresource Integrity (SRI) specification. - -## Abstract - -An interface `ERC2477` with two functions `tokenURIIntegrity` and `tokenURISchemaIntegrity` are specified for smart contracts and a narrative is provided to explain how this improves the integrity of the token metadata documents. - -## Motivation - -Tokens are being used in many applications to represent, trace and provide access to assets off-chain. These assets include in-game digital items in mobile apps, luxury watches and products in our global supply chain, among many other creative uses. - -Several token standards allow attaching metadata to specific tokens using a URI (RFC 3986) and these are supported by the applications mentioned above. These metadata standards are: - -* ERC-721 metadata extension (`ERC721Metadata`) -* ERC-1155 metadata extension (`ERC1155Metadata_URI`) -* ERC-1046 (DRAFT) ERC-20 Metadata Extension - -Although all these standards allow storing the metadata entirely on-chain (using the "data" URI, RFC 2397), or using a content-addressable system (e.g. IPFS's Content IDentifiers [sic]), nearly every implementation we have found is using Uniform Resource Locators (the exception is The Sandbox which uses IPFS URIs). These URLs provide no guarantees of content correctness or immutability. This standard adds such guarantees. - -## Design - -**Approach A:** A token contract may reference metadata by using its URL. This provides no integrity protection because the referenced metadata and/or schema could change at any time if the hosted content is mutable. This is the world before EIP-2477: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│─────▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -``` - -Note: according to the JSON Schema project, a metadata document referencing a schema using a URI in the `$schema` key is a known approach, but it is not standardized. - -**Approach B:** EIP-2477 provides mechanisms to establish integrity for these references. In one approach, there is integrity for the metadata document. Here, the on-chain data includes a hash of the metadata document. The metadata may or may not reference a schema. In this approach, changing the metadata document will require updating on-chain `tokenURIIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌ ─ ─ ─ ─ -│ TokenID │──────▶│Metadata│─ ─ ─▶ Schema │ -└───────────────────────┘ └────────┘ └ ─ ─ ─ ─ -┌───────────────────────┐ ▲ -│ tokenURIIntegrity │════════════╝ -└───────────────────────┘ -``` - -**Approach C:** In a stronger approach, the schema is referenced by the metadata using an extension to JSON Schema, providing integrity. In this approach, changing the metadata document or the schema will require updating on-chain `tokenURIIntegrity` and the metadata document, additionally changing the schema requires updating the on-chain `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│═════▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ -│ tokenURIIntegrity │════════════╝ -└───────────────────────┘ -``` - -**Approach D:** Equally strong, the metadata can make a normal reference (no integrity protection) to the schema and on-chain data also includes a hash of the schema document. In this approach, changing the metadata document will require updating on-chain `tokenURIIntegrity` and updating the schema document will require updating the `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│─────▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ ▲ -│ tokenURIIntegrity │════════════╝ ║ -└───────────────────────┘ ║ -┌───────────────────────┐ ║ -│tokenURISchemaIntegrity│════════════════════════════╝ -└───────────────────────┘ -``` - -**Approach E:** Lastly, the schema can be referenced with integrity from the metadata and also using on-chain data. In this approach, changing the metadata document or the schema will require updating on-chain `tokenURIIntegrity` and the metadata document, additionally changing the schema requires updating the on-chain `tokenURISchemaIntegrity`: - -``` -┌───────────────────────┐ ┌────────┐ ┌────────┐ -│ TokenID │──────▶│Metadata│═════▶│ Schema │ -└───────────────────────┘ └────────┘ └────────┘ -┌───────────────────────┐ ▲ ▲ -│ tokenURIIntegrity │════════════╝ ║ -└───────────────────────┘ ║ -┌───────────────────────┐ ║ -│tokenURISchemaIntegrity│════════════════════════════╝ -└───────────────────────┘ -``` - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Smart contracts - -**Smart contracts implementing the ERC-2477 standard MUST implement the `ERC2477` interface.** - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.7; - -/// @title ERC-2477 Token Metadata Integrity -/// @dev See https://eips.ethereum.org/EIPS/eip-2477 -/// @dev The ERC-165 identifier for this interface is 0x832a7e0e -interface ERC2477 /* is ERC165 */ { - /// @notice Get the cryptographic hash of the specified tokenID's metadata - /// @param tokenId Identifier for a specific token - /// @return digest Bytes returned from the hash algorithm, or "" if not available - /// @return hashAlgorithm The name of the cryptographic hash algorithm, or "" if not available - function tokenURIIntegrity(uint256 tokenId) external view returns(bytes memory digest, string memory hashAlgorithm); - - /// @notice Get the cryptographic hash for the specified tokenID's metadata schema - /// @param tokenId Identifier for a specific token - /// @return digest Bytes returned from the hash algorithm, or "" if not available - /// @return hashAlgorithm The name of the cryptographic hash algorithm, or "" if not available - function tokenURISchemaIntegrity(uint256 tokenId) external view returns(bytes memory digest, string memory hashAlgorithm); -} -``` - -The returned cryptographic hashes correspond to the token's metadata document and that metadata document's schema, respectively. - -For example, with ERC-721 `tokenURIIntegrity(21)` would correspond to `tokenURI(21)`. With ERC-1155, `tokenURIIntegrity(16)` would correspond to `uri(16)`. In both cases, `tokenURISchemaIntegrity(32)` would correspond to the schema of the document matched by `tokenURIIntegrity(32)`. - -**Smart contracts implementing the ERC-2477 standard MUST implement the ERC-165 standard, including the interface identifiers above.** - -Smart contracts implementing the ERC-2477 standard MAY use any hashing or content integrity scheme. - -Smart contracts implementing the ERC-2477 standard MAY use or omit a mechanism to notify when the integrity is updated (e.g. an Ethereum logging operation). - -Smart contracts implementing the ERC-2477 standard MAY use any mechanism to provide schemas for metadata documents and SHOULD use JSON-LD on the metadata document for this purpose (i.e. `"@schema":...`). - -### Metadata - -A metadata document MAY conform to this schema to provide referential integrity to its schema document. - -```json -{ - "title": "EIP-2477 JSON Object With Refererential Integrity to Schema", - "type": "object", - "properties": { - "$schema": { - "type": "string", - "format": "uri" - }, - "$schemaIntegrity": { - "type": "object", - "properties": { - "digest": { - "type": "string" - }, - "hashAlgorithm": { - "type": "string" - } - }, - "required": ["digest", "hashAlgorithm"] - } - }, - "required": ["$schema", "$schemaIntegrity"] -} -``` - -### Clients - -A client implementing the ERC-2477 standard MUST support at least the `sha256` hash algorithm and MAY support other algorithms. - -### Caveats - -* This EIP metadata lists ERC-721 and ERC-1155 as "required" for implementation, due to a technical limitation of EIP metadata. In actuality, this standard is usable with any token implementation that has a `tokenURI(uint id)` or similar function. - -## Rationale - -**Function and parameter naming** - -The W3C Subresource Integrity (SRI) specification uses the attribute "integrity" to perform integrity verification. This ERC-2477 standard provides a similar mechanism and reuses the integrity name so as to be familiar to people that have seen SRI before. - -**Function return tuple** - -The SRI integrity attribute encodes elements of the tuple $$(cryptographic\ hash\ function, digest, options)$$. This ERC-2477 standard returns a digest and hash function name and omits forward-compatibility options. - -Currently, the SRI specification does not make use of options. So we cannot know what format they might be when implemented. This is the motivation to exclude this parameter. - -The digest return value is first, this is an optimization because we expect on-chain implementations will be more likely to use this return value if they will only be using one of the two. - -**Function return types** - -The digest is a byte array and supports various hash lengths. This is consistent with SRI. Whereas SRI uses base64 encoding to target an HTML document, we use a byte array because Ethereum already allows this encoding. - -The hash function name is a string. Currently there is no universal taxonomy of hash function names. SRI recognizes the names `sha256`, `sha384` and `sha512` with case-insensitive matching. We are aware of two authorities which provide taxonomies and canonical names for hash functions: ETSI Object Identifiers and NIST Computer Security Objects Register. However, SRI's approach is easier to follow and we have adopted this here. - -**Function return type — hash length** - -Clients must support the SHA-256 algorithm and may optionally support others. This is a departure from the SRI specification where SHA-256, SHA-384 and SHA-512 are all required. The rationale for this less-secure requirement is because we expect some clients to be on-chain. Currently SHA-256 is simple and cheap to do on Ethereum whereas SHA-384 and SHA-512 are more expensive and cumbersome. - -The most popular hash function size below 256 bits in current use is SHA-1 at 160 bits. Multiple collisions (the "Shattered" PDF file, the 320 byte file, the chosen prefix) have been published and a recipe is given to generate infinitely more collisions. SHA-1 is broken. The United States National Institute of Standards and Technology (NIST) has first deprecated SHA-1 for certain use cases in November 2015 and has later further expanded this deprecation. - -The most popular hash function size above 256 bits in current use is SHA-384 as specified by NIST. - -The United States National Security Agency requires a hash length of 384 or more bits for the SHA-2 (CNSA Suite Factsheet) algorithm suite for use on TOP SECRET networks. (No unclassified documents are currently available to specify use cases at higher classification networks.) - -We suspect that SHA-256 and the 0xcert Asset Certification will be popular choices to secure token metadata for the foreseeable future. - -**In-band signaling** - -One possible way to achieve strong content integrity with the existing token standards would be to include, for example, a `?integrity=XXXXX` at the end of all URLs. This approach is not used by any existing implementations we know about. There are a few reasons we have not chosen this approach. The strongest reason is that the World Wide Web has the same problem and they chose to use the Sub-Resource Integrity approach, which is a separate data field than the URL. - -Other supplementary reasons are: - -* For on-chain consumers of data, it is easier to parse a direct hash field than to perform string operations. - -* Maybe there are some URIs which are not amenable to being modified in that way, therefore limiting the generalizability of that approach. - -This design justification also applies to `tokenURISchemaIntegrity`. The current JSON-LD specification allows a JSON document to link to a schema document. But it does not provide integrity. Rather than changing how JSON-LD works, or changing JSON Schemas, we have the `tokenURISchemaIntegrity` property to just provide the integrity. - -## Backwards Compatibility - -Both ERC-721 and ERC-1155 provide compatible token metadata specifications that use URIs and JSON schemas. The ERC-2477 standard is compatible with both, and all specifications are additive. Therefore, there are no backward compatibility regressions. - -ERC-1523 Standard for Insurance Policies as ERC-721 Non Fungible Tokens (DRAFT) proposes an extension to ERC-721 which also tightens the requirements on metadata. Because it is wholly an extension of ERC-721, ERC-1523 is automatically supported by ERC-2477 (since this standard already supports ERC-721). - -ERC-1046 (DRAFT) ERC-20 Metadata Extension proposes a comparate extension for ERC-20. Such a concept is outside the scope of this ERC-2477 standard. Should ERC-1046 (DRAFT) be finalized, we will welcome a new ERC which copies ERC-2477 and removes the `tokenId` parameter. - -Similarly, ERC-918 (DRAFT) Mineable Token Standard proposes an extension for ERC-20 and also includes metadata. The same comment applies here as ERC-1046. - -## Test Cases - -Following is a token metadata document which is simultaneously compatible with ERC-721, ERC-1155 and ERC-2477 standards. - -```json -{ - "$schema": "https://URL_TO_SCHEMA_DOCUMENT", - "name": "Asset Name", - "description": "Lorem ipsum...", - "image": "https://s3.amazonaws.com/your-bucket/images/{id}.png" -} -``` - -This above example shows how JSON-LD is employed to reference the schema document (`$schema`). - -Following is a corresponding schema document which is accessible using the URI `"https://URL_TO_SCHEMA_DOCUMENT"` above. - -```json -{ - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents" - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - } - } -} -``` - -Assume that the metadata and schema above apply to a token with identifier 1234. (In ERC-721 this would be a specific token, in ERC-1155 this would be a token type.) Then these two function calls MAY have the following output: - -* `function tokenURIIntegrity(1234)` - * `bytes digest `: `3fc58b72faff20684f1925fd379907e22e96b660` - * `string hashAlgorithm`: `sha256` -* `function tokenURISchemaIntegrity(1234)` - * `bytes digest `: `ddb61583d82e87502d5ee94e3f2237f864eeff72` - * `string hashAlgorithm`: `sha256` - -To avoid doubt: the previous paragraph specifies "MAY" have that output because other hash functions are also acceptable. - -## Implementation - -0xcert Framework supports ERC-2477. - -## Reference - -Normative standard references - -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt -2. ERC-165 Standard Interface Detection. ./eip-165.md -3. ERC-721 Non-Fungible Token Standard. ./eip-721.md -4. ERC-1155 Multi Token Standard. ./eip-1155.md -5. JSON-LD. https://www.w3.org/TR/json-ld/ -6. Secure Hash Standard (SHS). https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf - -Other standards - -1. ERC-1046 ERC-20 Metadata Extension (DRAFT). ./eip-1046.md -2. ERC-918 Mineable Token Standard (DRAFT). ./eip-918.md -3. ERC-1523 Standard for Insurance Policies as ERC-721 Non Fungible Tokens (DRAFT). ./eip-1523.md -4. W3C Subresource Integrity (SRI). https://www.w3.org/TR/SRI/ -5. The "data" URL scheme. https://tools.ietf.org/html/rfc2397 -6. Uniform Resource Identifier (URI): Generic Syntax. https://tools.ietf.org/html/rfc3986 -7. CID [Specification] (DRAFT). https://github.com/multiformats/cid - -Discussion - -1. JSON-LD discussion of referential integrity. https://lists.w3.org/Archives/Public/public-json-ld-wg/2020Feb/0003.html -2. JSON Schema use of `$schema` key for documents. https://github.com/json-schema-org/json-schema-spec/issues/647#issuecomment-417362877 - -Other - -1. [0xcert Framework supports ERC-2477]. https://github.com/0xcert/framework/pull/717 -2. [Shattered] The first collision for full SHA-1. https://shattered.io/static/shattered.pdf -3. [320 byte file] The second SHA Collision. https://privacylog.blogspot.com/2019/12/the-second-sha-collision.html -4. [Chosen prefix] https://sha-mbles.github.io -5. Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths. (Rev. 1. Superseded.) https://csrc.nist.gov/publications/detail/sp/800-131a/rev-1/archive/2015-11-06 -6. Commercial National Security Algorithm (CNSA) Suite Factsheet. https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/commercial-national-security-algorithm-suite-factsheet.cfm -7. ETSI Assigned ASN.1 Object Identifiers. https://portal.etsi.org/pnns/oidlist -8. Computer Security Objects Register. https://csrc.nist.gov/projects/computer-security-objects-register/algorithm-registration -9. The Sandbox implementation. https://github.com/pixowl/sandbox-smart-contracts/blob/7022ce38f81363b8b75a64e6457f6923d91960d6/src/Asset/ERC1155ERC721.sol - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2477.md diff --git a/EIPS/eip-2494.md b/EIPS/eip-2494.md index 0fa1a28e990a16..76f5e329227b25 100644 --- a/EIPS/eip-2494.md +++ b/EIPS/eip-2494.md @@ -1,382 +1,7 @@ --- eip: 2494 -title: Baby Jubjub Elliptic Curve -author: Barry WhiteHat (@barryWhiteHat), Marta Bellés (@bellesmarta), Jordi Baylina (@jbaylina) -discussions-to: https://ethereum-magicians.org/t/eip-2494-baby-jubjub-elliptic-curve/3968 -status: Stagnant -type: Standards Track category: ERC -created: 2020-01-29 +status: Moved --- -## Simple Summary - -This proposal defines Baby Jubjub, an elliptic curve designed to work inside zk-SNARK circuits in Ethereum. - -## Abstract - -Two of the main issues behind why blockchain technology is not broadly used by individuals and industry are scalability and privacy guarantees. With a set of cryptographic tools called zero-knowledge proofs (ZKP) it is possible to address both of these problems. More specifically, the most suitable protocols for blockchain are called zk-SNARKs (zero-knowledge Succinct Non-interactive ARguments of Knowledge), as they are non-interactive, have succinct proof size and sublinear verification time. These types of protocols allow proving generic computational statements that can be modelled with arithmetic circuits defined over a finite field (also called zk-SNARK circuits). - -To verify a zk-SNARK proof, it is necessary to use an elliptic curve. In Ethereum, the curve is alt_bn128 (also referred as BN254), which has primer order `r`. With this curve, it is possible to generate and validate proofs of any `F_r`-arithmetic circuit. This EIP describes *Baby Jubjub*, an elliptic curve defined over the finite field `F_r` which can be used inside any zk-SNARK circuit, allowing for the implementation of cryptographic primitives that make use of elliptic curves, such as the Pedersen Hash or the Edwards Digital Signature Algorithm (EdDSA). - -## Motivation - -A [zero knowledge proof](https://en.wikipedia.org/wiki/Zero-knowledge_proof) (ZKP) is a protocol that enables one party, the prover, to convince another, the verifier, that a statement is true without revealing any information beyond the veracity of the statement. [Non-Interactive ZKPs](https://people.csail.mit.edu/silvio/Selected%20Scientific%20Papers/Zero%20Knowledge/Noninteractive_Zero-Knowkedge.pdf) (NIZK) are a particular type of zero-knowledge proofs in which the prover can generate the proof without interaction with the verifier. NIZK protocols are very suitable for Ethereum applications, because they allow a smart contract to act as a verifier. This way, anyone can generate a proof and send it as part of a transaction to the smart contract, which can perform some action depending on whether the proof is valid or not. In this context, the most preferable NIZK are [zk-SNARK](https://eprint.iacr.org/2013/279.pdf) (Zero-knowledge Succinct Non Interactive ARgument of Knowledge), a set of non-interactive zero-knowledge protocols that have succinct proof size and sublinear verification time. The importance of these protocols is double: on the one hand, they help improve privacy guarantees, and on the other, they are a possible solution to scalability issues (e.g. see [zk-Rollup](https://github.com/barryWhiteHat/roll_up) project). - -Like most ZKPs, zk-SNARKs permit proving computational statements. For example, one can prove things like: the knowledge of a private key associated with a certain public key, the correct computation of a transaction, or the knowledge of the preimage of a particular hash. Importantly, one can do these things without leaking any information about the statements in question. In other words, without leaking any information about the private key, the transaction details, or the value of the preimage. More specifically, zk-SNARKs permit proving any computational statement that can be modelled with an `F_r`-arithmetic circuit, a circuit consisting of set of wires that carry values from the field `F_r` and connect them to addition and multiplication gates `mod r`. This type of circuits are often called zk-SNARK circuits. - -The implementation of most zk-SNARK protocols (e.g. [[Pinnochio]](https://eprint.iacr.org/2013/279.pdf) and [[Groth16]](https://eprint.iacr.org/2016/260.pdf)) make use of an elliptic curve for validating a proof. In Ethereum, the curve used is alt_bn128 (also referred as BN254), which has prime order `r`. While it is possible to generate and validate proofs of `F_r`-arithmetic circuits with BN254, it is not possible to use BN254 to implement elliptic-curve cryptography within these circuits. To implement functions that require the use of elliptic curves inside a zk-SNARK circuit -- such as the [Pedersen Hash](https://github.com/zcash/zips/blob/master/protocol/protocol.pdf) or the [Edwards Digital Signature Algorithm](https://tools.ietf.org/html/rfc8032) (EdDSA) -- a new curve with coordinates in `F_r` is needed. To this end, we propose in this EIP *Baby Jubjub*, an elliptic curve defined over `F_r` that can be used inside any `F_r`-arithmetic circuit. In the next sections we describe in detail the characteristics of the curve, how it was generated, and which security considerations were taken. - -``` - inputs zk-SNARK (alt_bn128) output - +--------------------------------------------+ - | +--------------------+ | - --->| | EdDSA (Baby Jubjub)| | - | +--------------------+ | - --->| |---> - | +-----------------------------+ | - --->| | Pedersen Hash (Baby Jubjub) | | - | +-----------------------------+ | - +--------------------------------------------+ -``` - -## Specification - -### Definitions -Let `F_r` be the prime finite field with `r` elements, where -``` -r = 21888242871839275222246405745257275088548364400416034343698204186575808495617 -``` - -Let `E` be the twisted Edwards elliptic curve defined over `F_r` described by equation -``` -ax^2 + y^2 = 1 + dx^2y^2 -``` -with parameters -``` -a = 168700 -d = 168696 -``` -We call **Baby Jubjub** the curve `E(F_r)`, that is, the subgroup of `F_r`-rational points of `E`. - -### Order - -Baby Jubjub has order - -``` -n = 21888242871839275222246405745257275088614511777268538073601725287587578984328 -``` - -which factors in -``` -n = h x l -``` -where -``` -h = 8 -l = 2736030358979909402780800718157159386076813972158567259200215660948447373041 -``` -The parameter `h` is called *cofactor* and `l` is a prime number of 251 bits. - -### Generator Point - -The point `G = (x,y)` with coordinates -``` -x = 995203441582195749578291179787384436505546430278305826713579947235728471134 -y = 5472060717959818805561601436314318772137091100104008585924551046643952123905 -``` -generates all `n` points of the curve. - -### Base Point - -The point `B = (x,y)` with coordinates - -``` -x = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -y = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -generates the subgroup of points `P` of Baby Jubjub satisfying `l * P = O`. That is, it generates the set of points of order `l` and origin `O`. - -### Arithmetic - -Let `P1 = (x1, y1)` and `P2 = (x2, y2)` be two arbitrary points of Baby Jubjub. Then `P1 + P2 = (x3, y3)` is calculated in the following way: -``` -x3 = (x1*y2 + y1*x2)/(1 + d*x1*x2*y1*y2) -y3 = (y1*y2 - a*x1*x2)/(1 - d*x1*x2*y1*y2) -``` -Note that both addition and doubling of points can be computed using a single formula. - -## Rationale - -The search for Baby Jubjub was motivated by the need for an elliptic curve that allows the implementation of elliptic-curve cryptography in `F_r`-arithmetic circuits. The curve choice was based on three main factors: type of curve, generation process and security criteria. This section describes how these factors were addressed. - -**Form of the Curve** - -Baby Jubjub is a **twisted Edwards** curve birationally equivalent to a **Montgomery** curve. The choice of this form of curve was based on the following facts: -1. The Edwards-curve Digital Signature Scheme is based on twisted Edwards curves. -2. Twisted Edwards curves have a single complete formula for addition of points, which makes the implementation of the group law inside circuits very efficient [[Crypto08/013, Section 6]](https://eprint.iacr.org/2008/013.pdf). -3. As a twisted Edwards curve is generally birationally equivalent to a Montgomery curve [[Crypto08/13,Theorem 3.2]](https://eprint.iacr.org/2008/013.pdf), the curve can be easily converted from one form to another. As addition and doubling of points in a Montgomery curve can be performed very efficiently, computations outside the circuit can be done faster using this form and sped up inside circuits by combining it with twisted Edwards form (see [here](http://hyperelliptic.org/EFD/g1p/index.html)) for more details). - -**Generation of the Curve** - -Baby Jubjub was conceived as a solution to the circuit implementation of cryptographic schemes that require elliptic curves. As with any cryptographic protocol, it is important to reduce the possibility of a backdoor being present. As a result, we designed the generation process to be **transparent** and **deterministic** -- in order to make it clear that no external considerations were taken into account, and to ensure that the process can be reproduced and followed by anyone who wishes to do so. - -The algorithm chosen for generating Baby Jubjub is based in the criteria defined in [[RFC7748, Appendix A.1]](https://tools.ietf.org/html/rfc7748) and can be found in [this github repository](https://github.com/barryWhiteHat/baby_jubjub). Essentially, the algorithm takes a prime number `p = 1 mod 4` and returns the lowest `A>0` such that `A-2` is a multiple of 4 and such that the set of solutions in `F_p` of `y^2 = x^3 + Ax^2 + x` defines a Montgomery curve with cofactor 8. - -Baby Jubjub was generated by running the algorithm with the prime - -`r = 21888242871839275222246405745257275088548364400416034343698204186575808495617`, - -which is the order of alt_bn128, the curve used to verify zk-SNARK proofs in Ethereum. The output of the algorithm was `A=168698`. Afterwards, the corresponding Montgomery curve was transformed into twisted Edwards form. Using SAGE libraries for curves, the order `n` of the curve and its factorization `n = 8*l` was calculated. - -- **Choice of generator** : the generator point `G` is the point of order `n` with smallest positive `x`-coordinate in `F_r`. -- **Choice of base point**: the base point `B` is chosen to be `B = 8*G`, which has order `l`. - -**Security Criteria** - -It is crucial that Baby Jubjub be safe against well-known attacks. To that end, we decided that the curve should pass [SafeCurves](https://safecurves.cr.yp.to/) security tests, as they are known for gathering the best known attacks against elliptic curves. Supporting evidence that Baby Jubjub satisfies the SafeCurves criteria can be found [here](https://github.com/barryWhiteHat/baby_jubjub). - - -## Backwards Compatibility - -Baby Jubjub is a twisted Edwards elliptic curve birational to different curves. So far, the curve has mainly been used in its original form, in Montomgery form, and in another (different representation) twisted Edwards form -- which we call the reduced twisted Edwards form. - -Below are the three representations and the birational maps that make it possible to map points from one form of the curve to another. In all cases, the generator and base points are written in the form **`(x,y)`.** - -### Forms of the Curve - -All generators and base points are written in the form (x,y). - -**Twisted Edwards Form** (standard) - -- Equation: ``ax^2 + y^2 = 1 + dx^2y^2`` -- Parameters: ``a = 168700, d = 168696`` -- Generator point: - ``` - (995203441582195749578291179787384436505546430278305826713579947235728471134, 5472060717959818805561601436314318772137091100104008585924551046643952123905) - ``` -- Base point: - ``` - (5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203) - ``` - -**Montgomery Form** - -- Equation: ``By^2 = x^3 + A x^2 + x`` -- Parameters: ``A = 168698, B = 1`` -- Generator point: - ``` - (7, 4258727773875940690362607550498304598101071202821725296872974770776423442226) - ``` -- Base point: - ``` - (7117928050407583618111176421555214756675765419608405867398403713213306743542, 14577268218881899420966779687690205425227431577728659819975198491127179315626) - ``` - -**Reduced Twisted Edwards Form** - -- Equation: ``a' x^2 + y^2 = 1 + d' x^2y^2`` -- Parameters: - ``` - a' = -1 - d' = 12181644023421730124874158521699555681764249180949974110617291017600649128846 - ``` -- Generator point: - ``` - (4986949742063700372957640167352107234059678269330781000560194578601267663727, 5472060717959818805561601436314318772137091100104008585924551046643952123905) - ``` -- Base point: - ``` - (9671717474070082183213120605117400219616337014328744928644933853176787189663, 16950150798460657717958625567821834550301663161624707787222815936182638968203) - ``` - -### Conversion of Points - -Following formulas allow to convert points from one form of the curve to another. We will denote the coordinates - -* ``(u, v)`` for points in the Montomgery form, -* ``(x, y)`` for points in the Twisted Edwards form and -* ``(x', y')`` for points in reduced Twisted Edwards form. - -Note that in the last conversion -- from Twisted Edwards to Reduced Twisted Edwards and back -- we also use the scaling factor `f`, where: -``` -f = 6360561867910373094066688120553762416144456282423235903351243436111059670888 -``` -In the expressions one can also use directly `-f`, where: -``` --f = 15527681003928902128179717624703512672403908117992798440346960750464748824729 -``` - -**Montgomery --> Twisted Edwards** -``` -(u, v) --> (x, y) - -x = u/v -y = (u-1)/(u+1) -``` - -**Twisted Edwards --> Montgomery** -``` -(x, y) --> (u, v) - -u = (1+y)/(1-y) -v = (1+y)/((1-y)x) -``` - -**Montgomery --> Reduced Twisted Edwards** -``` -(u, v) --> (x', y') - -x' = u*(-f)/v -y' = (u-1)/(u+1) -``` - -**Reduced Twisted Edwards --> Montgomery** -``` -(x', y') --> (u, v) - -u = (1+y')/(1-y') -v = (-f)*(1+y')/((1-y')*x') -``` - -**Twisted Edwards --> Reduced Twisted Edwards** -``` -(x, y) --> (x', y') - -x' = x*(-f) -y' = y -``` - -**Reduced Twisted Edwards --> Twisted Edwards** -``` -(x', y') --> (x, y) - -x = x'/(-f) -y = y' -``` -## Security Considerations - -This section specifies the safety checks done on Baby Jubjub. The choices of security parameters are based on [SafeCurves criteria](https://safecurves.cr.yp.to), and supporting evidence that Baby Jubjub satisfies the following requisites can be found [here](https://github.com/barryWhiteHat/baby_jubjub). - -**Curve Parameters** - -Check that all parameters in the specification of the curve describe a well-defined elliptic curve over a prime finite field. - -- The number `r` is prime. -- Parameters `a` and `d` define an equation that corresponds to an elliptic curve. -- The product of `h` and `l` results into the order of the curve and the `G` point is a generator. -- The number `l` is prime and the `B` point has order `l`. - -**Elliptic Curve Discrete Logarithm Problem** - -Check that the discrete logarithm problem remains difficult in the given curve. We checked Baby Jubjub is resistant to the following known attacks. - -- *Rho method* [[Blake-Seroussi-Smart, Section V.1]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the cost for the rho method, which takes on average around `0.886*sqrt(l)` additions, to be above `2^100`. -- *Additive and multiplicative transfers* [[Blake-Seroussi-Smart, Section V.2]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the embedding degree to be at least `(l − 1)/100`. -- *High discriminant* [[Blake-Seroussi-Smart, Section IX.3]](https://www.cambridge.org/core/books/elliptic-curves-in-cryptography/16A2B60636EFA7EBCC3D5A5D01F28546): we require the complex-multiplication field discriminant `D` to be larger than `2^100`. - -**Elliptic Curve Cryptography** - -- *Ladders* [[Montgomery]](https://wstein.org/edu/Fall2001/124/misc/montgomery.pdf): check the curve supports the Montgomery ladder. -- *Twists* [[SafeCurves, twist]](https://safecurves.cr.yp.to/twist.html): check it is secure against the small-subgroup attack, invalid-curve attacks and twisted-attacks. -- *Completeness* [[SafeCurves, complete]](https://safecurves.cr.yp.to/complete.html): check if the curve has complete single-scalar and multiple-scalar formulas. -- *Indistinguishability* [[IACR2013/325]](https://eprint.iacr.org/2013/325): check availability of maps that turn elliptic-curve points indistinguishable from uniform random strings. - -## Test Cases - -**Test 1 (Addition)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 17777552123799933955779906779655732241715742912184938656739573121738514868268 -y1 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 - -x2 = 16540640123574156134436876038791482806971768689494387082833631921987005038935 -y2 = 20819045374670962167435360035096875258406992893633759881276124905556507972311 -``` -Then their sum `` P1+P2 = (x3, y3)`` is equal to: -``` -x3 = 7916061937171219682591368294088513039687205273691143098332585753343424131937 -y3 = 14035240266687799601661095864649209771790948434046947201833777492504781204499 -``` - -**Test 2 (Doubling)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 17777552123799933955779906779655732241715742912184938656739573121738514868268, -y1 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 - -x2 = 17777552123799933955779906779655732241715742912184938656739573121738514868268 -y2 = 2626589144620713026669568689430873010625803728049924121243784502389097019475 -``` -Then their sum `` P1+P2 = (x3, y3)`` is equal to: -``` -x3 = 6890855772600357754907169075114257697580319025794532037257385534741338397365 -y3 = 4338620300185947561074059802482547481416142213883829469920100239455078257889 -``` - -**Test 3 (Doubling the identity)** - -Consider the points ``P1 = (x1, y1)`` and ``P2 = (x2, y2)`` with the following coordinates: -``` -x1 = 0 -y1 = 1 - -x2 = 0 -y2 = 1 -``` -Then their sum `` P1+P2 = (x3, y3)`` results in the same point: -``` -x3 = 0 -y3 = 1 -``` - -**Test 4 (Curve membership)** - -Point ``(0,1)`` is a point on Baby Jubjub. - -Point ``(1,0)`` is not a point on Baby Jubjub. - -**Test 5 (Base point choice)** - -Check that the base point `` B = (Bx, By)`` with coordinates - -``` -Bx = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -By = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -is 8 times the generator point ``G = (Gx, Gy)``, where -``` -Gx = 995203441582195749578291179787384436505546430278305826713579947235728471134 -Gy = 5472060717959818805561601436314318772137091100104008585924551046643952123905 -``` -That is, check that ``B = 8 x G``. - -**Test 6 (Base point order)** - -Check that the base point `` B = (Bx, By)`` with coordinates - -``` -Bx = 5299619240641551281634865583518297030282874472190772894086521144482721001553 -By = 16950150798460657717958625567821834550301663161624707787222815936182638968203 -``` -multiplied by `l`, where -``` -l = 2736030358979909402780800718157159386076813972158567259200215660948447373041 -``` -results in the origin point `O = (0, 1)`. This test checks that the base point `B` has order `l`. - -## Implementation - -Arithmetic of Baby Jubjub and some cryptographic primitives using the curve have already been implemented in different languages. Here are a few such implementations: - -- Python: https://github.com/barryWhiteHat/baby_jubjub_ecc -- JavaScript: https://github.com/iden3/circomlib/blob/master/src/babyjub.js -- Circuit (circom): https://github.com/iden3/circomlib/blob/master/circuits/babyjub.circom -- Rust: https://github.com/arnaucube/babyjubjub-rs -- Solidity: https://github.com/yondonfu/sol-baby-jubjub -- Go: https://github.com/iden3/go-iden3-crypto/tree/master/babyjub - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2494.md diff --git a/EIPS/eip-2515.md b/EIPS/eip-2515.md index 7f60b3fa45808c..7cdd80d6d6778c 100644 --- a/EIPS/eip-2515.md +++ b/EIPS/eip-2515.md @@ -43,7 +43,7 @@ Add the variable `DIFFICULTY_FREEZE_DIFFERENCE` and use the `LAST_FORK_HEIGHT` t For example we can set the `DFD = 1,800,000 blocks` or approximately 9 months. The Difficulty Calculation would then be. ``` -if (BLOCK_HEIGHT <= LAST_FORK_HEIGHT + DIFFICUTLY_FREEZE_DIFFERENCE) : +if (BLOCK_HEIGHT <= LAST_FORK_HEIGHT + DIFFICULTY_FREEZE_DIFFERENCE) : block_diff = parent_diff + parent_diff // 2048 * max( 1 - (block_timestamp - parent_timestamp) // 10, -99) diff --git a/EIPS/eip-2520.md b/EIPS/eip-2520.md index d72c1e920bf93e..0ded919d219502 100644 --- a/EIPS/eip-2520.md +++ b/EIPS/eip-2520.md @@ -1,75 +1,7 @@ --- eip: 2520 -title: Multiple contenthash records for ENS -author: Filip Štamcar (@filips123) -discussions-to: https://github.com/ethereum/EIPs/issues/2393 -status: Stagnant -type: Standards Track category: ERC -created: 2020-02-18 -requires: 1577 +status: Moved --- -## Simple Summary -ENS support for multiple `contenthash` records on a single ENS name. - -## Motivation -Many applications are resolving ENS names to content hosted on distributed systems. To do this, they use `contenthash` record from ENS domain to know how to resolve names and which distributed system should be used. - -However, the domain can store only one `contenthash` record which means that the site owner needs to decide which hosting system to use. Because there are many ENS-compatible hosting systems available (IPFS, Swarm, recently Onion and ZeroNet), and there will probably be even more in the future, lack of support for multiple records could become problematic. Instead, domains should be able to store multiple `contenthash` records to allow applications to resolve to multiple hosting systems. - -## Specification -Setting and getting functions **MUST** have the same public interface as specified in EIP 1577. Additionally, they **MUST** also have new public interfaces introduced by this EIP: - -* For setting a `contenthash` record, the `setContenthash` **MUST** provide additional `proto` parameter and use it to save the `contenthash`. When `proto` is not provided, it **MUST** save the record as default record. - - ```solidity - function setContenthash(bytes32 node, bytes calldata proto, bytes calldata hash) external authorised(node); - ``` - -* For getting a `contenthash` record, the `contenthash` **MUST** provide additional `proto` parameter and use it to get the `contenthash` for requested type. When `proto` is not provided, it **MUST** return the default record. - - ```solidity - function contenthash(bytes32 node, bytes calldata proto) external view returns (bytes memory); - ``` - -* Resolver that supports multiple `contenthash` records **MUST** return `true` for `supportsInterface` with interface ID `0x6de03e07`. - -Applications that are using ENS `contenthash` records **SHOULD** handle them in the following way: - -* If the application only supports one hosting system (like directly handling ENS from IPFS/Swarm gateways), it **SHOULD** request `contenthash` with a specific type. The contract **MUST** then return it and application **SHOULD** correctly handle it. - -* If the application supports multiple hosting systems (like MetaMask), it **SHOULD** request `contenthash` without a specific type (like in EIP 1577). The contract **MUST** then return the default `contenthash` record. - -## Rationale -The proposed implementation was chosen because it is simple to implement and supports all important requested features. However, it doesn't support multiple records for the same type and priority order, as they don't give much advantage and are harder to implement properly. - -## Backwards Compatibility -The EIP is backwards-compatible with EIP 1577, the only differences are additional overloaded methods. Old applications will still be able to function correctly, as they will receive the default `contenthash` record. - -## Implementation -```solidity -contract ContentHashResolver { - bytes4 constant private MULTI_CONTENT_HASH_INTERFACE_ID = 0x6de03e07; - mapping(bytes32=>mapping(bytes=>bytes)) hashes; - - function setContenthash(bytes32 node, bytes calldata proto, bytes calldata hash) external { - hashes[node][proto] = hash; - emit ContenthashChanged(node, hash); - } - - function contenthash(bytes32 node, bytes calldata proto) external view returns (bytes memory) { - return hashes[node][proto]; - } - - function supportsInterface(bytes4 interfaceID) public pure returns(bool) { - return interfaceID == MULTI_CONTENT_HASH_INTERFACE_ID; - } -} -``` - -## Security Considerations -TBD - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2520.md diff --git a/EIPS/eip-2525.md b/EIPS/eip-2525.md index 71a285511154ec..ae319b3ee99cb9 100644 --- a/EIPS/eip-2525.md +++ b/EIPS/eip-2525.md @@ -1,171 +1,7 @@ --- eip: 2525 -title: ENSLogin -author: Hadrien Croubois (@amxx) -discussions-to: https://ethereum-magicians.org/t/discussion-ens-login/3569 -status: Stagnant -type: Standards Track category: ERC -created: 2020-02-19 -requires: 137, 634, 1193, 2304 +status: Moved --- -## 1. Abstract - -This presents a method to improve a universal method of login to the ethereum blockchain, leveraging the metadata storage provided by the ENS. We consider a user to be logged in when we have an [EIP-1193](./eip-1193.md) provider that can sign transaction and messages on his behalf. This method is inspired by [Alex Van de Sande's work](https://www.youtube.com/watch?v=1LVwWknE-NQ) and [Web3Connect](https://web3connect.com). In the future, the approach described here-after should be extended to work with any blockchain. - -## 2. Motivation - -Multiple wallet solutions can be used to interact with the Ethereum blockchain. Some (metamask, gnosis, ...) are compatible as they inject a standardized wallet object in the browser without requiring any effort from the Dapp developers, but they require an effort on the user side (user has to install the plugin). Other solutions (Portis, Authereum, Torus, Universal Login, ...) propose a more seamless flow to non-crypto-aware users but require an integration effort from the Dapp developers. Hardware wallet (ledger, trezor, keepkey, ...) also require integration effort from the Dapp developers. - -When Dapps integrate login with multiple solutions, they rely on the user choosing the correct wallet-provider. This could prove increasingly difficult as the number of wallet-provider increases, particularly for novice users. Additionally, if decentralized applications pick and choose only a handful of wallets to support, the current incumbent wallets will have a distinct advantage and new wallets will struggle to find adoption. This will create a less competitive environment and stifle innovation. Rather than relying on the user choosing which wallet-provider to connect with (as does Web3Connect), ENSLogin proposes to use user-owned ENS domain as entry points. Metadata attached to these ENS domains is used to detect which wallet-provider if used by the corresponding account. - -That way, ENSLogin would allow any user to connect to any Dapp with any wallet, using a simple domain as a login. - -## 3. Description - -### 3.1. Overview - -The ENSLogin works as follow: - -* Request an ENS domain from the user -* Resolve the ENS domain to retrieve (see [EIP-137](./eip-137.md)) - * An address (see [EIP-137](./eip-137.md)) - * A text entry (see [EIP-634](./eip-634.md)) -* Interpret the text entry and download the file it points to -* Evaluate the content of the downloaded file -* Return the corresponding object to the Dapp - -At this point, the app should process like with any web3 provider. Calling the `enable()` functions should ask the users for wallet specific credentials is needed. - -This workflow is to be implemented by an SDK that Dapp could easily import. The SDK would contain the resolution mechanism and support for both centralized and decentralized storage solution. Wallet-provider specific code should NOT be part of SDK. Wallet-provider specific code should only be present in the external file used to generate the web3 provider. - -### 3.2. Details - -* **Text entry resolution:** A pointer to the code needed to instantiate the wallet-provider is recorded using the ENS support for text entries (see [EIP-634](./eip-634.md)). The corresponding key is `enslogin` (**subject to change**). If no value is associated with the key `enslogin` at the targeted domain, we fallback to metadata store on the parent's node with the key `enslogin-default` (**subject to change**). -**Example:** for the ens domain `username.domain.eth`, the resolution would look for (in order): - * `resolver.at(ens.owner(nodehash("username.domain.eth"))).text(nodehash("username.domain.eth"), 'enslogin')` - * `resolver.at(ens.owner(nodehash("domain.eth"))).text(nodehash("domain.eth"), 'enslogin-default')` - -* **Provider link:** Code for instantiating the wallet-provider must be pointed to in a standardized manner. **This is yet not specified.** The current approach uses a human-readable format `scheme://path` such as: - - * `ipfs://Qm12345678901234567890123456789012345678901234` - * `https://server.com/enslogin-module-someprovider` - - And adds a suffix depending on the targeted blockchain type (see [SLIP 44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md)) and language. Canonical case is a webapp using ethereum so the target would be: - - * `ipfs://Qm12345678901234567890123456789012345678901234/60/js` - * `https://server.com/enslogin-module-someprovider/60/js` - - Note that this suffix mechanism is compatible with http/https as well as IPFS. It is a constraint on the storage layer as some may not be able to do this kind of resolution. - -* **Provider instantiation:** - * [JAVASCRIPT/ETHEREUM] The file containing the wallet-provider's code should inject a function `global.provider: (config) => Promise` that returns a promise to a standardized provider object. For EVM blockchains, the object should follow [EIP-1193](./eip-1193.md). - * Other blockchain types/langages should be detailed in the future. - - -* **Configuration object:** In addition to the username (ENS domain), the Dapp should have the ability to pass a configuration object that could be used by the wallet-provider instantiating function. This configuration should include: - * A body (common to all provider) that specify details about the targeted chain (network name / node, address of the ens entrypoint ...). If any of these are missing, a fallback can be used (mainnet as a default network, bootstrapping an in-browser IPFS node, ...). - * Wallet provider-specific fields (**optional**, starting with one underscore `_`) can be added to pass additional, wallet-provider specific, parameters / debugging flags. - * SDK specific fields (**optional**, starting with two underscores `__`) can be used to pass additional arguments. - - Minimal configuration: - ``` - { - provider: { - network: 'goerli' - } - } - ``` - Example of advanced configuration object: - ``` - { - provider: { - network: 'goerli', - ens: '0x112234455c3a32fd11230c42e7bccd4a84e02010' - }, - ipfs: { - host: 'ipfs.infura.io', - port: 5001, - protocol: 'https' - }, - _authereum: {...}, - _portis: {...}, - _unilogin: {...}, - _torus: {...}, - __callbacks: { - resolved: (username, addr, descr) => { - console.log(`[CALLBACKS] resolved: ${username} ${addr} ${descr}`); - }, - loading: (protocol, path) => { - console.log(`[CALLBACKS] loading: ${protocol} ${path}`); - }, - loaded: (protocol, path) => { - console.log(`[CALLBACKS] loaded: ${protocol} ${path}`); - } - } - } - ``` - -**TODO** *(maybe move that part to section 6.1)*: -Add [SLIP 44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) compliant blockchain description to the config for better multichain support. This will require a additional field `ENS network` to know which ethereum network to use for resolution when the targeted blockchain/network is not ethereum (could also be used for cross chain resolution on ethereum, for example xDAI login with metadata stored on mainnet) - -### 3.3. Decentralization - -Unlike solution like Web3Connect, ENSLogin proposes a modular approach that is decentralized by nature. -The code needed for a Dapp to use ENSLogin (hereafter referred to as the SDK) only contains lookup mechanism for the ethereum blockchain and the data storages solutions. The solution is limited by the protocols (https / ipfs / ...) that the SDK can interact with. Beyond that, any wallet-provider that follows the expected structure and that is available through one of the supported protocol is automatically compatible with all the Dapps proposing ENSLogin support. There is no need to go through a centralized approval process. Furthermore, deployed SDK do not need to be upgraded to benefit from the latest wallet updates. The only permissioned part of the protocol is in the ENS control of the users over the metadata that describes their wallet-provider implementation. Users could also rely on the fallback mechanism to have the wallet-provider update it for them. - -### 3.4. Incentives - -We believe ENSLogin's biggest strength is the fact that it aligns the incentives of Dapp developers and wallet-providers to follow this standard. - -* A wallet-provider that implements the required file and make them available will ensure the compatibility of its wallet with all Dapps using ENSLogin. This will remove the burden of asking all Dapps to integrate their solutions, which Dapps are unlikely to do until the wallet as strong userbase. Consequently, ENSLogin will improve the competition between wallet-providers and encourage innovation in that space -* A Dapp that uses ENSLogin protocol, either by including the ENSLogin's SDK or by implementing compatible behaviour, will make itself available to all the users of all the compatible wallet. At some point, being compatible with ENSLogin will be the easiest to reach a large user-base. -* ENSLogin should be mostly transparent for the users. Most wallet provider will set up the necessary entries without requiring any effort from the user. Advanced users can take control over the wallet resolution process, which will be simple once the right tooling is available. - -### 3.5. Drawbacks - -While ENSLogin allows dapps to support any wallet for logging in, dapps still must choose which wallets they suggest to users for registration. This can be done through a component like Web3Connect or BlockNative's - -## 4. Prototype - -**TODO** - -## 5. Support by the community - -### 5.1. Adoption - -| Name | Live | Module | Assigns ENS names | support by default | -| -------------- | ---- | ------ | ----------------- | ------------------ | -| Argent | yes | no | yes | no | -| Authereum | yes | yes | yes | no | -| Fortmatic | yes | no | no | no | -| Gnosis Safe | yes | yes\* | no | no | -| Ledger | yes | beta | no | no | -| KeepKey | yes | no | no | no | -| Metamask | yes | yes | no | no | -| Opera | yes | yes\* | no | no | -| Portis | yes | yes | no | no | -| SquareLink | yes | no | no | no | -| Shipl | no | no | no | no | -| Torus | yes | yes | no | no | -| Trezor | yes | no | no | no | -| UniLogin | beta | beta | yes | no | - -\*use the metamask module - -## 6. Possible evolutions - -### 6.1. Multichain support - -**TODO** - -## 7. FAQ - -### 7.1. Can anyone connect with my login? Where are my private keys stored? - -ENSLogin only has access to what is recorded on the ENS, namely your address and the provider you use. Private key management is a is handled by the provider and is outside ENSLogin's scope. Some might store the key on disk. Other might rely on custodial keys stored on a remote (hopefully secure) server. Others might use a dedicated hardware component to handle signature and never directly have access to the private key. - -### 7.2. How do I get an ENS Login? - -**TODO** (this might need a separate ERC) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2525.md diff --git a/EIPS/eip-2535.md b/EIPS/eip-2535.md index 6cf1d83a1428a2..1c2fb213efceb3 100644 --- a/EIPS/eip-2535.md +++ b/EIPS/eip-2535.md @@ -1,435 +1,7 @@ --- eip: 2535 -title: Diamonds, Multi-Facet Proxy -description: Create modular smart contract systems that can be extended after deployment. -author: Nick Mudge (@mudgen) -discussions-to: https://ethereum-magicians.org/t/discussion-for-eip2535-diamonds/10459/ -status: Final -type: Standards Track category: ERC -created: 2020-02-22 +status: Moved --- -## Abstract - - - -This proposal standardizes diamonds, which are modular smart contract systems that can be upgraded/extended after deployment, and have virtually no size limit. More technically, a **diamond** is a contract with external functions that are supplied by contracts called **facets**. Facets are separate, independent contracts that can share internal functions, libraries, and state variables. - -## Motivation - -There are a number of different reasons to use diamonds. Here are some of them: - -1. **A single address for unlimited contract functionality.** Using a single address for contract functionality makes deployment, testing and integration with other smart contracts, software and user interfaces easier. -1. **Your contract exceeds the 24KB maximum contract size.** You may have related functionality that it makes sense to keep in a single contract, or at a single contract address. A diamond does not have a max contract size. -1. **A diamond provides a way to organize contract code and data.** You may want to build a contract system with a lot of functionality. A diamond provides a systematic way to isolate different functionality and connect them together and share data between them as needed in a gas-efficient way. -1. **A diamond provides a way to upgrade functionality.** Upgradeable diamonds can be upgraded to add/replace/remove functionality. Because diamonds have no max contract size, there is no limit to the amount of functionality that can be added to diamonds over time. Diamonds can be upgraded without having to redeploy existing functionality. Parts of a diamond can be added/replaced/removed while leaving other parts alone. -1. **A diamond can be immutable.** It is possible to deploy an immutable diamond or make an upgradeable diamond immutable at a later time. -1. **A diamond can reuse deployed contracts.** Instead of deploying contracts to a blockchain, existing already deployed, onchain contracts can be used to create diamonds. Custom diamonds can be created from existing deployed contracts. This enables the creation of on-chain smart contract platforms and libraries. - -This standard is an improvement of [EIP-1538](./eip-1538.md). The same motivations of that standard apply to this standard. - -A deployed facet can be used by any number of diamonds. - -The diagram below shows two diamonds using the same two facets. - -- `FacetA` is used by `Diamond1` -- `FacetA` is used by `Diamond2` -- `FacetB` is used by `Diamond1` -- `FacetB` is used by `Diamond2` - - - -### Upgradeable Diamond vs. Centralized Private Database - -Why have an upgradeable diamond instead of a centralized, private, mutable database? - -1. Decentralized Autonomous Organizations (DAOs) and other governance systems can be used to upgrade diamonds. -1. Wide interaction and integration with the Ethereum ecosystem. -1. With open storage data and verified source code it is possible to show a provable history of trustworthiness. -1. With openness bad behavior can be spotted and reported when it happens. -1. Independent security and domain experts can review the change history of contracts and vouch for their history of trustworthiness. -1. It is possible for an upgradeable diamond to become immutable and trustless. - -### Some Diamond Benefits - -1. A stable contract address that provides needed functionality. -1. A single address with the functionality of multiple contracts (facets) that are independent from each other but can share internal functions, libraries and state variables. -1. Emitting events from a single address can simplify event handling. -1. A way to add, replace and remove multiple external functions atomically (in the same transaction). -1. Fine-grained upgrades, so you can change just the parts of a diamond that need to be changed. -1. Have greater control over when and what functions exist. -1. Decentralized Autonomous Organizations (DAOs), multisig contracts and other governance systems can be used to upgrade diamonds. -1. An event that shows what functions are added, replaced and removed. -1. The ability to show all changes made to a diamond. -1. Increase trust over time by showing all changes made to a diamond. -1. A way to look at a diamond to see its current facets and functions. -1. Have an immutable, trustless diamond. -1. Solves the 24KB maximum contract size limitation. Diamonds can be any size. -1. Separate functionality can be implemented in separate facets and used together in a diamond. -1. Diamonds can be created from already deployed, existing onchain contracts. -1. Larger contracts have to reduce their size by removing error messages and other things. You can keep your full functionality that you need by implementing a diamond. -1. Enables zero, partial or full diamond immutability as desired, and when desired. -1. The ability to develop and improve an application over time with an upgradeable diamond and then make it immutable and trustless if desired. -1. Develop incrementally and let your diamond grow with your application. -1. Upgrade diamonds to fix bugs, add functionality and implement new standards. -1. Organize your code with a diamond and facets. -1. Diamonds can be large (have many functions) but still be modular because they are compartmented with facets. -1. Contract architectures that call multiple contracts in a single transaction can save gas by condensing those contracts into a single diamond and accessing state variables directly. -1. Save gas by converting external functions to internal functions. This done by sharing internal functions between facets. -1. Save gas by creating external functions for gas-optimized specific use cases, such as bulk transfers. -1. Diamonds are designed for tooling and user-interface software. - - -## Specification - -### Terms - -1. A **diamond** is a facade smart contract that `delegatecall`s into its facets to execute function calls. A diamond is stateful. Data is stored in the contract storage of a diamond. -1. A **facet** is a stateless smart contract or Solidity library with external functions. A facet is deployed and one or more of its functions are added to one or more diamonds. A facet does not store data within its own contract storage but it can define state and read and write to the storage of one or more diamonds. The term facet comes from the diamond industry. It is a side, or flat surface of a diamond. -1. A **loupe facet** is a facet that provides introspection functions. In the diamond industry, a loupe is a magnifying glass that is used to look at diamonds. -1. An **immutable function** is an external function that cannot be replaced or removed (because it is defined directly in the diamond, or because the diamond's logic does not allow it to be modified). -1. A **mapping** for the purposes of this EIP is an association between two things and does not refer to a specific implementation. - -The term **contract** is used loosely to mean a smart contract or deployed Solidity library. - -When this EIP uses **function** without specifying internal or external, it means external function. - -In this EIP the information that applies to external functions also applies to public functions. - -### Overview - -A diamond calls functions from its facets using `delegatecall`. - -In the diamond industry diamonds are created and shaped by being cut, creating facets. In this standard diamonds are cut by adding, replacing or removing functions from facets. - -### A Note on Implementing Interfaces - -Because of the nature of diamonds, a diamond can implement an interface in one of two ways: directly (`contract Contract is Interface`), or by adding functions to it from one or more facets. For the purposes of this proposal, when a diamond is said to implement an interface, either method of implementation is permitted. - -### Fallback Function - -When an external function is called on a diamond its fallback function is executed. The fallback function determines which facet to call based on the first four bytes of the call data (known as the function selector) and executes that function from the facet using `delegatecall`. - -A diamond's fallback function and `delegatecall` enable a diamond to execute a facet's function as if it was implemented by the diamond itself. The `msg.sender` and `msg.value` values do not change and only the diamond's storage is read and written to. - -Here is an illustrative example of how a diamond's fallback function might be implemented: - -```solidity -// Find facet for function that is called and execute the -// function if a facet is found and return any value. -fallback() external payable { - // get facet from function selector - address facet = selectorTofacet[msg.sig]; - require(facet != address(0)); - // Execute external function from facet using delegatecall and return any value. - assembly { - // copy function selector and any arguments - calldatacopy(0, 0, calldatasize()) - // execute function call using the facet - let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) - // get any return value - returndatacopy(0, 0, returndatasize()) - // return any return value or error back to the caller - switch result - case 0 {revert(0, returndatasize())} - default {return (0, returndatasize())} - } -} -``` - -This diagram shows the structure of a diamond: - - - -### Storage - -A state variable or storage layout organizational pattern is needed because Solidity's builtin storage layout system doesn't support proxy contracts or diamonds. The particular layout of storage is not defined in this EIP, but may be defined by later proposals. Examples of storage layout patterns that work with diamonds are [Diamond Storage](../assets/eip-2535/storage-examples/DiamondStorage.sol) and [AppStorage](../assets/eip-2535/storage-examples/AppStorage.sol). - -Facets can share state variables by using the same structs at the same storage positions. Facets can share internal functions and libraries by inheriting the same contracts or using the same libraries. In these ways facets are separate, independent units but can share state and functionality. - -The diagram below shows facets with their own data and data shared between them. - -Notice that all data is stored in the diamond's storage, but different facets have different access to data. - -In this diagram - -- Only `FacetA` can access `DataA` -- Only `FacetB` can access `DataB` -- Only the diamond's own code can access `DataD`. -- `FacetA` and `FacetB` share access to `DataAB`. -- The diamond's own code, `FacetA` and `FacetB` share access to `DataABD`. - - - -### Solidity Libraries as Facets - -Smart contracts or deployed Solidity libraries can be facets of diamonds. - -Only Solidity libraries that have one or more external functions can be deployed to a blockchain and be a facet. - -Solidity libraries that contain internal functions only cannot be deployed and cannot be a facet. Internal functions from Solidity libraries are included in the bytecode of facets and contracts that use them. Solidity libraries with internal functions only are useful for sharing internal functions between facets. - -Solidity library facets have a few properties that match their use as facets: -* They cannot be deleted. -* They are stateless. They do not have contract storage. -* Their syntax prevents declaring state variables outside Diamond Storage. - -### Adding/Replacing/Removing Functions - -#### `IDiamond` Interface - -All diamonds must implement the `IDiamond` interface. - -During the deployment of a diamond any immutable functions and any external functions added to the diamond must be emitted in the `DiamondCut` event. - -**A `DiamondCut` event must be emitted any time external functions are added, replaced, or removed.** This applies to all upgrades, all functions changes, at any time, whether through `diamondCut` or not. - -```solidity -interface IDiamond { - enum FacetCutAction {Add, Replace, Remove} - // Add=0, Replace=1, Remove=2 - - struct FacetCut { - address facetAddress; - FacetCutAction action; - bytes4[] functionSelectors; - } - - event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); -} -``` - -The `DiamondCut` event records all function changes to a diamond. - -#### `IDiamondCut` Interface - -A diamond contains within it a mapping of function selectors to facet addresses. Functions are added/replaced/removed by modifying this mapping. - -Diamonds should implement the `IDiamondCut` interface if after their deployment they allow modifications to their function selector mapping. - -The `diamondCut` function updates any number of functions from any number of facets in a single transaction. Executing all changes within a single transaction prevents data corruption which could occur in upgrades done over multiple transactions. - -`diamondCut` is specified for the purpose of interoperability. Diamond tools, software and user-interfaces should expect and use the standard `diamondCut` function. - -```solidity -interface IDiamondCut is IDiamond { - /// @notice Add/replace/remove any number of functions and optionally execute - /// a function with delegatecall - /// @param _diamondCut Contains the facet addresses and function selectors - /// @param _init The address of the contract or facet to execute _calldata - /// @param _calldata A function call, including function selector and arguments - /// _calldata is executed with delegatecall on _init - function diamondCut( - FacetCut[] calldata _diamondCut, - address _init, - bytes calldata _calldata - ) external; -} -``` - -The `_diamondCut` argument is an array of `FacetCut` structs. - -Each `FacetCut` struct contains a facet address and array of function selectors that are updated in a diamond. - -For each `FacetCut` struct: - - * If the `action` is `Add`, update the function selector mapping for each `functionSelectors` item to the `facetAddress`. If any of the `functionSelectors` had a mapped facet, revert instead. - * If the `action` is `Replace`, update the function selector mapping for each `functionSelectors` item to the `facetAddress`. If any of the `functionSelectors` had a value equal to `facetAddress` or the selector was unset, revert instead. - * If the `action` is `Remove`, remove the function selector mapping for each `functionSelectors` item. If any of the `functionSelectors` were previously unset, revert instead. - -Any attempt to replace or remove an immutable function must revert. - -Being intentional and explicit about adding/replacing/removing functions helps catch and prevent upgrade mistakes. - -##### Executing `_calldata` - -After adding/replacing/removing functions the `_calldata` argument is executed with `delegatecall` on `_init`. This execution is done to initialize data or setup or remove anything needed or no longer needed after adding, replacing and/or removing functions. - -If the `_init` value is `address(0)` then `_calldata` execution is skipped. In this case `_calldata` can contain 0 bytes or custom information. - -### Inspecting Facets & Functions - -> A loupe is a small magnifying glass used to look at diamonds. - -Diamonds must support inspecting facets and functions by implementing the `IDiamondLoupe` interface. - -#### `IDiamondLoupe` Interface - -```solidity -// A loupe is a small magnifying glass used to look at diamonds. -// These functions look at diamonds -interface IDiamondLoupe { - struct Facet { - address facetAddress; - bytes4[] functionSelectors; - } - - /// @notice Gets all facet addresses and their four byte function selectors. - /// @return facets_ Facet - function facets() external view returns (Facet[] memory facets_); - - /// @notice Gets all the function selectors supported by a specific facet. - /// @param _facet The facet address. - /// @return facetFunctionSelectors_ - function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); - - /// @notice Get all the facet addresses used by a diamond. - /// @return facetAddresses_ - function facetAddresses() external view returns (address[] memory facetAddresses_); - - /// @notice Gets the facet that supports the given selector. - /// @dev If facet is not found return address(0). - /// @param _functionSelector The function selector. - /// @return facetAddress_ The facet address. - function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); -} -``` - -See a [reference implementation](#reference-implementation) to see how this can be implemented. - -The loupe functions can be used in user-interface software. A user interface calls these functions to provide information about and visualize diamonds. - -The loupe functions can be used in deployment functionality, upgrade functionality, testing and other software. - -### Implementation Points - -A diamond must implement the following: - -1. A diamond contains a fallback function and zero or more immutable functions that are defined within it. -1. A diamond associates function selectors with facets. -1. When a function is called on a diamond it executes immediately if it is an "immutable function" defined directly in the diamond. Otherwise the diamond's fallback function is executed. The fallback function finds the facet associated with the function and executes the function using `delegatecall`. If there is no facet for the function then optionally a default function may be executed. If there is no facet for the function and no default function and no other mechanism to handle it then execution reverts. -1. Each time functions are added, replaced or removed a `DiamondCut` event is emitted to record it. -1. A diamond implements the DiamondLoupe interface. -1. All immutable functions must be emitted in the `DiamondCut` event as new functions added. And the loupe functions must return information about immutable functions if they exist. The facet address for an immutable function is the diamond's address. Any attempt to delete or replace an immutable function must revert. - -A diamond may implement the following: - -1. [EIP-165](./eip-165.md)'s `supportsInterface`. If a diamond has the `diamondCut` function then the interface ID used for it is `IDiamondCut.diamondCut.selector`. The interface ID used for the diamond loupe interface is `IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector`. - -The diamond address is the address that users interact with. The diamond address does not change. Only facet addresses can change by using the `diamondCut` function, or other function. - -## Rationale - -### Using Function Selectors - -User interface software can be used to retrieve function selectors and face addresses from a diamond in order show what functions a diamond has. - -This standard is designed to make diamonds work well with user-interface software. Function selectors with the ABI of a contract provide enough information about functions to be useful for user-interface software. - -### Gas Considerations - -Delegating function calls does have some gas overhead. This is mitigated in several ways: - -1. Because diamonds do not have a max size limitation it is possible to add gas optimizing functions for use cases. For example someone could use a diamond to implement the [EIP-721](./eip-721.md) standard and implement batch transfer functions to reduce gas (and make batch transfers more convenient). -1. Some contract architectures require calling multiple contracts in one transaction. Gas savings can be realized by condensing those contracts into a single diamond and accessing contract storage directly. -1. Facets can contain few external functions, reducing gas costs. Because it costs more gas to call a function in a contract with many functions than a contract with few functions. -1. The Solidity optimizer can be set to a high setting causing more bytecode to be generated but the facets will use less gas when executed. - -### Versions of Functions - -Software or a user can verify what version of a function is called by getting the facet address of the function. This can be done by calling the `facetAddress` function from the `IDiamondLoupe` interface. This function takes a function selector as an argument and returns the facet address where it is implemented. - -### Default Function - -Solidity provides the `fallback` function so that specific functionality can be executed when a function is called on a contract that does not exist in the contract. This same behavior can optionally be implemented in a diamond by implementing and using a default function, which is a function that is executed when a function is called on a diamond that does not exist in the diamond. - -A default function can be implemented a number of ways and this standard does not specify how it must be implemented. - -### Loupe Functions & `DiamondCut` Event - -To find out what functions a regular contract has it is only necessary to look at its verified source code. - -The verified source code of a diamond does not include what functions it has so a different mechanism is needed. - -A diamond has four standard functions called the loupe functions that are used to show what functions a diamond has. - -The loupe functions can be used for many things including: -1. To show all functions used by a diamond. -1. To query services like Etherscan or files to retrieve and show all source code used by a diamond. -1. To query services like Etherscan or files to retrieve ABI information for a diamond. -1. To test or verify that a transaction that adds/replaces/removes functions on a diamond succeeded. -1. To find out what functions a diamond has before calling functions on it. -1. To be used by tools and programming libraries to deploy and upgrade diamonds. -1. To be used by user interfaces to show information about diamonds. -1. To be used by user interfaces to enable users to call functions on diamonds. - -Diamonds support another form of transparency which is a historical record of all upgrades on a diamond. This is done with the `DiamondCut` event which is used to record all functions that are added, replaced or removed on a diamond. - -### Sharing Functions Between Facets - -In some cases it might be necessary to call a function defined in a different facet. Here are ways to do this: - -1. Copy internal function code in one facet to the other facet. -1. Put common internal functions in a contract that is inherited by multiple facets. -1. Put common internal functions in a Solidity library and use the library in facets. -1. A type safe way to call an external function defined in another facet is to do this: `MyOtherFacet(address(this)).myFunction(arg1, arg2)` -1. A more gas-efficient way to call an external function defined in another facet is to use delegatecall. Here is an example of doing that: -```solidity -DiamondStorage storage ds = diamondStorage(); -bytes4 functionSelector = bytes4(keccak256("myFunction(uint256)")); -// get facet address of function -address facet = ds.selectorToFacet[functionSelector]; -bytes memory myFunctionCall = abi.encodeWithSelector(functionSelector, 4); -(bool success, bytes memory result) = address(facet).delegatecall(myFunctionCall); -``` -6. Instead of calling an external function defined in another facet you can instead create an internal function version of the external function. Add the internal version of the function to the facet that needs to use it. - -### Facets can be Reusable and Composable - -A deployed facet can be used by any number of diamonds. - -Different combinations of facets can be used with different diamonds. - -It is possible to create and deploy a set of facets that are reused by different diamonds over time. - -The ability to use the same deployed facets for many diamonds reduces deployment costs. - -It is possible to implement facets in a way that makes them usable/composable/compatible with other facets. It is also possible to implement facets in a way that makes them not usable/composable/compatible with other facets. - -A function signature is the name of a function and its parameter types. Example function signature: `myfunction(uint256)`. A limitation is that two external functions with the same function signature can’t be added to the same diamond at the same time because a diamond, or any contract, cannot have two external functions with the same function signature. - -All the functions of a facet do not have to be added to a diamond. Some functions in a facet can be added to a diamond while other functions in the facet are not added to the diamond. - -## Backwards Compatibility - -This standard makes upgradeable diamonds compatible with future standards and functionality because new functions can be added and existing functions can be replaced or removed. - -## Reference Implementation - -All the Solidity code for a complete reference implementation has been put in a single file here: [Diamond.sol](../assets/eip-2535/reference/Diamond.sol) - -The same reference implementation has been organized into multiple files and directories and also includes a deployment script and tests. Download it as a zip file: [`EIP2535-Diamonds-Reference-Implementation.zip`](../assets/eip-2535/reference/EIP2535-Diamonds-Reference-Implementation.zip) - -## Security Considerations - -### Ownership and Authentication - -> **Note:** The design and implementation of diamond ownership/authentication is **not** part of this standard. The examples given in this standard and in the reference implementation are just **examples** of how it could be done. - -It is possible to create many different authentication or ownership schemes with this proposal. Authentication schemes can be very simple or complex, fine grained or coarse. This proposal does not limit it in any way. For example ownership/authentication could be as simple as a single account address having the authority to add/replace/remove functions. Or a decentralized autonomous organization could have the authority to only add/replace/remove certain functions. - -Consensus functionality could be implemented such as an approval function that multiple different people call to approve changes before they are executed with the `diamondCut` function. These are just examples. - -The development of standards and implementations of ownership, control and authentication of diamonds is encouraged. - -### Arbitrary Execution with `diamondCut` - -The `diamondCut` function allows arbitrary execution with access to the diamond's storage (through `delegatecall`). Access to this function must be restricted carefully. - -### Do Not Self Destruct -Use of `selfdestruct` in a facet is heavily discouraged. Misuse of it can delete a diamond or a facet. - -### Function Selector Clash - -A function selector clash occurs when two different function signatures hash to the same four-byte hash. This has the unintended consequence of replacing an existing function in a diamond when the intention was to add a new function. This scenario is not possible with a properly implemented `diamondCut` function because it prevents adding function selectors that already exist. - -### Transparency - -Diamonds emit an event every time one or more functions are added, replaced or removed. All source code can be verified. This enables people and software to monitor changes to a contract. If any bad acting function is added to a diamond then it can be seen. - -Security and domain experts can review the history of change of a diamond to detect any history of foul play. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2535.md diff --git a/EIPS/eip-2537.md b/EIPS/eip-2537.md index 9a80865676204c..08a5b8dab0db21 100644 --- a/EIPS/eip-2537.md +++ b/EIPS/eip-2537.md @@ -1,67 +1,71 @@ --- eip: 2537 title: Precompile for BLS12-381 curve operations -author: Alex Vlasov (@shamatar), Kelly Olson (@ineffectualproperty) +description: Adds operation on BLS12-381 curve as a precompile in a set necessary to efficiently perform operations such as BLS signature verification. +author: Alex Vlasov (@shamatar), Kelly Olson (@ineffectualproperty), Alex Stokes (@ralexstokes), Antonio Sanso (@asanso) discussions-to: https://ethereum-magicians.org/t/eip2537-bls12-precompile-discussion-thread/4187 -status: Stagnant +status: Review type: Standards Track category: Core created: 2020-02-21 --- -## Simple Summary +## Abstract -This precompile adds operation on BLS12-381 curve as a precompile in a set necessary to *efficiently* perform operations such as BLS signature verification and perform SNARKs verifications. +Add functionality to efficiently perform operations over the BLS12-381 curve, including those for BLS signature verification. -## Abstract +Along with the curve arithmetic, multiexponentiation operations are included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. + +## Motivation + +The motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. + +## Specification -If `block.number >= X` we introduce *nine* separate precompiles to perform the following operations: +### Constants + +| Name | Value | Comment | +|---------------------|-------|--------------------| +| `FORK_TIMESTAMP` | *TBD* | Mainnet | +| BLS12_G1ADD | 0x0b | precompile address | +| BLS12_G1MUL | 0x0c | precompile address | +| BLS12_G1MSM | 0x0d | precompile address | +| BLS12_G2ADD | 0x0e | precompile address | +| BLS12_G2MUL | 0x0f | precompile address | +| BLS12_G2MSM | 0x10 | precompile address | +| BLS12_PAIRING | 0x11 | precompile address | +| BLS12_MAP_FP_TO_G1 | 0x12 | precompile address | +| BLS12_MAP_FP2_TO_G2 | 0x13 | precompile address | + +If `block.timestamp >= FORK_TIMESTAMP` we introduce *nine* separate precompiles to perform the following operations: - BLS12_G1ADD - to perform point addition in G1 (curve over base prime field) with a gas cost of `500` gas - BLS12_G1MUL - to perform point multiplication in G1 (curve over base prime field) with a gas cost of `12000` gas -- BLS12_G1MULTIEXP - to perform multiexponentiation in G1 (curve over base prime field) with a gas cost formula defined in the corresponding section +- BLS12_G1MSM - to perform multi-scalar-multiplication (MSM) in G1 (curve over base prime field) with a gas cost formula defined in the corresponding section - BLS12_G2ADD - to perform point addition in G2 (curve over quadratic extension of the base prime field) with a gas cost of `800` gas - BLS12_G2MUL - to perform point multiplication in G2 (curve over quadratic extension of the base prime field) with a gas cost of `45000` gas -- BLS12_G2MULTIEXP - to perform multiexponentiation in G2 (curve over quadratic extension of the base prime field) with a gas cost formula defined in the corresponding section +- BLS12_G2MSM - to perform multi-scalar-multiplication (MSM) in G2 (curve over quadratic extension of the base prime field) with a gas cost formula defined in the corresponding section - BLS12_PAIRING - to perform a pairing operations between a set of *pairs* of (G1, G2) points a gas cost formula defined in the corresponding section -- BLS12_MAP_FP_TO_G1 - maps base field element into the G1 point with a gast cost of `5500` gas +- BLS12_MAP_FP_TO_G1 - maps base field element into the G1 point with a gas cost of `5500` gas - BLS12_MAP_FP2_TO_G2 - maps extension field element into the G2 point with a gas cost of `75000` gas -Mapping functions specification is included as a separate [document](../assets/eip-2537/field_to_curve.md). Mapping function does NOT perform mapping of the byte string into field element (as it can be implemented in many different ways and can be efficiently performed in EVM), but only does field arithmetic to map field element into curve point. Such functionality is required for signature schemes. - -Multiexponentiation operation is included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. - -### Proposed addresses table - -|Precompile |Address | -|---|---| -|BLS12_G1ADD | 0x0a | -|BLS12_G1MUL | 0x0b | -|BLS12_G1MULTIEXP | 0x0c | -|BLS12_G2ADD | 0x0d | -|BLS12_G2MUL | 0x0e | -|BLS12_G2MULTIEXP | 0x0f | -|BLS12_PAIRING | 0x10 | -|BLS12_MAP_FP_TO_G1 | 0x11 | -|BLS12_MAP_FP2_TO_G2 | 0x12 | - -## Motivation - -Motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. - -## Specification +A mapping functions specification is included as a separate [document](../assets/eip-2537/field_to_curve.md). This mapping function does NOT perform mapping of the byte string into a field element (as it can be implemented in many different ways and can be efficiently performed in EVM), but only does field arithmetic to map a field element into a curve point. Such functionality is required for signature schemes. -Curve parameters: +### Curve parameters -BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): +The BLS12 curve is fully defined by the following set of parameters (coefficient `A=0` for all BLS12 curves): ``` -Base field modulus = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +Base field modulus = p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +Fp - finite field of size p +Curve Fp equation: Y^2 = X^3+B (mod p) B coefficient = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 -Main subgroup order = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +Main subgroup order = q = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 Extension tower Fp2 construction: -Fp quadratic non-residue = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa +Fp quadratic non-residue = nr2 = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa +Fp2 is Fp[X]/(X^2-nr2) +Curve Fp2 equation: Y^2 = X^3 + B*(v+1) where v is the square root of nr2 Fp6/Fp12 construction: Fp2 cubic non-residue c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 Fp2 cubic non-residue c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 @@ -70,10 +74,10 @@ Twist type: M B coefficient for twist c0 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 B coefficient for twist c1 = 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 Generators: -G1: +H1: X = 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb Y = 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1 -G2: +H2: X c0 = 0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8 X c1 = 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e Y c0 = 0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801 @@ -83,37 +87,47 @@ Pairing parameters: x is negative = true ``` -One should note that base field modulus is equal to `3 mod 4` that allows an efficient square root extraction, although as described below gas cost of decompression is larger than gas cost of supplying decompressed point data in `calldata`. +One should note that base field modulus `p` is equal to `3 mod 4` that allows an efficient square root extraction, although as described below gas cost of decompression is larger than gas cost of supplying decompressed point data in `calldata`. + +### Fields and Groups + +Field Fp is defined as the finite field of size `p` with elements represented as integers between 0 and p-1 (both inclusive). + +Field Fp2 is defined as `Fp[X]/(X^2-nr2)` with elements `el = c0 + c1 * v`, where `v` is the formal square root of `nr2` represented as integer pairs `(c0,c1)`. + +Group G1 is defined as a set of Fp pairs (points) `(x,y)` such that either `(x,y)` is `(0,0)` or `x,y` satisfy the curve Fp equation. + +Group G2 is defined as a set of Fp2 pairs (points) `(x',y')` such that either `(x,y)` is `(0,0)` or `(x',y')` satisfy the curve Fp2 equation. ### Fine points and encoding of base elements #### Field elements encoding: -To encode points involved in the operation one has to encode elements of the base field and the extension field. +In order to produce inputs to an operation, one encodes elements of the base field and the extension field. -Base field element (Fp) is encoded as `64` bytes by performing BigEndian encoding of the corresponding (unsigned) integer (top `16` bytes are always zeroes). `64` bytes are chosen to have `32` byte aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]`). Corresponding integer **must** be less than field modulus. +A base field element (Fp) is encoded as `64` bytes by performing the BigEndian encoding of the corresponding (unsigned) integer. Due to the size of `p`, the top `16` bytes are always zeroes. `64` bytes are chosen to have `32` byte aligned ABI (representable as e.g. `bytes32[2]` or `uint256[2]` with the latter assuming the BigEndian encoding). The corresponding integer **must** be less than field modulus. -For elements of the quadratic extension field (Fp2) encoding is byte concatenation of individual encoding of the coefficients totaling in `128` bytes for a total encoding. For an Fp2 element in a form `el = c0 + c1 * v` where `v` is formal quadratic non-residue and `c0` and `c1` are Fp elements the corresponding byte encoding will be `encode(c0) || encode(c1)` where `||` means byte concatenation (or one can use `bytes32[4]` or `uint256[4]` in terms of Solidity types). +For elements of the quadratic extension field (Fp2), encoding is byte concatenation of individual encoding of the coefficients totaling in `128` bytes for a total encoding. For an Fp2 element in a form `el = c0 + c1 * v` where `v` is the formal square root of a quadratic non-residue and `c0` and `c1` are Fp elements the corresponding byte encoding will be `encode(c0) || encode(c1)` where `||` means byte concatenation (or one can use `bytes32[4]` or `uint256[4]` in terms of Solidity types). -*Note on the top `16` bytes being zero*: it's required that the encoded element is "in a field" that means strictly `< modulus`. In BigEndian encoding it automatically means that for a modulus that is just `381` bit long top `16` bytes in `64` bytes encoding are zeroes and it **must** be checked if only a subslice of input data is used for actual decoding. +*Note on the top `16` bytes being zero*: it is required that an encoded element is "in a field", which means strictly `< modulus`. In BigEndian encoding it automatically means that for a modulus that is just `381` bit long the top `16` bytes in `64` bytes encoding are zeroes and this **must** be checked even if only a subslice of input data is used for actual decoding. -If encodings do not follow this spec anywhere during parsing in the precompile the precompile *must* return an error. +On inputs that can not be a valid encodings of field elements the precompile *must* return an error. #### Encoding of points in G1/G2: -Points in either G1 (in base field) or in G2 (in extension field) are encoded as byte concatenation of encodings of the `x` and `y` affine coordinates. Total encoding length for G1 point is thus `128` bytes and for G2 point is `256` bytes. +Points of G1 and G2 are encoded as byte concatenation of the respective encodings of the `x` and `y` coordinates. Total encoding length for a G1 point is thus `128` bytes and for a G2 point is `256` bytes. #### Point of infinity encoding: -Also referred to as "zero point". For BLS12 curves point with coordinates `(0, 0)` (formal zeroes in Fp or Fp2) is *not* on the curve, so encoding of such point `(0, 0)` is used as a convention to encode point of infinity. +Also referred to as the "zero point". For BLS12 curves, the point with coordinates `(0, 0)` (zeroes in Fp or Fp2) is *not* on the curve, so a sequence of `128` resp. `256` zero bytes, which naively would decode as `(0, 0)` is instead used by convention to encode the point of infinity of G1 resp. G2. #### Encoding of scalars for multiplication operation: -Scalar for multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. Corresponding integer is **not** required to be less than or equal than main subgroup size. +A scalar for the multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. The corresponding integer is **not** required to be less than or equal than main subgroup order `q`. #### Behavior on empty inputs: -Certain operations have variable length input, such as multiexponentiations (takes a list of pairs `(point, scalar)`), or pairing (takes a list of `(G1, G2)` points). While their behavior is well-defined (from arithmetic perspective) on empty inputs, this EIP discourages such use cases and variable input length operations must return an error if input is empty. +Certain operations have variable length input, such as MSMs (takes a list of pairs `(point, scalar)`), or pairing (takes a list of `(G1, G2)` points). While their behavior is well-defined (from an arithmetic perspective) on empty inputs, this EIP discourages such use cases and variable input length operations must return an error if the input is empty. ### ABI for operations @@ -122,99 +136,124 @@ Certain operations have variable length input, such as multiexponentiations (tak G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). Output is an encoding of addition operation result - single G1 point (`128` bytes). Error cases: -- Either of points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point - Input has invalid length +Note: + +There is no subgroup check for the G1 addition precompile. + #### ABI for G1 multiplication -G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G1 point (`128` bytes). +G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of a G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of the multiplication operation result - a single G1 point (`128` bytes). Error cases: -- Point being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- An input is on the G1 elliptic curve but not in the correct subgroup - Input has invalid length -#### ABI for G1 multiexponentiation +#### ABI for G1 MSM -G1 multiexponentiation call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). +G1 MSM call expects `160*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of a G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G1 point (`128` bytes). Error cases: -- Any of G1 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G1 elliptic curve nor the infinity point +- An input is on the G1 elliptic curve but not in the correct subgroup - Input has invalid length -- Input is empty #### ABI for G2 addition -G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - single G2 point (`256` bytes). +G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - a single G2 point (`256` bytes). Error cases: -- Either of points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point - Input has invalid length +Note: + +There is no subgroup check for the G2 addition precompile. + #### ABI for G2 multiplication G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G2 point (`256` bytes). Error cases: -- Point being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- An input is on the G2 elliptic curve but not in the correct subgroup - Input has invalid length -#### ABI for G2 multiexponentiation +#### ABI for G2 MSM -G2 multiexponentiation call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). +G2 MSM call expects `288*k` (`k` being a **positive** integer) bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of MSM operation result - a single G2 point (`256` bytes). Error cases: -- Any of G2 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on the G2 elliptic curve nor the infinity point +- An input is on the G2 elliptic curve but not in the correct subgroup - Input has invalid length -- Input is empty #### ABI for pairing -Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: +Pairing call expects `384*k` (`k` being a **positive** integer) bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: + - `128` bytes of G1 point encoding - `256` bytes of G2 point encoding -Output is a `32` bytes where first `31` bytes are equal to `0x00` and the last byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise. +Each point is expected to be in the subgroup of order `q`. + +Output is `32` bytes where first `31` bytes are equal to `0x00` and the last byte is `0x01` if pairing result is equal to the multiplicative identity in a pairing target field and `0x00` otherwise. Error cases: -- Any of G1 or G2 points being not on the curve must result in error -- Any of G1 or G2 points are not in the correct subgroup -- Field elements encoding rules apply (obviously) + +- Invalid coordinate encoding +- An input is neither a point on its respective elliptic curve nor the infinity point +- An input is on its respective elliptic curve but not in the correct subgroup - Input has invalid length -- Input is empty + +Note: + +If any input is the infinity point, pairing result will be 1. Protocols may want to check and reject infinity points prior to calling the precompile. #### ABI for mapping Fp element to G1 point -Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. Output of this call is `128` bytes and is G1 point following respective encoding rules. +Field-to-curve call expects `64` bytes as an input that is interpreted as an element of Fp. Output of this call is `128` bytes and is an encoded G1 point. Error cases: + - Input has invalid length -- Input is not a valid field element +- Input is not correctly encoded #### ABI for mapping Fp2 element to G2 point -Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. Output of this call is `256` bytes and is G2 point following respective encoding rules. +Field-to-curve call expects `128` bytes as an input that is interpreted as an element of Fp2. Output of this call is `256` bytes and is an encoded G2 point. Error cases: + - Input has invalid length -- Input is not a valid field element +- Input is not correctly encoded -### Gas burinig on error +### Gas burning on error -Following the current state of all other precompiles if call to one of the precompiles in this EIP results in an error then all the gas supplied along with a `CALL` or `STATICCALL` is burned. +Following the current state of all other precompiles, if a call to one of the precompiles in this EIP results in an error then all the gas supplied along with a `CALL` or `STATICCALL` is burned. ### DDoS protection -Sane implementation of this EIP *should not* contain infinite cycles (it is possible and not even hard to implement all the functionality without `while` cycles) and gas schedule accurately reflects a time spent on computations of the corresponding function (precompiles pricing reflects an amount of gas consumed in the worst case where such case exists). +A sane implementation of this EIP *should not* contain potential infinite loops (it is possible and not even hard to implement all the functionality without `while` loops) and the gas schedule accurately reflects the time spent on computations of the corresponding function (precompiles pricing reflects an amount of gas consumed in the worst case where such a case exists). ### Gas schedule -Assuming a constant `30 MGas/second` following prices are suggested. +Assuming a constant `30 MGas/second`, the following prices are suggested. #### G1 addition @@ -232,11 +271,11 @@ Assuming a constant `30 MGas/second` following prices are suggested. `45000` gas -#### G1/G2 Multiexponentiation +#### G1/G2 MSM -Multiexponentiations are expected to be performed by the Peppinger algorithm (we can also say that is **must** be performed by Peppinger algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the multiexponentiation with a discount cup `max_discount` for `k > 128`. +MSMs are expected to be performed by Pippenger's algorithm (we can also say that it **must** be performed by Pippenger's algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the MSM with a discount cup `max_discount` for `k > 128`. -To avoid non-integer arithmetic call cost is calculated as `(k * multiplication_cost * discount) / multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding single multiplication call cost for G1/G2. +To avoid non-integer arithmetic, the call cost is calculated as `(k * multiplication_cost * discount) / multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding single multiplication call cost for G1/G2. Discounts table as a vector of pairs `[k, discount]`: @@ -248,7 +287,7 @@ Discounts table as a vector of pairs `[k, discount]`: #### Pairing operation -Cost of the pairing operation is `43000*k + 65000` where `k` is a number of pairs. +The cost of the pairing operation is `43000*k + 65000` where `k` is a number of pairs. #### Fp-to-G1 mapping operation @@ -260,72 +299,70 @@ Fp2 -> G2 mapping is `75000` gas #### Gas schedule clarifications for the variable-length input -For multiexponentiation and pairing functions gas cost depends on the input length. The current state of how gas schedule is implemented in major clients (at the time of writing) is that gas cost function does *not* perform any validation of the length of the input and never returns an error. So we present a list of rules how gas cost functions **must** be implemented to ensure consistency between clients and safety. +For MSM and pairing functions, the gas cost depends on the input length. The current state of how the gas schedule is implemented in major clients (at the time of writing) is that the gas cost function does *not* perform any validation of the length of the input and never returns an error. So we present a list of rules how the gas cost functions **must** be implemented to ensure consistency between clients and safety. -##### Gas schedule clarifications for G1/G2 Multiexponentiation +##### Gas schedule clarifications for G1/G2 MSM Define a constant `LEN_PER_PAIR` that is equal to `160` for G1 operation and to `288` for G2 operation. Define a function `discount(k)` following the rules in the corresponding section, where `k` is number of pairs. The following pseudofunction reflects how gas should be calculated: -``` - k = floor(len(input) / LEN_PER_PAIR); - if k == 0 { - return 0; - } - - gas_cost = k * multiplication_cost * discount(k) / multiplier; - - return gas_cost; +``` +k = floor(len(input) / LEN_PER_PAIR); +if k == 0 { + return 0; +} +gas_cost = k * multiplication_cost * discount(k) / multiplier; +return gas_cost; ``` -We use floor division to get number of pairs. If length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on precompile will return an error. Also, case when `k = 0` is safe: `CALL` or `STATICCALL` cost is non-zero, and case with formal zero gas cost is already used in `Blake2f` precompile. In any case, main precompile routine **must** produce an error on such an input because it violated encoding rules. +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error. Also, the case when `k = 0` is safe: `CALL` or `STATICCALL` cost is non-zero, and the case with formal zero gas cost is already used in `Blake2f` precompile. In any case, the main precompile routine **must** produce an error on such an input because it violated encoding rules. ##### Gas schedule clarifications for pairing Define a constant `LEN_PER_PAIR = 384`; The following pseudofunction reflects how gas should be calculated: -``` - k = floor(len(input) / LEN_PER_PAIR); - - gas_cost = 23000*k + 115000; - - return gas_cost; +``` +k = floor(len(input) / LEN_PER_PAIR); +gas_cost = 43000*k + 65000; +return gas_cost; ``` -We use floor division to get number of pairs. If length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on precompile will return an error (precompile routine **must** produce an error on such an input because it violated encoding rules). +We use floor division to get the number of pairs. If the length of the input is not divisible by `LEN_PER_PAIR` we still produce *some* result, but later on the precompile will return an error (the precompile routine **must** produce an error on such an input because it violated encoding rules). ## Rationale -Motivation section covers a total motivation to have operations over BLS12-381 curve available. We also extend a rationale for move specific fine points. +The motivation section covers a total motivation to have operations over the BLS12-381 curves available. We also extend a rationale for more specific fine points. -### Multiexponentiation as a separate call +### MSM as a separate call -Explicit separate multiexponentiation operation that allows one to save execution time (so gas) by both the algorithm used (namely Peppinger algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negigible overhead if e.g. for multiexponentiation of `100` points would have to call the multipication precompile `100` times and addition for `99` times (roughly `138600` would be saved). +Explicit separate MSM operation that allows one to save execution time (so gas) by both the algorithm used (namely Pippenger's algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negligible overhead if e.g. for MSM of `100` points would have to call the multiplication precompile `100` times and addition for `99` times (roughly `138600` would be saved). ## Backwards Compatibility There are no backward compatibility questions. -## Important notes - ### Subgroup checks -Subgroup check **is mandatory** during the pairing call. Implementations *should* use fast subgroup checks: at the time of writing multiplication gas cost is based on `double-and-add` multiplication method that has a clear "worst case" (all bits are equal to one). For pairing operation it's expected that implementation uses faster subgroup check, e.g. by using wNAF multiplication method for elliptic curves that is ~ `40%` cheaper with windows size equal to 4. (Tested empirically. Savings are due to lower hamming weight of the group order and even lower hamming weight for wNAF. Concretely, subgroup check for both G1 and G2 points in a pair are around `35000` combined). +Scalar multiplications, MSMs and pairings MUST perform a subgroup check. +Implementations SHOULD use the optimized subgroup check method detailed in a dedicated [document](../assets/eip-2537/fast_subgroup_checks.md). +On any input that fails the subgroup check, the precompile MUST return an error. +As endomorphism acceleration requires input on the correct subgroup, implementers MAY use endomorphism acceleration. ### Field to curve mapping -Algorithms and set of parameters for SWU mapping method is provided by a separate [document](../assets/eip-2537/field_to_curve.md) +The algorithms and set of parameters for SWU mapping method are provided by a separate [document](../assets/eip-2537/field_to_curve.md) ## Test Cases -Due to the large test parameters space we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. Generator for G1 is labeled as `G`, generator for G2 is labeled as `H`, otherwise we assume random point on a curve in a correct subgroup. `0` means either scalar zero or point of infinity. `1` means either scalar one or multiplicative identity. `group_order` is a main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. +Due to the large test parameters space, we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. The generator for G1 is labeled as `G`, the generator for G2 is labeled as `H`, otherwise we assume random points on a curve in a correct subgroup. `0` means either scalar zero or point at infinity. `1` means either scalar one or multiplicative identity. `group_order` is the main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. -Requeired properties for basic ops (add/multiply): +Required properties for basic ops (add/multiply): - Commutativity: `P + Q = Q + P` +- Identity element: `P + 0 = P` - Additive negation: `P + (-P) = 0` - Doubling `P + P = 2*P` - Subgroup check: `group_order * P = 0` @@ -334,8 +371,13 @@ Requeired properties for basic ops (add/multiply): - Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` Required properties for pairing operation: -- Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` -- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) + +- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` +- Non-degeneracy `e(P, Q) != 1` +- `e(P, 0*Q) = e(0*P, Q) = 1` +- `e(P, -Q) = e(-P, Q)` + +Test vectors can be found [in the test vectors files](../assets/eip-2537/test-vectors.md). ### Benchmarking test cases @@ -344,7 +386,8 @@ A set of test vectors for quick benchmarking on new implementations is located i ## Reference Implementation There are two fully spec compatible implementations on the day of writing: -- One in Rust language that is based on the EIP1962 code and integrated with OpenEthereum for this library + +- One in Rust language that is based on the [EIP-196](./eip-196.md) code and integrated with OpenEthereum for this library - One implemented specifically for Geth as a part of the current codebase ## Security Considerations @@ -354,4 +397,5 @@ Strictly following the spec will eliminate security implications or consensus im Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2539.md b/EIPS/eip-2539.md index d84fa690191bb1..3e4f850a592dfd 100644 --- a/EIPS/eip-2539.md +++ b/EIPS/eip-2539.md @@ -1,20 +1,20 @@ --- eip: 2539 title: BLS12-377 curve operations -author: Alex Vlasov (@shamatar) +description: Precompiles for BLS12-377 curve operations +author: Alex Vlasov (@shamatar), hujw77 (@hujw77) discussions-to: https://ethereum-magicians.org/t/eip-2539-bls12-377-precompile-discussion-thread/4659 -status: Stagnant +status: Draft type: Standards Track category: Core created: 2020-02-26 requires: 1109, 2046 --- -## Simple Summary -This precompile adds operation on BLS12-377 curve (from Zexe paper) as a precompile in a set necessary to *efficiently* perform operations such as BLS signature verification and perform SNARKs verifications. Unique properties of BLS12-377 also later allow to have SNARKs that check BLS12-377 pairing in an efficient way and allow e.g. constant-size BLS signature aggregation. - ## Abstract +This precompile adds operation on BLS12-377 curve (from Zexe paper) as a precompile in a set necessary to *efficiently* perform operations such as BLS signature verification and perform SNARKs verifications. Unique properties of BLS12-377 also later allow to have SNARKs that check BLS12-377 pairing in an efficient way and allow e.g. constant-size BLS signature aggregation. + If `block.number >= X` we introduce *nine* separate precompiles to perform the following operations: - BLS12_377_G1ADD - to perform point addition on a curve defined over prime field @@ -24,22 +24,27 @@ If `block.number >= X` we introduce *nine* separate precompiles to perform the f - BLS12_377_G2MUL - to perform point multiplication on a curve twist defined over quadratic extension of the base field - BLS12_377_G2MULTIEXP - to perform multiexponentiation on a curve twist defined over quadratic extension of the base field - BLS12_377_PAIRING - to perform a pairing operations between a set of *pairs* of (G1, G2) points +- BLS12_377_MAP_FP_TO_G1 - maps base field element into the G1 point +- BLS12_377_MAP_FP2_TO_G2 - maps extension field element into the G2 point Multiexponentiation operation is included to efficiently aggregate public keys or individual signer's signatures during BLS signature verification. ### Proposed addresses table -|Precompile |Address | -|---|---| -|BLS12_377_G1ADD | 0x13 | -|BLS12_377_G1MUL | 0x14 | -|BLS12_377_G1MULTIEXP | 0x15 | -|BLS12_377_G2ADD | 0x16 | -|BLS12_377_G2MUL | 0x17 | -|BLS12_377_G2MULTIEXP | 0x18 | -|BLS12_377_PAIRING | 0x19 | +| Precompile | Address | +| ----------------------- | ------- | +| BLS12_377_G1ADD | 0x15 | +| BLS12_377_G1MUL | 0x16 | +| BLS12_377_G1MULTIEXP | 0x17 | +| BLS12_377_G2ADD | 0x18 | +| BLS12_377_G2MUL | 0x19 | +| BLS12_377_G2MULTIEXP | 0x1a | +| BLS12_377_PAIRING | 0x1b | +| BLS12_377_MAP_FP_TO_G1 | 0x1c | +| BLS12_377_MAP_FP2_TO_G2 | 0x1d | ## Motivation + Motivation of this precompile is to add a cryptographic primitive that allows to get 120+ bits of security for operations over pairing friendly curve compared to the existing BN254 precompile that only provides 80 bits of security. In addition it allows efficient one-time recursive proof aggregations, e.g. proofs about existence of BLS12-377 based signature. ## Specification @@ -76,9 +81,9 @@ Pairing parameters: x is negative = false ``` -#### Fine points and encoding of base elements +### Fine points and encoding of base elements -##### Field elements encoding: +#### Field elements encoding: To encode points involved in the operation one has to encode elements of the base field and the extension field. @@ -88,114 +93,130 @@ For elements of the quadratic extension field (Fp2) encoding is byte concatenati If encodings do not follow this spec anywhere during parsing in the precompile the precompile *must* return an error. -##### Encoding of points in G1/G2: +#### Encoding of points in G1/G2: Points in either G1 (in base field) or in G2 (in extension field) are encoded as byte concatenation of encodings of the `x` and `y` affine coordinates. Total encoding length for G1 point is thus `128` bytes and for G2 point is `256` bytes. -##### Point of infinity encoding: +#### Point of infinity encoding: Also referred as "zero point". For BLS12 curves point with coordinates `(0, 0)` (formal zeroes in Fp or Fp2) is *not* on the curve, so encoding of such point `(0, 0)` is used as a convention to encode point of infinity. -##### Encoding of scalars for multiplication operation: +#### Encoding of scalars for multiplication operation: Scalar for multiplication operation is encoded as `32` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. Corresponding integer is **not** required to be less than or equal than main subgroup size. -#### ABI for operations +### ABI for operations -##### ABI for G1 addition +#### ABI for G1 addition G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). Output is an encoding of addition operation result - single G1 point (`128` bytes). Error cases: -- Either of points being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Either of points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G1 multiplication +#### ABI for G1 multiplication G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G1 point (`128` bytes). Error cases: -- Point being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G1 multiexponentiation +#### ABI for G1 multiexponentiation G1 multiexponentiation call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). Error cases: -- Any of G1 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Any of G1 points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G2 addition +#### ABI for G2 addition G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). Output is an encoding of addition operation result - single G2 point (`256` bytes). Error cases: -- Either of points being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Either of points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G2 multiplication +#### ABI for G2 multiplication G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiplication operation result - single G2 point (`256` bytes). Error cases: -- Point being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Point being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for G2 multiexponentiation +#### ABI for G2 multiexponentiation G2 multiexponentiation call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). Error cases: -- Any of G2 points being not on the curve must result in error -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Any of G2 points being not on the curve must result in error + - Field elements encoding rules apply (obviously) + - Input has invalid length -##### ABI for pairing +#### ABI for pairing Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: -- `128` bytes of G1 point encoding -- `256` bytes of G2 point encoding + - `128` bytes of G1 point encoding + - `256` bytes of G2 point encoding Output is a `32` bytes where first `31` bytes are equal to `0x00` and the last byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise. Error cases: -- Invalid encoding of any boolean variable must result in error -- Any of G1 or G2 points being not on the curve must result in error -- Any of G1 or G2 points are not in the correct subgroup -- Field elements encoding rules apply (obviously) -- Input has invalid length + - Invalid encoding of any boolean variable must result in error + - Any of G1 or G2 points being not on the curve must result in error + - Any of G1 or G2 points are not in the correct subgroup + - Field elements encoding rules apply (obviously) + - Input has invalid length + +#### ABI for mapping Fp element to G1 point + +Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. Output of this call is `128` bytes and is G1 point following respective encoding rules. + +Error cases: + - Input has invalid length + - Input is not a valid field element -#### Prevention of DDoS on error handling +#### ABI for mapping Fp2 element to G2 point + +Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. Output of this call is `256` bytes and is G2 point following respective encoding rules. + +Error cases: + - Input has invalid length + - Input is not a valid field element -This precompile performs extensive computations and in case of any errors during execution it MUST consume all gas from the the gas schedule for the corresponding operation. +### Prevention of DDoS on error handling -#### Gas schedule +This precompile performs extensive computations and in case of any errors during execution it MUST consume all gas from the gas schedule for the corresponding operation. + +### Gas schedule Assuming a constant `30 MGas/second` following prices are suggested. -##### G1 addition +#### G1 addition `600` gas -##### G1 multiplication +#### G1 multiplication `12000` gas -##### G2 addition +#### G2 addition `4500` gas -##### G2 multiplication +#### G2 multiplication `55000` gas -##### G1/G2 Multiexponentiation +#### G1/G2 Multiexponentiation Multiexponentiations are expected to be performed by the Peppinger algorithm (we can also say that is **must** be performed by Peppinger algorithm to have a speedup that results in a discount over naive implementation by multiplying each pair separately and adding the results). For this case there was a table prepared for discount in case of `k <= 128` points in the multiexponentiation with a discount cup `max_discount` for `k > 128`. @@ -209,23 +230,33 @@ Discounts table as a vector of pairs `[k, discount]`: `max_discount = 174` -##### Pairing operation +#### Pairing operation Cost of the pairing operation is `55000*k + 65000` where `k` is a number of pairs. +#### Fp-to-G1 mapping operation + +Fp -> G1 mapping is `5500` gas. + +#### Fp2-to-G2 mapping operation + +Fp2 -> G2 mapping is `75000` gas + ## Rationale + Motivation section covers a total motivation to have operations over BLS12-377 curve available. We also extend a rationale for move specific fine points. -#### Multiexponentiation as a separate call +### Multiexponentiation as a separate call Explicit separate multiexponentiation operation that allows one to save execution time (so gas) by both the algorithm used (namely Peppinger algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negigible overhead if e.g. for multiexponentiation of `100` points would have to call the multipication precompile `100` times and addition for `99` times (roughly `138600` would be saved). ## Backwards Compatibility + There are no backward compatibility questions. -## Important notes +### Important notes -### Subgroup checks +#### Subgroup checks Subgroup check **is mandatory** during the pairing call. Implementations *should* use fast subgroup checks: at the time of writing multiplication gas cost is based on `double-and-add` multiplication method that has a clear "worst case" (all bits are equal to one). For pairing operation it's expected that implementation uses faster subgroup check, e.g. by using wNAF multiplication method for elliptic curves that is ~ `40%` cheaper with windows size equal to 4. (Tested empirically. Savings are due to lower hamming weight of the group order and even lower hamming weight for wNAF. Concretely, subgroup check for both G1 and G2 points in a pair are around `35000` combined). @@ -234,33 +265,35 @@ Subgroup check **is mandatory** during the pairing call. Implementations *should Due to the large test parameters space we first provide properties that various operations must satisfy. We use additive notation for point operations, capital letters (`P`, `Q`) for points, small letters (`a`, `b`) for scalars. Generator for G1 is labeled as `G`, generator for G2 is labeled as `H`, otherwise we assume random point on a curve in a correct subgroup. `0` means either scalar zero or point of infinity. `1` means either scalar one or multiplicative identity. `group_order` is a main subgroup order. `e(P, Q)` means pairing operation where `P` is in G1, `Q` is in G2. Requeired properties for basic ops (add/multiply): - -- Commutativity: `P + Q = Q + P` -- Additive negation: `P + (-P) = 0` -- Doubling `P + P = 2*P` -- Subgroup check: `group_order * P = 0` -- Trivial multiplication check: `1 * P = P` -- Multiplication by zero: `0 * P = 0` -- Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` + - Commutativity: `P + Q = Q + P` + - Additive negation: `P + (-P) = 0` + - Doubling `P + P = 2*P` + - Subgroup check: `group_order * P = 0` + - Trivial multiplication check: `1 * P = P` + - Multiplication by zero: `0 * P = 0` + - Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` Required properties for pairing operation: -- Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` -- Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) + - Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` + - Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) + +Test vector for all operations are expanded in this `csv` files in matter-labs' 1962 proposol. -Test vector for all operations are expanded in this `csv` files in [repo](https://github.com/matter-labs/eip1962/tree/master/src/test/test_vectors/eip2537). +## Reference Implementation -## Implementation There is a various choice of existing implementations of the curve operations. It may require extra work to add an ABI: -- EIP1962 code bases with fixed parameters - - [Rust](https://github.com/matter-labs/eip1962) - - [C++](https://github.com/matter-labs/eip1962_cpp) -- Original implementation linked in Zexe paper in [Rust](https://github.com/scipr-lab/zexe) -- Standalone in [Go](https://github.com/kilic/bls12-377) + - Code bases with fixed parameters + - Rust: matter-labs + - C++: matter-labs + - Original implementation linked in Zexe paper in Rust: github.com/scipr-lab/zexe + - Standalone in Go: github.com/kilic/bls12-377 ## Security Considerations + Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. ## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-2544.md b/EIPS/eip-2544.md index 4df16b5dfb930f..98dbdbe943eb3d 100644 --- a/EIPS/eip-2544.md +++ b/EIPS/eip-2544.md @@ -1,126 +1,7 @@ --- eip: 2544 -title: ENS Wildcard Resolution -description: Adds support for "wildcard" resolution of subdomains in ENS. -author: Nick Johnson (@arachnid), 0age (@0age) -discussions-to: https://ethereum-magicians.org/t/eip-2544-ens-wildcard-resolution -status: Stagnant -type: Standards Track category: ERC -created: 2020-02-28 -requires: 137 +status: Moved --- -## Abstract - -The Ethereum Name Service Specification (EIP-137) establishes a two-step name resolution process. First, an ENS client performs the namehash algorithm on the name to determine the associated "node", and supplies that node to the ENS Registry contract to determine the resolver. Then, if a resolver has been set on the Registry, the client supplies that same node to the resolver contract, which will return the associated address or other record. - -As currently specified, this process terminates if a resolver is not set on the ENS Registry for a given node. This EIP changes the name resolution process by adding an additional step if a resolver is not set for a domain. This step strips out the leftmost label from the name, derives the node of the new fragment, and supplies that node to the ENS Registry. If a resolver is located for that node, the client supplies the original, complete node to that resolver contract to derive the relevant records. This step is repeated until a node with a resolver is found. - -Further, this specification defines a new way for resolvers to resolve names, using a unified `resolve()` method that permits more flexible handling of name resolution. - -## Motivation - -Many applications such as wallet providers, exchanges, and dapps have expressed a desire to issue ENS names for their users via custom subdomains on a shared parent domain. However, the cost of doing so is currently prohibitive for large user bases, as a distinct record must be set on the ENS Registry for each subdomain. - -Furthermore, users cannot immediately utilize these subdomains upon account creation, as the transaction to assign a resolver for the node of the subdomain must first be submitted and mined on-chain. This adds unnecessary friction when onboarding new users, who coincidentally would often benefit greatly from the usability improvements afforded by an ENS name. - -Enabling wildcard support allows for the design of more advanced resolvers that deterministically generate addresses and other records for unassigned subdomains. The generated addresses could map to counterfactual contract deployment addresses (i.e. `CREATE2` addresses), to designated "fallback" addresses, or other schemes. Additionally, individual resolvers would still be assignable to any given subdomain, which would supersede the wildcard resolution using the parent resolver. - -Another critical motivation with EIP-2544 is to enable wildcard resolution in a backwards-compatible fashion. It does not require modifying the current ENS Registry contract or any existing resolvers, and continues to support existing ENS records — legacy ENS clients would simply fail to resolve wildcard records. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Let: - - `namehash` be the algorithm defined in EIP 137. - - `dnsencode` be the process for encoding DNS names specified in section 3.1 of RFC1035, with the exception that there is no limit on the total length of the encoded name. The empty string is encoded identically to the name '.', as a single 0-octet. - - `parent` be a function that removes the first label from a name (eg, `parent('foo.eth') = 'eth'`). `parent('tld')` is defined as the empty string ''. - - `ens` is the ENS registry contract for the current network. - -EIP-2544-compliant ENS resolvers MAY implement the following function interface: - -``` -interface ExtendedResolver { - function resolve(bytes calldata name, bytes calldata data) external view returns(bytes); -} -``` - -If a resolver implements this function, it MUST return true when `supportsInterface()` is called on it with the interface's ID, 0xTBD. - -ENS clients will call `resolve` with the DNS-encoded name to resolve and the encoded calldata for a resolver function (as specified in EIP-137 and elsewhere); the function MUST either return valid return data for that function, or revert if it is not supported. - -EIP-2544-compliant ENS clients MUST perform the following procedure when determining the resolver for a given name: - -1. Set `currentname = name` -2. Set `resolver = ens.resolver(namehash(currentname))` -3. If `resolver` is not the zero address, halt and return `resolver`. -4. If `name` is the empty name ('' or '.'), halt and return null. -5. Otherwise, set `currentname = parent(currentname)` and go to 2. - -If the procedure above returns null, name resolution MUST terminate unsuccessfully. Otherwise, EIP-2544-compliant ENS clients MUST perform the following procedure when resolving a record: - -1. Set `calldata` to the ABI-encoded call data for the resolution function required - for example, the ABI encoding of `addr(namehash(name))` when resolving the `addr` record. -2. Set `supports2544 = resolver.supportsInterface(0xTBD)`. -3. If `supports2544` is true, set `result = resolver.resolve(dnsencode(name), calldata)` -4. Otherwise, set `result` to the result of calling `resolver` with `calldata`. -5. Return `result` after decoding it using the return data ABI of the corresponding resolution function (eg, for `addr()`, ABI-decode the result of `resolver.resolve()` as an `address`). - -Note that in all cases the resolution function (`addr()` etc) and the `resolve` function are supplied the original `name`, *not* the `currentname` found in the first stage of resolution. - -### Pseudocode -``` -function getResolver(name) { - for(let currentname = name; currentname !== ''; currentname = parent(currentname)) { - const node = namehash(currentname); - const resolver = ens.resolver(node); - if(resolver != '0x0000000000000000000000000000000000000000') { - return resolver; - } - } - return null; -} - -function resolve(name, func, ...args) { - const resolver = getResolver(name); - if(resolver === null) { - return null; - } - const supports2544 = resolver.supportsInterface('0xTBD'); - let result; - if(supports2544) { - const calldata = resolver[func].encodeFunctionCall(namehash(name), ...args); - result = resolver.resolve(dnsencode(name), calldata); - return resolver[func].decodeReturnData(result); - } else { - return resolver[func](...args); - } -} -``` - -## Rationale - -The proposed implementation supports wildcard resolution in a manner that minimizes the impact to existing systems. It also reuses existing algorithms and procedures to the greatest possible extent, thereby easing the burden placed on authors and maintainers of various ENS clients. - -It also recognizes an existing consensus concerning the desirability of wildcard resolution for ENS, enabling more widespread adoption of the original specification by solving for a key scalability obstacle. - -While introducing an optional `resolve` function for resolvers, taking the unhashed name and calldata for a resolution function increases implementation complexity, it provides a means for resolvers to obtain plaintext labels and act accordingly, which enables many wildcard-related use-cases that would otherwise not be possible - for example, a wildcard resolver could resolve `id.nifty.eth` to the owner of the NFT with id `id` in some collection. With only namehashes to work with, this is not possible. Resolvers with simpler requirements can continue to simply implement resolution functions directly and omit support for the `resolve` function entirely. - -The DNS wire format is used for encoding names as it permits quick and gas-efficient hashing of names, as well as other common operations such as fetching or removing individual labels; in contrast, dot-separated names require iterating over every character in the name to find the delimiter. - -## Backwards Compatibility - -Existing ENS clients that are compliant with EIP-137 will fail to resolve wildcard records and refuse to interact with them, while those compliant with EIP-2544 will continue to correctly resolve, or reject, existing ENS records. Resolvers wishing to implement the new `resolve` function for non-wildcard use-cases (eg, where the resolver is set directly on the name being resolved) should consider what to return to legacy clients that call the individual resolution functions for maximum compatibility. - -## Security Considerations - -While compliant ENS clients will continue to refuse to resolve records without a resolver, there is still the risk that an improperly-configured client will refer to an incorrect resolver, or will not reject interactions with the null address when a resolver cannot be located. - -Additionally, resolvers supporting completely arbitrary wildcard subdomain resolution will increase the likelihood of funds being sent to unintended recipients as a result of typos. Applications that implement such resolvers should consider making additional name validation available to clients depending on the context, or implementing features that support recoverability of funds. - -There is also the possibility that some applications might require that no resolver be set for certain subdomains. For this to be problematic, the parent domain would need to successfully resolve the given subdomain node — to the knowledge of the authors, no application currently supports this feature or expects that subdomains should not resolve to a record. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2544.md diff --git a/EIPS/eip-2569.md b/EIPS/eip-2569.md index 8ed6b119c29551..280c82a66eeaa4 100644 --- a/EIPS/eip-2569.md +++ b/EIPS/eip-2569.md @@ -1,353 +1,7 @@ --- eip: 2569 -title: Saving and Displaying Image Onchain for Universal Tokens -description: A set of interfaces to save an SVG image in Ethereum, and to retrieve the image file from Ethereum for universal tokens. -author: Hua Zhang (@dgczhh), Yuefei Tan (@whtyfhas), Derek Zhou (@zhous), Ran Xing (@lemontreeran) -discussions-to: https://ethereum-magicians.org/t/erc-2569-saving-and-displaying-image-onchain-for-universal-tokens/4167 -status: Stagnant -type: Standards Track category: ERC -created: 2020-03-28 +status: Moved --- -## Abstract -This set of interfaces allow a smart contract to save an SVG image in Ethereum and to retrieve an SVG image from Ethereum for fungible tokens, non-fungible tokens and tokens based on standards that will be developed in the future. - -The interface set has two interfaces: one to save an SVG file in Ethereum and the other to retrieve an SVG file from Ethereum. - -Typical applications include but not limited to: -* A solution for storage of a fungible token's icon. -* A solution for storage of a non-fungible token's icon. -* A solution for storage of the icon/logo of a DAO's reputation token. - -## Motivation -The ERC-721 token standard is a popular standard to define a non-fungible token in Ethereum. This standard is widely used to specify a crypto gift, crypto medal, crypto collectible etc. The most famous use case is the [cryptokitty](https://www.cryptokitties.co/). - -In most of these applications an image is attached to an ERC-721 token. For example, in the cryptokitty case each kitty has a unique image. While the token's code is saved in Ethereum permanently, the image attached to the token is not. - -The existing solutions still keep such an image in a centralized server instead of Ethereum. When these applications display an image for a token they retrieve the token's information from Ethereum and search the centralized server for the token's associated image by using the token's information. - -Although this is an applicable way to display an image for a token, the image is still vulnerable to risks of being damaged or lost when saved in a centralized server. - -Hence we propose a set of interfaces to save an image for a universal token in Ethereum to keep the image permanent and tamper-resistant, and to retrieve an image for a universal token from Ethereum. - -## Specification - -An EIP-2569 compatible contract MUST have a method with the signature getTokenImageSvg(uint256) view returns (string memory) and a method with the signature setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal. - -These methods define how a smart contract saves an image for a universal token in Ethereum which keeps the image permanent and tamper-resistant, and how a smart contract retrieves an image from Ethereum for a universal token. - -By calling the methods users should access an SVG image. - -* getTokenImageSvg(uint256 tokenId) external view returns (string memory): for an ERC-721 or ERC-1155 token or a token implemented by a contract which has a member "ID" to specify its token type or token index we define an interface to get an SVG image by using the token's ID number. For an ERC-20 token or a token implemented by a contract which doesn't have a member "ID" to specify its token type or token index we define an interface to get an SVG image for it if the token has a member variable string to save the image. - -It has the following parameter: - -tokenId: for a non-fungible token such as an ERC-721 token or a multi-token such as an ERC-1155 token which has a member "ID" to specify its token type or token index our proposed interface assigns an SVG image's file content to a string variable of the token's contract and associates the SVG image to this "ID" number. This unique ID is used to access its SVG image in both a "set" operation and a "get" operation. -For a fungible token such as an ERC-20 token no such an ID is needed and our proposed interface just assigns an SVG image's file content to a string variable of the token's contract. - -* setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal: for an ERC-721 or ERC-1155 token or a token implemented by a contract which has a member "ID" to specify its token type or token index we define an interface to associate an SVG image to the token's ID number. For an ERC-20 token or a token implemented by a contract which doesn't have a member "ID" to specify its token type or token index we define an interface to assign an SVG image to a member variable string of this token's contract. - -It has the following two parameters: - -tokenId: for a non-fungible token such as an ERC-721 token or a multi-token such as an ERC-1155 token which has a member "ID" to specify its token type or token index our proposed interface assigns an SVG image's file content to a string variable of the token's contract and associates the SVG image to this "ID" number. This unique ID is used to access its SVG image in both a "set" operation and a "get" operation. -For a fungible token such as an ERC-20 token no such an ID is needed and our proposed interface just assigns an SVG image's file content to a string variable of the token's contract. - -imageSvg: we use a string variable to save an SVG image file's content. -An SVG image that will be saved in the imageSvg string should include at least two attributes:"name", "desc"(description). - -The procedure to save an image for a token in Ethereum is as follows: - -**Step1:** define a string variable or an array of strings to hold an image or an array of images. - -**Step 2:** define a function to set an (SVG) image's file content or an array of image file's contents to the string variable or the array of strings. - -Step 1: for a token such as an ERC-721 or ERC-1155 token which has a member variable "ID" to specify a token type or index and a member variable string to keep an (SVG) image associated with the "ID", retrieve the (SVG) image from Ethereum by calling our proposed "get" interface with the token's ID; -for a token which doesn't have a member variable "ID" to specify a token type of index but has a member variable string to keep an (SVG) image, retrieve the (SVG) image from Ethereum by calling our proposed "get" without an "ID". - -## Rationale -After Bitcoin was created people have found ways to keep information permanent and tamper-resistant by encoding text messages they want to preserve permanently and tamper-resistantly in blockchain transactions. However existing applications only do this for text information and there are no solutions to keep an image permanent and tamper-resistant. - -One of the most significant reasons for not doing so is that in general the size of an image is much bigger than the size of a text file, thus the gas needed to save an image in Ethereum would exceed a block's gas limit. - -However this changed a lot after the SVG(Scalable Vector Graphics) specification was developed by W3C since 1999. - -The SVG specification offers several advantages (for more details about the advantages please refer to a reference link:https://en.wikipedia.org/wiki/Scalable_Vector_Graphics) over raster images. One of these advantages is its compact file-size. - -"Compact file-size – Pixel-based images are saved at a large size from the start because you can only retain the quality when you make the image smaller, but not when you make it larger. This can impact a site’s download speed. Since SVGs are scalable, they can be saved at a minimal file size". - -This feature well fixes the painpoint of saving an image file in Ethereum, therefore we think saving an SVG image in Ethereum is a good solution for keep the image permanent and tamper-resistant. - -In most ERC-721 related DAPPs they display an image for a non-fungible token. In most ERC-20 related DAPPs they don't have an image for a fungible token. We think displaying an image for a token either based on existing token standards such as ERC-20, ERC-721, ERC-1155 or based on future standards is needed in many use cases. Therefore those DAPPs which currently don't display an image for a token will eventually need such a function. - -However with regard to most of the existing DAPPs which can display an image for a token they save such an image in a centralized server which, we think, is just a compromised solution. By utilizing the SVG specification we think converting a token's image to an SVG image and saving it in Ethereum provides a better solution for DAPPs to access an image for a token. - -This solution not only works for tokens based on ERC-721, ERC-1155 and ERC-20 but will work for tokens based on future standards. - -## Backwards Compatibility -There are no backward compatibility issues. - -## Reference Implementation -`tokenId`: a token index in an ERC-721 token or a token type/index in an ERC-1155 token. It is a uint256 variable. - -`imageSvg`: an SVG image's file content. It is a string variable. Note: the SVG image should include at least three attributes:"name", "description" and "issuer". - -`setTokenImageSvg`: interface to set an SVG image to a token with or without an ID number. - -`getTokenImageSvg`: interface to get an SVG image for a token with or without an ID number. - -We propose to add three sol files in the existing ERC-721 implementation. -Here are the details for the proposed sol files. - -```solidity -// ----- IERC721GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; - -/** - * @title ERC-721 Non-Fungible Token Standard, optional retrieving SVG image extension - * @dev See https://eips.ethereum.org/EIPS/eip-721 - */ -contract IERC721GetImageSvg is IERC721 { - function getTokenImageSvg(uint256 tokenId) external view returns (string memory); -} - - -// ----- ERC721GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/GSN/Context.sol"; -import "@openzeppelin/contracts/token/ERC721/./ERC721.sol"; -import "@openzeppelin/contracts/introspection/ERC165.sol"; -import "./IERC721GetImageSvg.sol"; - -contract ERC721GetImageSvg is Context, ERC165, ERC721, IERC721GetImageSvg { - // Mapping for token Images - mapping(uint256 => string) private _tokenImageSvgs; - - /* - * bytes4(keccak256('getTokenImageSvg(uint256)')) == 0x87d2f48c - * - * => 0x87d2f48c == 0x87d2f48c - */ - bytes4 private constant _INTERFACE_ID_ERC721_GET_TOKEN_IMAGE_SVG = 0x87d2f48c; - - /** - * @dev Constructor function - */ - constructor () public { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(_INTERFACE_ID_ERC721_GET_TOKEN_IMAGE_SVG); - } - - /** - * @dev Returns an SVG Image for a given token ID. - * Throws if the token ID does not exist. May return an empty string. - * @param tokenId uint256 ID of the token to query - */ - function getTokenImageSvg(uint256 tokenId) external view returns (string memory) { - require(_exists(tokenId), "ERC721GetImageSvg: SVG Image query for nonexistent token"); - return _tokenImageSvgs[tokenId]; - } - - /** - * @dev Internal function to set the token SVG image for a given token. - * Reverts if the token ID does not exist. - * @param tokenId uint256 ID of the token to set its SVG image - * @param imagesvg string SVG to assign - */ - function setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal { - require(_exists(tokenId), "ERC721GetImageSvg: SVG image set of nonexistent token"); - _tokenImageSvgs[tokenId] = imagesvg; - } - -} - - -// ----- ERC721ImageSvgMintable.sol ------------------------- - -pragma solidity ^0.5.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721Metadata.sol"; -import "@openzeppelin/contracts/access/roles/MinterRole.sol"; -import "./ERC721GetImageSvg.sol"; - -/** - * @title ERC721ImageSvgMintable - * @dev ERC721 minting logic with imagesvg. - */ -contract ERC721ImageSvgMintable is ERC721, ERC721Metadata, ERC721GetImageSvg, MinterRole { - /** - * @dev Function to mint tokens. - * @param to The address that will receive the minted tokens. - * @param tokenId The token id to mint. - * @param tokenImageSvg The token SVG image of the minted token. - * @return A boolean that indicates if the operation was successful. - */ - function mintWithTokenImageSvg(address to, uint256 tokenId, string memory tokenImageSvg) public onlyMinter returns (bool) { - _mint(to, tokenId); - setTokenImageSvg(tokenId, tokenImageSvg); - return true; - } -} - - -We propose to add three sol files in the existing ERC-1155 implementation. -Here are the details for the proposed sol files. - -// ----- IERC1155GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./IERC1155.sol"; - -/** - * @title ERC-1155 Multi Token Standard, retrieving SVG image for a token - * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md - */ -contract IERC1155GetImageSvg is IERC1155 { - function getTokenImageSvg(uint256 tokenId) external view returns (string memory); -} - - -// ----- ERC1155GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./ERC1155.sol"; -import "./IERC1155GetImageSvg.sol"; - -contract ERC1155GetImageSvg is ERC165, ERC1155, IERC1155GetImageSvg { - // Mapping for token Images - mapping(uint256 => string) private _tokenImageSvgs; - - /* - * bytes4(keccak256('getTokenImageSvg(uint256)')) == 0x87d2f48c - * - * => 0x87d2f48c == 0x87d2f48c - */ - bytes4 private constant _INTERFACE_ID_ERC1155_GET_TOKEN_IMAGE_SVG = 0x87d2f48c; - - /** - * @dev Constructor function - */ - constructor () public { - // register the supported interfaces to conform to ERC1155 via ERC165 - _registerInterface(_INTERFACE_ID_ERC1155_GET_TOKEN_IMAGE_SVG); - } - - - /** - * @dev Returns an SVG Image for a given token ID. - * Throws if the token ID does not exist. May return an empty string. - * @param tokenId uint256 ID of the token to query - */ - function getTokenImageSvg(uint256 tokenId) external view returns (string memory) { - require(_exists(tokenId), "ERC1155GetImageSvg: SVG Image query for nonexistent token"); - return _tokenImageSvgs[tokenId]; - } - - /** - * @dev Internal function to set the token SVG image for a given token. - * Reverts if the token ID does not exist. - * @param tokenId uint256 ID of the token to set its SVG image - * @param imagesvg string SVG to assign - */ - function setTokenImageSvg(uint256 tokenId, string memory imagesvg) internal { - require(_exists(tokenId), "ERC1155GetImageSvg: SVG image set of nonexistent token"); - _tokenImageSvgs[tokenId] = imagesvg; - } - -} - - - -// ----- ERC1155MixedFungibleWithSvgMintable.sol ------------------------- - -pragma solidity ^0.5.0; - -import "./ERC1155MixedFungibleMintable.sol"; -import "./ERC1155GetImageSvg.sol"; - -/** - @dev Mintable form of ERC1155 with SVG images - Shows how easy it is to mint new items with SVG images -*/ - -contract ERC1155MixedFungibleWithSvgMintable is ERC1155, ERC1155MixedFungibleMintable, ERC1155GetImageSvg { - /** - * @dev Function to mint non-fungible tokens. - * @param _to The address that will receive the minted tokens. - * @param _type The token type to mint. - * @param tokenImageSvg The token SVG image of the minted token. - */ - function mintNonFungibleWithImageSvg(uint256 _type, address[] calldata _to, string memory tokenImageSvg) external creatorOnly(_type) { - mintNonFungible(_type, _to); - setTokenImageSvg(_type, tokenImageSvg); - } - - - /** - * @dev Function to mint fungible tokens. - * @param _to The address that will receive the minted tokens. - * @param _id The token type to mint. - * @param _quantities The number of tokens for a type to mint. - * @param tokenImageSvg The token SVG image of the minted token. - */ - function mintFungibleWithImageSvg(uint256 _id, address[] calldata _to, uint256[] calldata _quantities, string memory tokenImageSvg) external creatorOnly(_id) { - mintFungible(_id, _to, _quantities, tokenImageSvg) { - setTokenImageSvg(_id, tokenImageSvg); - } -} - - - -We propose to add three sol files in the existing ERC-20 implementation. -Here are the details for the proposed sol files. - - -// ----- IERC20GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; - -/** - * @title ERC-20 Fungible Token Standard, retrieving SVG image for a token - * @dev See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol - */ -contract IERC20GetImageSvg is IERC20 { - function getTokenImageSvg() external view returns (string memory); -} - - -// ----- ERC20GetImageSvg.sol ------------------------- - -pragma solidity ^0.5.0; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; -import "./IERC20GetImageSvg.sol"; - -contract ERC20GetImageSvg is ERC20, IERC20GetImageSvg { - string private _tokenImageSvg; -//将图片实现写在构造器中 - constructor(string calldata svgCode) public { -_tokenImageSvg = svgCode -} - - /** - * @dev Returns an SVG Image. - */ - function getTokenImageSvg() external view returns (string memory) { - return _tokenImageSvg; - } - -} - - -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2569.md diff --git a/EIPS/eip-2612.md b/EIPS/eip-2612.md index eecb1f7dfc77b0..416c494fd2824e 100644 --- a/EIPS/eip-2612.md +++ b/EIPS/eip-2612.md @@ -1,188 +1,7 @@ --- eip: 2612 -title: Permit Extension for EIP-20 Signed Approvals -description: EIP-20 approvals via EIP-712 secp256k1 signatures -author: Martin Lundfall (@Mrchico) -discussions-to: https://github.com/ethereum/EIPs/issues/2613 -status: Final -type: Standards Track category: ERC -created: 2020-04-13 -requires: 20, 712 +status: Moved --- -## Abstract -Arguably one of the main reasons for the success of [EIP-20](./eip-20.md) tokens lies in the interplay between `approve` and `transferFrom`, which allows for tokens to not only be transferred between externally owned accounts (EOA), but to be used in other contracts under application specific conditions by abstracting away `msg.sender` as the defining mechanism for token access control. - -However, a limiting factor in this design stems from the fact that the EIP-20 `approve` function itself is defined in terms of `msg.sender`. This means that user's _initial action_ involving EIP-20 tokens must be performed by an EOA (_but see Note below_). If the user needs to interact with a smart contract, then they need to make 2 transactions (`approve` and the smart contract call which will internally call `transferFrom`). Even in the simple use case of paying another person, they need to hold ETH to pay for transaction gas costs. - -This ERC extends the EIP-20 standard with a new function `permit`, which allows users to modify the `allowance` mapping using a signed message, instead of through `msg.sender`. - -For an improved user experience, the signed data is structured following [EIP-712](./eip-712.md), which already has wide spread adoption in major RPC providers. - -**_Note:_** EIP-20 must be performed by an EOA unless the address owning the token is actually a contract wallet. Although contract wallets solves many of the same problems that motivates this EIP, they are currently only scarcely adopted in the ecosystem. Contract wallets suffer from a UX problem -- since they separate the EOA `owner` of the contract wallet from the contract wallet itself (which is meant to carry out actions on the `owner`s behalf and holds all of their funds), user interfaces need to be specifically designed to support them. The `permit` pattern reaps many of the same benefits while requiring little to no change in user interfaces. - -## Motivation -While EIP-20 tokens have become ubiquitous in the Ethereum ecosystem, their status remains that of second class tokens from the perspective of the protocol. The ability for users to interact with Ethereum without holding any ETH has been a long outstanding goal and the subject of many EIPs. - -So far, many of these proposals have seen very little adoption, and the ones that have been adopted (such as [EIP-777](./eip-777.md)), introduce a lot of additional functionality, causing unexpected behavior in mainstream contracts. - -This ERC proposes an alternative solution which is designed to be as minimal as possible and to only address _one problem_: the lack of abstraction in the EIP-20 `approve` method. - -While it may be tempting to introduce `*_by_signature` counterparts for every EIP-20 function, they are intentionally left out of this EIP-20 for two reasons: - - - the desired specifics of such functions, such as decision regarding fees for `transfer_by_signature`, possible batching algorithms, varies depending on the use case, and, - - they can be implemented using a combination of `permit` and additional helper contracts without loss of generality. - -## Specification -Compliant contracts must implement 3 new functions in addition to EIP-20: -```sol -function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external -function nonces(address owner) external view returns (uint) -function DOMAIN_SEPARATOR() external view returns (bytes32) -``` -The semantics of which are as follows: - -For all addresses `owner`, `spender`, uint256s `value`, `deadline` and `nonce`, uint8 `v`, bytes32 `r` and `s`, -a call to `permit(owner, spender, value, deadline, v, r, s)` will set -`approval[owner][spender]` to `value`, -increment `nonces[owner]` by 1, -and emit a corresponding `Approval` event, -if and only if the following conditions are met: - - -- The current blocktime is less than or equal to `deadline`. -- `owner` is not the zero address. -- `nonces[owner]` (before the state update) is equal to `nonce`. -- `r`, `s` and `v` is a valid `secp256k1` signature from `owner` of the message: - -If any of these conditions are not met, the `permit` call must revert. - -```sol -keccak256(abi.encodePacked( - hex"1901", - DOMAIN_SEPARATOR, - keccak256(abi.encode( - keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"), - owner, - spender, - value, - nonce, - deadline)) -)) -``` -where `DOMAIN_SEPARATOR` is defined according to EIP-712. The `DOMAIN_SEPARATOR` should be unique to the contract and chain to prevent replay attacks from other domains, -and satisfy the requirements of EIP-712, but is otherwise unconstrained. -A common choice for `DOMAIN_SEPARATOR` is: -```solidity -DOMAIN_SEPARATOR = keccak256( - abi.encode( - keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), - keccak256(bytes(name)), - keccak256(bytes(version)), - chainid, - address(this) -)); -``` - -In other words, the message is the EIP-712 typed structure: - -```js -{ - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Permit": [{ - "name": "owner", - "type": "address" - }, - { - "name": "spender", - "type": "address" - }, - { - "name": "value", - "type": "uint256" - }, - { - "name": "nonce", - "type": "uint256" - }, - { - "name": "deadline", - "type": "uint256" - } - ], - "primaryType": "Permit", - "domain": { - "name": erc20name, - "version": version, - "chainId": chainid, - "verifyingContract": tokenAddress - }, - "message": { - "owner": owner, - "spender": spender, - "value": value, - "nonce": nonce, - "deadline": deadline - } -}} -``` - -Note that nowhere in this definition we refer to `msg.sender`. The caller of the `permit` function can be any address. - - -## Rationale -The `permit` function is sufficient for enabling any operation involving EIP-20 tokens to be paid for using the token itself, rather than using ETH. - -The `nonces` mapping is given for replay protection. - -A common use case of `permit` has a relayer submit a `Permit` on behalf of the `owner`. In this scenario, the relaying party is essentially given a free option to submit or withhold the `Permit`. If this is a cause of concern, the `owner` can limit the time a `Permit` is valid for by setting `deadline` to a value in the near future. The `deadline` argument can be set to `uint(-1)` to create `Permit`s that effectively never expire. - -EIP-712 typed messages are included because of its wide spread adoption in many wallet providers. - - -## Backwards Compatibility -There are already a couple of `permit` functions in token contracts implemented in contracts in the wild, most notably the one introduced in the `dai.sol`. - -Its implementation differs slightly from the presentation here in that: -- instead of taking a `value` argument, it takes a bool `allowed`, setting approval to 0 or `uint(-1)`. -- the `deadline` argument is instead called `expiry`. This is not just a syntactic change, as it effects the contents of the signed message. - -There is also an implementation in the token `Stake` (Ethereum address `0x0Ae055097C6d159879521C384F1D2123D1f195e6`) with the same ABI as `dai` but with different semantics: it lets users issue "expiring approvals", that only allow `transferFrom` to occur while `expiry >= block.timestamp`. - -The specification presented here is in line with the implementation in Uniswap V2. - -The requirement to revert if the permit is invalid was added when the EIP was already widely deployed, but at the moment it was consistent with all found implementations. - -## Security Considerations - -Though the signer of a `Permit` may have a certain party in mind to submit their transaction, another party can always front run this transaction and call `permit` before the intended party. The end result is the same for the `Permit` signer, however. - -Since the ecrecover precompile fails silently and just returns the zero address as `signer` when given malformed messages, it is important to ensure `owner != address(0)` to avoid `permit` from creating an approval to spend "zombie funds" belong to the zero address. - -Signed `Permit` messages are censorable. The relaying party can always choose to not submit the `Permit` after having received it, withholding the option to submit it. The `deadline` parameter is one mitigation to this. If the signing party holds ETH they can also just submit the `Permit` themselves, which can render previously signed `Permit`s invalid. - -The standard EIP-20 race condition for approvals (SWC-114) applies to `permit` as well. - -If the `DOMAIN_SEPARATOR` contains the `chainId` and is defined at contract deployment instead of reconstructed for every signature, there is a risk of possible replay attacks between chains in the event of a future chain split. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2612.md diff --git a/EIPS/eip-2615.md b/EIPS/eip-2615.md index 9191c801c64bc3..34ed14f5f0a143 100644 --- a/EIPS/eip-2615.md +++ b/EIPS/eip-2615.md @@ -1,241 +1,7 @@ --- eip: 2615 -title: Non-Fungible Token with mortgage and rental functions -author: Kohshi Shiba -discussions-to: https://github.com/ethereum/EIPs/issues/2616 -status: Stagnant -type: Standards Track category: ERC -created: 2020-04-25 -requires: 165, 721 +status: Moved --- -## Simple Summary - -This standard proposes an extension to ERC721 Non-Fungible Tokens (NFTs) to support rental and mortgage functions. These functions are necessary for NFTs to emulate real property, just like those in the real world. - -## Abstract - -This standard is an extension of ERC721. It proposes additional roles, the right of tenants to enable rentals, and the right of lien. - -With ERC2615, NFT owners will be able to rent out their NFTs and take out a mortgage by collateralizing their NFTs. For example, this standard can apply to: - -- Virtual items (in-game assets, virtual artwork, etc.) -- Physical items (houses, automobiles, etc.) -- Intellectual property rights -- DAO membership tokens - -NFT developers are also able to easily integrate ERC2615 since it is fully backwards-compatible with the ERC721 standard. - -One notable point is that the person who has the right to use an application is not the owner but the user (i.e. tenant). Application developers must implement this specification into their applications. - -## Motivation - -It has been challenging to implement rental and mortgage functions with the ERC721 standard because it only has one role defined (which is the Owner). - -Currently, a security deposit is needed for trustless renting with ERC721, and ownership lockup within a contract is necessary whenever one chooses to mortgage their ERC721 property. The tracking and facilitation of these relationships must be done separately from the ERC721 standard. - -This proposal eliminates these requirements by integrating basic rights of tenantship and liens. By standardizing these functions, developers can more easily integrate rental and mortgage functions for their applications. - -## Specification - -This standard proposes three user roles: the **Lien Holder**, the **Owner**, and the **User**. Their rights are as follows: - -- A **Lien Holder** has the right to: - - 1. Transfer the **Owner** role - 2. Transfer the **User** role - -- An **Owner** has the right to: - - 1. Transfer the **Owner** role - 2. Transfer the **User** role - -- A **User** has the right to: - 1. Transfer the **User** role - -### ERC-2615 Interface - -```solidity -event TransferUser(address indexed from, address indexed to, uint256 indexed itemId, address operator); -event ApprovalForUser(address indexed user, address indexed approved, uint256 itemId); -event TransferOwner(address indexed from, address indexed to, uint256 indexed itemId, address operator); -event ApprovalForOwner(address indexed owner, address indexed approved, uint256 itemId); -event ApprovalForAll(address indexed owner, address indexed operator, bool approved); -event LienApproval(address indexed to, uint256 indexed itemId); -event TenantRightApproval(address indexed to, uint256 indexed itemId); -event LienSet(address indexed to, uint256 indexed itemId, bool status); -event TenantRightSet(address indexed to, uint256 indexed itemId,bool status); - -function balanceOfOwner(address owner) public view returns (uint256); -function balanceOfUser(address user) public view returns (uint256); -function userOf(uint256 itemId) public view returns (address); -function ownerOf(uint256 itemId) public view returns (address); - -function safeTransferOwner(address from, address to, uint256 itemId) public; -function safeTransferOwner(address from, address to, uint256 itemId, bytes memory data) public; -function safeTransferUser(address from, address to, uint256 itemId) public; -function safeTransferUser(address from, address to, uint256 itemId, bytes memory data) public; - -function approveForOwner(address to, uint256 itemId) public; -function getApprovedForOwner(uint256 itemId) public view returns (address); -function approveForUser(address to, uint256 itemId) public; -function getApprovedForUser(uint256 itemId) public view returns (address); -function setApprovalForAll(address operator, bool approved) public; -function isApprovedForAll(address requester, address operator) public view returns (bool); - -function approveLien(address to, uint256 itemId) public; -function getApprovedLien(uint256 itemId) public view returns (address); -function setLien(uint256 itemId) public; -function getCurrentLien(uint256 itemId) public view returns (address); -function revokeLien(uint256 itemId) public; - -function approveTenantRight(address to, uint256 itemId) public; -function getApprovedTenantRight(uint256 itemId) public view returns (address); -function setTenantRight(uint256 itemId) public; -function getCurrentTenantRight(uint256 itemId) public view returns (address); -function revokeTenantRight(uint256 itemId) public; -``` - -### ERC-2615 Receiver - -```solidity -function onERCXReceived(address operator, address from, uint256 itemId, uint256 layer, bytes memory data) public returns(bytes4); -``` - -### ERC-2615 Extensions - -Extensions here are provided to help developers build with this standard. - -#### 1. ERC721 Compatible functions - -This extension makes this standard compatible with ERC721. By adding the following functions, developers can take advantage of the existing tools for ERC721. - -Transfer functions in this extension will transfer both the **Owner** and **User** roles when the tenant right has not been set. Conversely, when the tenant right has been set, only the **Owner** role will be transferred. - -```solidity -function balanceOf(address owner) public view returns (uint256) -function ownerOf(uint256 itemId) public view returns (address) -function approve(address to, uint256 itemId) public -function getApproved(uint256 itemId) public view returns (address) -function transferFrom(address from, address to, uint256 itemId) public -function safeTransferFrom(address from, address to, uint256 itemId) public -function safeTransferFrom(address from, address to, uint256 itemId, bytes memory data) pubic -``` - -#### 2. Enumerable - -This extension is analogous to the enumerable extension of the ERC721 standard. - -```solidity -function totalNumberOfItems() public view returns (uint256); -function itemOfOwnerByIndex(address owner, uint256 index, uint256 layer)public view returns (uint256 itemId); -function itemByIndex(uint256 index) public view returns (uint256); -``` - -#### 3. Metadata - -This extension is analogous to the metadata extension of the ERC721 standard. - -```solidity -function itemURI(uint256 itemId) public view returns (string memory); -function name() external view returns (string memory); -function symbol() external view returns (string memory); -``` - -## How rentals and mortgages work - -This standard does not deal with token or value transfer. Other logic (outside the scope of this standard) must be used to orchestrate these transfers and to implement validation of payment. - -### Mortgage functions - -The following diagram demonstrates the mortgaging functionality. - -![concept image](../assets/eip-2615/mortgage-sequential.jpg "mortgage") - -Suppose Alice owns an NFT and wants to take out a mortgage, and Bob wants to earn interest by lending tokens to Alice. - -1. Alice approves the setting of a lien for the NFT Alice owns. -2. Alice sends a loan request to the mortgage contract. -3. Bob fills the loan request and transfers tokens to the mortgage contract. The lien is then set on the NFT by the mortgage contract. -4. Alice can now withdraw the borrowed tokens from the mortgage contract. -5. Alice registers repayment (anyone can pay the repayment). -6. Bob can finish the agreement if the agreement period ends and the agreement is kept (i.e. repayment is paid without delay). -7. Bob can revoke the agreement if the agreement is breached (e.g. repayment is not paid on time) and execute the lien and take over the ownership of the NFT. - -### Rental functions - -The following diagram demonstrates the rental functionality. - -![concept image](../assets/eip-2615/rental-sequential.jpg "rental") - -Suppose Alice owns NFTs and wants to rent out a NFT, and Bob wants to lease a NFT. - -1. Alice approves the setting of a tenant-right for the NFT Alice owns. -2. Alice sends a rental listing to the rental contract. -3. Bob fills the rental request, and the right to use the NFT is transferred to Bob. At the same time, the tenant-right is set, and Alice becomes not able to transfer the right to use the NFT. -4. Bob registers rent (anyone can pay the rent). -5. Alice can withdraw the rent from the rental contract. -6. Alice can finish the agreement if the agreement period has ended and the agreement is kept (i.e. rent is paid without delay). -7. Alice can revoke the agreement if the agreement is breached (e.g. rent is not paid on time) and revoke the tenant-right and take over the right to use the NFT. - -## Rationale - -There have been some attempts to achieve rentals or mortgages with ERC721. However, as I noted before, it has been challenging to achieve. I will explain the reasons and advantages of this standard below. - -### No security lockup for rentals - -To achieve trustless rental of NFTs with ERC721, it has been necessary to deposit funds as security. This is required to prevent malicious activity from tenants, as it is impossible to take back ownership once it is transferred. - -With this standard, security deposits are no longer needed since the standard natively supports rental and tenantship functions. - -### No ownership escrow when taking out a mortgage - -In order to take out a mortgage on NFTs, it has been necessary to transfer the NFTs to a contract as collateral. This is required to prevent the potential default risk of the mortgage. - -However, secured collateral with ERC721 hurts the utility of the NFT. Since most NFT applications provide services to the canonical owner of a NFT, the NFT essentially cannot be utilized under escrow. - -With ERC2615, it is possible to collateralize NFTs and use them at the same time. - -### Easy integration - -Because of the above reasons, a great deal of effort is required to implement rental and mortgage functions with ERC721. Adopting this standard is a much easier way to integrate rental and mortgage functionality. - -### No money/token transactions within tokens - -A NFT itself does not handle lending or rental functions directly. This standard is open-source, and there is no platform lockup. Developers can integrate it without having to worry about those risks. - -## Backward compatibility - -As mentioned in the specifications section, this standard can be fully ERC721 compatible by adding an extension function set. - -In addition, new functions introduced in this standard have many similarities with the existing functions in ERC721. This allows developers to easily adopt the standard quickly. - -## Test Cases - -When running the tests, you need to create a test network with Ganache-CLI: - -``` -ganache-cli -a 15 --gasLimit=0x1fffffffffffff -e 1000000000 -``` - -And then run the tests using Truffle: - -``` -truffle test -e development -``` - -Powered by Truffle and Openzeppelin test helper. - -## Implementation - -[Github Reposotory](https://github.com/kohshiba/ERC-X). - -## Security Considerations - -Since the external contract will control lien or tenant rights, flaws within the external contract directly lead to the standard's unexpected behavior. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2615.md diff --git a/EIPS/eip-2645.md b/EIPS/eip-2645.md index 9cba91992bc1c2..f3cfeef686499d 100644 --- a/EIPS/eip-2645.md +++ b/EIPS/eip-2645.md @@ -1,71 +1,7 @@ --- eip: 2645 -title: Hierarchical Deterministic Wallet for Layer-2 -author: Tom Brand , Louis Guthmann -discussions-to: https://ethereum-magicians.org/t/hierarchical-deterministic-wallet-for-computation-integrity-proof-cip-layer-2/4286 -status: Stagnant -type: Standards Track category: ERC -created: 2020-05-13 +status: Moved --- -## Simple Summary -In the context of Computation Integrity Proof (CIP) Layer-2 solutions such as ZK-Rollups, users are required to sign messages on new elliptic curves optimized for those environnements. We leverage existing work on Key Derivation ([BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) to define an efficient way to securely produce CIP L2s private keys, as well as creating domain separation between Layer-2 applications. - -## Abstract -We provide a Derivation Path allowing a user to derive hierarchical keys for Layer-2 solutions depending on the zk-technology, the application, the user’s Layer-1 address, as well as an efficient grinding method to enforce the private key distribution within the curve domain. The propose Derivation Path is defined as follow -``` -m / purpose' / layer' / application' / eth_address_1' / eth_address_2' / index -``` - -## Motivation -In the context of Computation Integrity Proof (CIP) Layer-2 solutions such as ZK-Rollups, users are required to sign messages on new elliptic curves optimized for those environnements. Extensive work has been done to make it secure on Bitcoin via [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) and [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki). These protocols are the standard for wallets in the entire industry, independent of the underlying blockchain. As Layer-2 solutions are taking off, it is a necessary requirement to maintain the same standard and security in this new space. - -## Specification -Starkware keys are derived with the following [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)-compatible derivation path, with direct inspiration from [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki): -``` -m / purpose' / layer' / application' / eth_address_1' / eth_address_2' / index -``` -where: -* `m` - the seed. -* `purpose` - `2645` (the number of this EIP). -* `layer` - the 31 lowest bits of sha256 on the layer name. Serve as a domain separator between different technologies. In the context of `starkex`, the value would be `579218131`. -* `application` - the 31 lowest bits of sha256 of the application name. Serve as a domain separator between different applications. In the context of DeversiFi in June 2020, it is the 31 lowest bits of sha256(starkexdvf) and the value would be `1393043894`. -* `eth_address_1 / eth_address_2` - the first and second 31 lowest bits of the corresponding eth_address. -* `index` - to allow multiple keys per eth_address. - -As example, the expected path for address 0x0000....0000 assuming seed `m` and index 0 in the context of DeversiFi in June 2020: `m/2645'/579218131'/1393043894'/0'/0'/0` - -The key derivation should follow the following algorithm -``` -N = 2**256 -n = Layer2 curve order -path = stark derivation path -BIP32() = Official BIP-0032 derivation function on secp256k1 -hash = SHA256 -i = 0 -root_key = BIP32(path) -while True: - key = hash(root_key|i) - if (key < (N - (N % n))): - return key % n - i++ -``` -This algorithm has been defined to maintain efficiency on existing restricted devices. - -Nota Bene: At each round, the probability for a key to be greater than (N - (N % n)) is < 2^(-5). - -## Rationale -This EIP specifies two aspects of keys derivation in the context of Hierarchical Wallets: -- Derivation Path -- Grinding Algorithm to enforce a uniform distribution over the elliptic curve. -The derivation path is defined to allow efficient keys separation based on technology and application while maintaining a 1-1 relation with the Layer-1 wallet. In such a way, losing EIP-2645 wallets falls back to losing the Layer-1 wallet. - -## Backwards Compatibility -This standard complies with BIP43. - -## Security Considerations -This EIP has been defined to maintain separation of keys while providing foolproof logic on key derivation. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2645.md diff --git a/EIPS/eip-2677.md b/EIPS/eip-2677.md index e0d136ca582908..7bf2473d7766ab 100644 --- a/EIPS/eip-2677.md +++ b/EIPS/eip-2677.md @@ -3,10 +3,11 @@ eip: 2677 title: Limit size of `initcode` author: Martin Holst Swende (@holiman), Paweł Bylica (@chfast), Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/eip-2677-limit-size-of-initcode/4550 -status: Stagnant +status: Withdrawn type: Standards Track category: Core created: 2020-05-18 +withdrawal-reason: Replaced by EIP-3860. --- ## Simple Summary diff --git a/EIPS/eip-2678.md b/EIPS/eip-2678.md index 5daf0ac93a10fc..9d9d8d2c4d1b58 100644 --- a/EIPS/eip-2678.md +++ b/EIPS/eip-2678.md @@ -1,1042 +1,7 @@ --- eip: 2678 -title: Revised Ethereum Smart Contract Packaging Standard (EthPM v3) -author: g. nicholas d’andrea (@gnidan), Piper Merriam (@pipermerriam), Nick Gheorghita (@njgheorghita), Christian Reitwiessner (@chriseth), Ben Hauser (@iamdefinitelyahuman), Bryant Eisenbach (@fubuloubu) -discussions-to: https://ethereum-magicians.org/t/ethpm-v3-specification-working-group/4086 -status: Final -type: Standards Track category: ERC -created: 2020-05-26 +status: Moved --- - -## Simple Summary - -A data format describing a smart contract software package. - - -## Abstract - -This EIP defines a data format for *package manifest* documents, -representing a package of one or more smart contracts, optionally -including source code and any/all deployed instances across multiple -networks. Package manifests are minified JSON objects, to be distributed -via content addressable storage networks, such as IPFS. Packages -are then published to on-chain EthPM registries, defined in -[EIP-1319](./eip-1319.md), from where they can be freely accessed. - -This document presents a natural language description of a formal -specification for version **3** of this format. - - -## Motivation - -This standard aims to encourage the Ethereum development ecosystem -towards software best practices around code reuse. By defining an open, -community-driven package data format standard, this effort seeks to -provide support for package management tools development by offering a -general-purpose solution that has been designed with observed common -practices in mind. - -- Updates the schema for a *package manifest* to be compatible with - the [metadata](https://solidity.readthedocs.io/en/latest/metadata.html) output for compilers. -- Updates the `"sources"` object definition to support a wider range of source file types and serve as [JSON input](https://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description) for a compiler. -- Moves compiler definitions to a top-level `"compilers"` array in order to: - - Simplify the links between a compiler version, sources, and the - compiled assets. - - Simplify packages that use multiple compiler versions. -- Updates key formatting from `snake_case` to `camelCase` to be - more consistent with [JSON convention](https://google.github.io/styleguide/jsoncstyleguide.xml?showone=Property_Name_Format#Property_Name_Format). - -### Guiding Principles - -This specification makes the following assumptions about the document -lifecycle. - -1. Package manifests are intended to be generated programmatically by - package management software as part of the release process. - -2. Package manifests will be consumed by package managers during tasks - like installing package dependencies or building and deploying new - releases. - -3. Package manifests will typically **not** be stored alongside the - source, but rather by package registries *or* referenced by package - registries and stored in something akin to IPFS. - -4. Package manifests can be used to verify public deployments of source - contracts. - -### Use Cases - -The following use cases were considered during the creation of this -specification. - -* **owned**: A package which contains contracts which are not meant to be used by themselves but rather as base contracts to provide functionality to other contracts through inheritance. -* **transferable**: A package which has a single dependency. -* **standard-token**: A package which contains a reusable contract. -* **safe-math-lib**: A package which contains deployed instance of one of the package contracts. -* **piper-coin**: A package which contains a deployed instance of a reusable contract from a dependency. -* **escrow**: A package which contains a deployed instance of a local contract which is linked against a deployed instance of a local library. -* **wallet**: A package with a deployed instance of a local contract which is linked against a deployed instance of a library from a dependency. -* **wallet-with-send**: A package with a deployed instance which links against a deep dependency. -* **simple-auction**: Compiler `"metadata"` field output. - -## Package Specification - -### Conventions - -#### RFC2119 - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, -“SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this -document are to be interpreted as described in RFC 2119. - -- - - -#### Prefixed vs Unprefixed - -A [prefixed](#prefixed) hexadecimal value begins with `0x`. -[Unprefixed](#unprefixed) values have no prefix. Unless otherwise -specified, all hexadecimal values **should** be represented with the -`0x` prefix. - -* **Prefixed**: `0xdeadbeef` -* **Unprefixed**: `deadbeef` - -### Document Format - -The canonical format is a single JSON object. Packages **must** conform -to the following serialization rules. - -- The document **must** be tightly packed, meaning no linebreaks or - extra whitespace. - -- The keys in all objects **must** be sorted alphabetically. - -- Duplicate keys in the same object are invalid. - -- The document **must** use - [UTF-8](https://en.wikipedia.org/wiki/UTF-8) - encoding. - -- The document **must** not have a trailing newline. - -- To ensure backwards compatibility, `manifest_version` is a forbidden - top-level key. - - -### Document Specification - -The following fields are defined for the package. Custom fields **may** -be included. Custom fields **should** be prefixed with `x-` to prevent -name collisions with future versions of the specification. - -* **See Also**: Formalized ([JSON-Schema](https://json-schema.org)) version of this specification: [package.spec.json](../assets/eip-2678/package.spec.json) -* **Jump To**: [Definitions](#object-definitions) - -### EthPM Manifest Version - -The `manifest` field defines the specification version that this -document conforms to. - -- Packages **must** include this field. - -* **Required**: Yes -* **Key**: `manifest` -* **Type**: String -* **Allowed Values**: `ethpm/3` - -### Package Name - -The `name` field defines a human readable name for this package. - -- Packages **should** include this field to be released on an EthPM - registry. - -- Package names **must** begin with a lowercase letter and be - comprised of only the lowercase letters `a-z`, numeric characters `0-9`, and the - dash character `-`. - -- Package names **must** not exceed 255 characters in length. - -* **Required**: If `version` is included. -* **Key**: `name` -* **Type**: String -* **Format**: **must** match the regular expression `^[a-z][-a-z0-9]{0,255}$` - -### Package Version - -The `version` field declares the version number of this release. - -- Packages **should** include this field to be released on an EthPM - registry. - -- This value **should** conform to the - [semver](http://semver.org/) version numbering - specification. - -* **Required**: If `name` is included. -* **Key**: `version` -* **Type**: String - -### Package Metadata - -The `meta` field defines a location for metadata about the package which -is not integral in nature for package installation, but may be important -or convenient to have on-hand for other reasons. - -- This field **should** be included in all Packages. - -* **Required**: No -* **Key**: `meta` -* **Type**: [Package Meta Object](#the-package-meta-object) - -### Sources - -The `sources` field defines a source tree that **should** comprise the -full source tree necessary to recompile the contracts contained in this -release. - -* **Required**: No -* **Key**: `sources` -* **Type**: Object (String: [Sources Object](#the-source-object)) - -### Contract Types - -The `contractTypes` field hosts the [Contract -Types](#contract-type) which have been included in this release. - -- Packages **should** only include contract types that can be found in - the source files for this package. - -- Packages **should not** include contract types from dependencies. - -- Packages **should not** include abstract contracts in the contract - types section of a release. - -* **Required**: No -* **Key**: `contractTypes` -* **Type**: Object (String: [Contract Type Object](#the-contract-type-object)) -* **Format**: Keys **must** be valid [Contract Aliases](#contract-alias).
Values **must** conform to the [Contract Type Object](#the-contract-type-object) definition. - -### Compilers - -The `compilers` field holds the information about the compilers and -their settings that have been used to generate the various -`contractTypes` included in this release. - -* **Required**: No -* **Key**: `compilers` -* **Type**: Array ([Compiler Information Object](#the-compiler-information-object)) - -### Deployments - -The `deployments` field holds the information for the chains on which -this release has [Contract Instances](#contract-instance) as well -as the [Contract Types](#contract-type) and other deployment -details for those deployed contract instances. The set of chains defined -by the [BIP122 URI](#bip122-uri) keys for this object **must** be -unique. There cannot be two different URI keys in a deployments field -representing the same blockchain. - -* **Required**: No -* **Key**: `deployments` -* **Type**: Object (String: Object(String: [Contract Instance Object](#the-contract-instance-object))) -* **Format**: Keys **must** be a valid BIP122 URI chain definition.
Values **must** be objects which conform to the following format:
- Keys **must** be valid [Contract Instance Names](#contract-instance-name)
- Values **must** be a valid [Contract Instance Object](#the-contract-instance-object) - -### Build Dependencies - -The `buildDependencies` field defines a key/value mapping of EthPM -packages that this project depends on. - -* **Required**: No -* **Key**: `buildDependencies` -* **Type**: Object (String: String) -* **Format**: Keys **must** be valid [package names](#package-name).
Values **must** be a [Content Addressable URI](#content-addressable-uri) which resolves to a valid package that conforms the same EthPM manifest version as its parent. - -### Object Definitions - -Definitions for different objects used within the Package. All objects -allow custom fields to be included. Custom fields **should** be prefixed -with `x-` to prevent name collisions with future versions of the -specification. - - -### The *Link Reference* Object - -A [Link Reference](#link-reference) object has the following -key/value pairs. All link references are assumed to be associated with -some corresponding [Bytecode](#bytecode). - -#### Offsets: `offsets` - -The `offsets` field is an array of integers, corresponding to each of -the start positions where the link reference appears in the bytecode. -Locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. This field is invalid if it references a -position that is beyond the end of the bytecode. - -* **Required**: Yes -* **Type**: Array - -#### Length: `length` - -The `length` field is an integer which defines the length in bytes of -the link reference. This field is invalid if the end of the defined link -reference exceeds the end of the bytecode. - -* **Required**: Yes -* **Type**: Integer - -#### Name: `name` - -The `name` field is a string which **must** be a valid -[Identifier](#identifier). Any link references which **should** be -linked with the same link value **should** be given the same name. - -* **Required**: No -* **Type**: String -* **Format**: **must** conform to the [Identifier](#identifier) format. - -### The *Link Value* Object - -Describes a single [Link Value](#link-value). - -A **Link Value object** is defined to have the following key/value -pairs. - - -#### Offsets: `offsets` - -The `offsets` field defines the locations within the corresponding -bytecode where the `value` for this link value was written. These -locations are 0-indexed from the beginning of the bytes representation -of the corresponding bytecode. - -* **Required**: Yes -* **Type**: Integer -* **Format**: See below. - -Format - -Array of integers, where each integer **must** conform to all of the -following. - -- greater than or equal to zero - -- strictly less than the length of the unprefixed hexadecimal - representation of the corresponding bytecode. - -#### Type: `type` - -The `type` field defines the `value` type for determining what is -encoded when [linking](#linking) the corresponding bytecode. - -* **Required**: Yes -* **Type**: String -* **Allowed Values**: `"literal"` for bytecode literals.
`"reference"` for named references to a particular [Contract Instance](#contract-instance) - -#### Value: `value` - -The `value` field defines the value which should be written when [linking](#linking) the corresponding bytecode. - -* **Required**: Yes -* **Type**: String -* **Format**: Determined based on `type`, see below. - -Format - -For static value *literals* (e.g. address), value **must** be a 0x-prefixed -hexadecimal string representing bytes. - - -To reference the address of a [Contract -Instance](#contract-instance) from the current package the value -should be the name of that contract instance. - -- This value **must** be a valid [Contract Instance - Name](#contract-instance-name). - -- The chain definition under which the contract instance that this - link value belongs to must contain this value within its keys. - -- This value **may not** reference the same contract instance that - this link value belongs to. - -To reference a contract instance from a [Package](#package) from -somewhere within the dependency tree the value is constructed as -follows. - -- Let `[p1, p2, .. pn]` define a path down the dependency tree. - -- Each of `p1, p2, pn` **must** be valid package names. - -- `p1` **must** be present in keys of the `buildDependencies` for the - current package. - -- For every `pn` where `n > 1`, `pn` **must** be present in the keys - of the `buildDependencies` of the package for `pn-1`. - -- The value is represented by the string - `::<...>::` where all of ``, - ``, `` are valid package names and `` is - a valid [Contract Name](#contract-name). - -- The `` value **must** be a valid [Contract - Instance Name](#contract-instance-name). - -- Within the package of the dependency defined by ``, all of the - following must be satisfiable: - - - There **must** be *exactly* one chain defined under the - `deployments` key which matches the chain definition that this - link value is nested under. - - - The `` value **must** be present in the keys - of the matching chain. - -### The *Bytecode* Object - -A bytecode object has the following key/value pairs. - -#### Bytecode: `bytecode` - -The `bytecode` field is a string containing the `0x` prefixed -hexadecimal representation of the bytecode. - -* **Required**: Yes -* **Type**: String -* **Format**: `0x` prefixed hexadecimal. - -#### Link References: `linkReferences` - -The `linkReferences` field defines the locations in the corresponding -bytecode which require [linking](#linking). - -* **Required**: No -* **Type**: Array -* **Format**: All values **must** be valid [Link Reference objects](#the-link-reference-object). See also below. - -Format - -This field is considered invalid if *any* of the [Link -References](#link-reference) are invalid when applied to the -corresponding `bytecode` field, *or* if any of the link references -intersect. - -Intersection is defined as two link references which overlap. - -#### Link Dependencies: `linkDependencies` - -The `linkDependencies` defines the [Link Values](#link-value) that -have been used to link the corresponding bytecode. - -* **Required**: No -* **Type**: Array -* **Format**: All values **must** be valid [Link Value objects](#the-link-value-object). See also below. - -Format - -Validation of this field includes the following: - -- Two link value objects **must not** contain any of the same values - for `offsets`. - -- Each [link value object](#the-link-value-object) **must** have a - corresponding [link reference object](#the-link-reference-object) under - the `linkReferences` field. - -- The length of the resolved `value` **must** be equal to the `length` - of the corresponding [Link Reference](#link-reference). - - -### The *Package Meta* Object - -The *Package Meta* object is defined to have the following key/value -pairs. - -#### Authors - -The `authors` field defines a list of human readable names for the -authors of this package. Packages **may** include this field. - -* **Required**: No -* **Key**: `authors` -* **Type**: Array(String) - -#### License - -The `license` field declares the license associated with this package. -This value **should** conform to the -[SPDX](https://spdx.org/licenses/) -format. Packages **should** include this field. If a file [Source -Object](#the-source-object) defines its own license, that license takes -precedence for that particular file over this package-scoped `meta` -license. - -* **Required**: No -* **Key**: `license` -* **Type**: String - -#### Description - -The `description` field provides additional detail that may be relevant -for the package. Packages **may** include this field. - -* **Required**: No -* **Key**: `description` -* **Type**: String - -#### Keywords - -The `keywords` field provides relevant keywords related to this package. - -* **Required**: No -* **Key**: `keywords` -* **Type**: Array(String) - -#### Links - -The `links` field provides URIs to relevant resources associated with -this package. When possible, authors **should** use the following keys -for the following common resources. - -- `website`: Primary website for the package. - -- `documentation`: Package Documentation - -- `repository`: Location of the project source code. - -* **Required**: No -* **Key**: `links` -* **Type**: Object (String: String) - -### The *Sources* Object - -A *Sources* object is defined to have the following fields. - -* **Key**: A unique identifier for the source file. (String) -* **Value**: [Source Object](#the-source-object) - -### The *Source* Object - -#### Checksum: `checksum` - -Hash of the source file. - -* **Required**: Only **if** the `content` field is missing and none of the provided URLs contain a content hash. -* **Key**: `checksum` -* **Value**: [Checksum Object](#the-checksum-object) - -#### URLS: `urls` - -Array of urls that resolve to the same source file. -- Urls **should** be stored on a content-addressable filesystem. - **If** they are not, then either `content` or `checksum` **must** be - included. - -- Urls **must** be prefixed with a scheme. - -- If the resulting document is a directory the key **should** be - interpreted as a directory path. - -- If the resulting document is a file the key **should** be - interpreted as a file path. - -* **Required**: If `content` is not included. -* **Key**: `urls` -* **Value**: Array(String) - -#### Content: `content` - -Inlined contract source. If both `urls` and `content` are provided, the `content` value -**must** match the content of the files identified in `urls`. - -* **Required**: If `urls` is not included. -* **Key**: `content` -* **Value**: String - -#### Install Path: `installPath` - -Filesystem path of source file. -- **Must** be a relative filesystem path that begins with a `./`. - -- **Must** resolve to a path that is within the current virtual - working directory. - -- **Must** be unique across all included sources. - -- **Must not** contain `../` to avoid accessing files outside of - the source folder in improper implementations. - -* **Required**: This field **must** be included for the package to be writable to disk. -* **Key**: `installPath` -* **Value**: String - -#### Type: `type` - -The `type` field declares the type of the source file. The field -**should** be one of the following values: `solidity`, `vyper`, -`abi-json`, `solidity-ast-json`. - -* **Required**: No -* **Key**: `type` -* **Value**: String - -#### License: `license` - -The `license` field declares the type of license associated with -this source file. When defined, this license overrides the -package-scoped [meta license](#license). - -* **Required**: No -* **Key**: `license` -* **Value**: String - -### The *Checksum* Object - -A *Checksum* object is defined to have the following key/value pairs. - -#### Algorithm: `algorithm` - -The `algorithm` used to generate the corresponding hash. Possible -algorithms include, but are not limited to `sha3`, `sha256`, `md5`, -`keccak256`. - -* **Required**: Yes -* **Type**: String - -#### Hash: `hash` - -The `hash` of a source files contents generated with the corresponding -algorithm. - -* **Required**: Yes -* **Type**: String - -### The *Contract Type* Object - -A *Contract Type* object is defined to have the following key/value -pairs. - -#### Contract Name: `contractName` - -The `contractName` field defines the [Contract -Name](#contract-name) for this [Contract -Type](#contract-type). - -* **Required**: If the [Contract Name](#contract-name) and [Contract Alias](#contract-alias) are not the same. -* **Type**: String -* **Format**: **Must** be a valid [Contract Name](#contract-name) - -#### Source ID: `sourceId` - -The global source identifier for the source file from which this -contract type was generated. - -* **Required**: No -* **Type**: String -* **Format**: **Must** match a unique source ID included in the [Sources Object](#the-sources-object) for this package. - -#### Deployment Bytecode: `deploymentBytecode` - -The `deploymentBytecode` field defines the bytecode for this [Contract -Type](#contract-type). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode object](#the-bytecode-object) format. - -#### Runtime Bytecode: `runtimeBytecode` - -The `runtimeBytecode` field defines the unlinked `0x`-prefixed runtime -portion of [Bytecode](#bytecode) for this [Contract -Type](#contract-type). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode object](#the-bytecode-object) format. - -#### ABI: `abi` - -* **Required**: No -* **Type**: Array -* **Format**: **Must** conform to the [Ethereum Contract ABI JSON](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#json) format. - -#### UserDoc: `userdoc` - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [UserDoc](https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format#user-documentation) format. - -#### DevDoc: `devdoc` - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [DevDoc](https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format#developer-documentation) format. - -### The *Contract Instance* Object - -A **Contract Instance Object** represents a single deployed [Contract -Instance](#contract-instance) and is defined to have the following -key/value pairs. - -#### Contract Type: `contractType` - -The `contractType` field defines the [Contract -Type](#contract-type) for this [Contract -Instance](#contract-instance). This can reference any of the -contract types included in this [Package](#package) *or* any of the -contract types found in any of the package dependencies from the -`buildDependencies` section of the [Package -Manifest](#package-manifest). - -* **Required**: Yes -* **Type**: String -* **Format**: See below. - -Format - -Values for this field **must** conform to *one of* the two formats -herein. - -To reference a contract type from this Package, use the format -``. - -- The `` value **must** be a valid [Contract - Alias](#contract-alias). - -- The value **must** be present in the keys of the `contractTypes` - section of this Package. - -To reference a contract type from a dependency, use the format -`:`. - -- The `` value **must** be present in the keys of the - `buildDependencies` of this Package. - -- The `` value **must** be be a valid [Contract - Alias](#contract-alias). - -- The resolved package for `` must contain the - `` value in the keys of the `contractTypes` section. - -#### Address: `address` - -The `address` field defines the [Address](#address) of the -[Contract Instance](#contract-instance). - -* **Required**: Yes -* **Type**: String -* **Format**: Hex encoded `0x` prefixed Ethereum address matching the regular expression `^0x[0-9a-fA-F]{40}$`. - -#### Transaction: `transaction` - -The `transaction` field defines the transaction hash in which this -[Contract Instance](#contract-instance) was created. - -* **Required**: No -* **Type**: String -* **Format**: `0x` prefixed hex encoded transaction hash. - -#### Block: `block` - -The `block` field defines the block hash in which this the transaction -which created this *contract instance* was mined. - -* **Required**: No -* **Type**: String -* **Format**: `0x` prefixed hex encoded block hash. - -#### Runtime Bytecode: `runtimeBytecode` - -The `runtimeBytecode` field defines the runtime portion of bytecode for -this [Contract Instance](#contract-instance). When present, the -value from this field supersedes the `runtimeBytecode` from the -[Contract Type](#contract-type) for this [Contract -Instance](#contract-instance). - -* **Required**: No -* **Type**: Object -* **Format**: **Must** conform to the [Bytecode Object](#the-bytecode-object) format. - -Every entry in the `linkReferences` for this bytecode **must** have a -corresponding entry in the `linkDependencies` section. - -### The *Compiler Information* Object - -The `compilers` field defines the various compilers and settings used -during compilation of any [Contract Types](#contract-type) or -[Contract Instance](#contract-instance) included in this package. - -A *Compiler Information* object is defined to have the following -key/value pairs. - -#### Name: `name` - -The `name` field defines which compiler was used in compilation. - -* **Required**: Yes -* **Key**: `name` -* **Type**: String - -#### Version: `version` - -The `version` field defines the version of the compiler. The field -**should** be OS agnostic (OS not included in the string) and take the -form of either the stable version in -[semver](http://semver.org/) format or if built on a -nightly should be denoted in the form of `-` ex: -`0.4.8-commit.60cc1668`. - -* **Required**: Yes -* **Key**: `version` -* **Type**: String - -#### Settings: `settings` - -The `settings` field defines any settings or configuration that was used -in compilation. For the `"solc"` compiler, this **should** conform to -the [Compiler Input and Output -Description](http://solidity.readthedocs.io/en/latest/using-the-compiler.html#compiler-input-and-output-json-description). - -* **Required**: No -* **Key**: `settings` -* **Type**: Object - -#### Contract Types: `contractTypes` - -A list of the [Contract Alias](#contract-alias) or [Contract Types](#contract-type) in this package -that used this compiler to generate its outputs. - -- All `contractTypes` that locally declare `runtimeBytecode` - **should** be attributed for by a compiler object. - -- A single `contractTypes` **must** not be attributed to more than one - compiler. - -* **Required**: No -* **Key**: `contractTypes` -* **Type**: Array([Contract Alias](#contract-alias)) - - -### BIP122 URI - -BIP122 URIs are used to define a blockchain via a subset of the -[BIP-122](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki) -spec. - - blockchain:///block/ - -The `` represents the blockhash of the first block on the -chain, and `` represents the hash of the -latest block that’s been reliably confirmed (package managers should be -free to choose their desired level of confirmations). - -### Glossary - -The terms in this glossary have been updated to reflect the changes made -in V3. - -#### ABI -The JSON representation of the application binary interface. See the -official -[specification](https://solidity.readthedocs.io/en/develop/abi-spec.html) -for more information. - -#### Address -A public identifier for an account on a particular chain - -#### Bytecode -The set of EVM instructions as produced by a compiler. Unless otherwise -specified this should be assumed to be hexadecimal encoded, representing -a whole number of bytes, and [prefixed](#prefixed) with `0x`. - -Bytecode can either be linked or unlinked. (see -[Linking](#linking)) - -* **Unlinked Bytecode**: The hexadecimal representation of a contract’s EVM instructions that contains sections of code that requires [linking](#linking) for the contract to be functional.
The sections of code which are unlinked **must** be filled in with zero bytes.
**Example**: `0x606060405260e06000730000000000000000000000000000000000000000634d536f` -* **Linked Bytecode**: The hexadecimal representation of a contract’s EVM instructions which has had all [Link References](#link-reference) replaced with the desired [Link Values](#link-value). **Example**: `0x606060405260e06000736fe36000604051602001526040518160e060020a634d536f` - -#### Chain Definition -This definition originates from [BIP122 -URI](https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki). - -A URI in the format `blockchain:///block/` - -- `chain_id` is the unprefixed hexadecimal representation of the - genesis hash for the chain. - -- `block_hash` is the unprefixed hexadecimal representation of the - hash of a block on the chain. - -A chain is considered to match a chain definition if the the genesis -block hash matches the `chain_id` and the block defined by `block_hash` -can be found on that chain. It is possible for multiple chains to match -a single URI, in which case all chains are considered valid matches - -#### Content Addressable URI -Any URI which contains a cryptographic hash which can be used to verify -the integrity of the content found at the URI. - -The URI format is defined in RFC3986 - -It is **recommended** that tools support IPFS and Swarm. - -#### Contract Alias -This is a name used to reference a specific [Contract -Type](#contract-type). Contract aliases **must** be unique within a -single [Package](#package). - -The contract alias **must** use *one of* the following naming schemes: - -- `` - -- `` - -The `` portion **must** be the same as the [Contract -Name](#contract-name) for this contract type. - -The `` portion **must** match the regular expression -`^[-a-zA-Z0-9]{1,256}$`. - -#### Contract Instance -A contract instance a specific deployed version of a [Contract -Type](#contract-type). - -All contract instances have an [Address](#address) on some specific -chain. - -#### Contract Instance Name -A name which refers to a specific [Contract -Instance](#contract-instance) on a specific chain from the -deployments of a single [Package](#package). This name **must** be -unique across all other contract instances for the given chain. The name -must conform to the regular expression -`^[a-zA-Z_$][a-zA-Z0-9_$]{0,255}$` - -In cases where there is a single deployed instance of a given [Contract -Type](#contract-type), package managers **should** use the -[Contract Alias](#contract-alias) for that contract type for this -name. - -In cases where there are multiple deployed instances of a given contract -type, package managers **should** use a name which provides some added -semantic information as to help differentiate the two deployed instances -in a meaningful way. - -#### Contract Name -The name found in the source code that defines a specific [Contract -Type](#contract-type). These names **must** conform to the regular -expression `^[a-zA-Z_$][a-zA-Z0-9_$]{0,255}$`. - -There can be multiple contracts with the same contract name in a -projects source files. - -#### Contract Type -Refers to a specific contract in the package source. This term can be -used to refer to an abstract contract, a normal contract, or a library. -Two contracts are of the same contract type if they have the same -bytecode. - -Example: - - contract Wallet { - ... - } - -A deployed instance of the `Wallet` contract would be of of type -`Wallet`. - -#### Identifier -Refers generally to a named entity in the [Package](#package). - -A string matching the regular expression -`^[a-zA-Z][-_a-zA-Z0-9]{0,255}$` - -#### Link Reference -A location within a contract’s bytecode which needs to be linked. A link -reference has the following properties. - -* **`offset`**: Defines the location within the bytecode where the link reference begins. -* **`length`**: Defines the length of the reference. -* **`name`**: (optional) A string to identify the reference. - -#### Link Value -A link value is the value which can be inserted in place of a [Link -Reference](#link-reference) - -#### Linking -The act of replacing [Link References](#link-reference) with [Link -Values](#link-value) within some [Bytecode](#bytecode). - -#### Package -Distribution of an application’s source or compiled bytecode along with -metadata related to authorship, license, versioning, et al. - -For brevity, the term **Package** is often used metonymously to mean -[Package Manifest](#package-manifest). - -#### Package Manifest -A machine-readable description of a package. - -#### Prefixed -[Bytecode](#bytecode) string with leading `0x`. - -* **Example**: `0xdeadbeef` - -#### Unprefixed -Not [Prefixed](#prefixed). - -* **Example**: `deadbeef` - -## Rationale - -### Minification - -EthPM packages are distributed as alphabetically-ordered & minified JSON to ensure consistency. -Since packages are published on content-addressable filesystems (eg. IPFS), this restriction -guarantees that any given set of contract assets will always resolve to the same content-addressed URI. - -### Package Names - -Package names are restricted to lower-case characters, numbers, and `-` to improve the readability -of the package name, in turn improving the security properties for a package. A user is more likely -to accurately identify their target package with this restricted set of characters, and not confuse -a malicious package that disguises itself as a trusted package with similar but different -characters (e.g. `O` and `0`). - -### BIP122 - -The BIP-122 standard has been used since EthPM v1 since it is an industry standard URI scheme for -identifying different blockchains and distinguishing between forks. - -### Compilers - -Compilers are now defined in a top-level array, simplifying the task for tooling to identify the compiler types -needed to interact with or validate the contract assets. This also removes unnecessarily duplicated -information, should multiple `contractTypes` share the same compiler type. - -## Backwards Compatibility - -To improve understanding and readability of the EthPM spec, the -`manifest_version` field was updated to `manifest` in v3. To ensure -backwards compatibility, v3 packages **must** define a top-level -`"manifest"` with a value of `"ethpm/3"`. Additionally, -`"manifest_version"` is a forbidden top-level key in v3 packages. - - -## Security Considerations - -Using EthPM packages implicitly requires importing &/or executing code written by others. The EthPM spec -guarantees that when using a properly constructed and released EthPM package, the user will have the exact same -code that was included in the package by the package author. However, it is impossible to guarantee that this code -is safe to interact with. Therefore, it is critical that end users only interact with EthPM packages authored and -released by individuals or organizations that they trust to include non-malicious code. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2678.md diff --git a/EIPS/eip-2680.md b/EIPS/eip-2680.md index 497cac5080d0c9..637cab1e90dde0 100644 --- a/EIPS/eip-2680.md +++ b/EIPS/eip-2680.md @@ -1,136 +1,7 @@ --- eip: 2680 -title: Ethereum 2 wallet layout -author: Jim McDonald -discussions-to: https://ethereum-magicians.org/t/eip-2680-ethereum-2-wallet-layout/4323 -status: Stagnant -type: Standards Track category: ERC -created: 2020-05-29 +status: Moved --- -## Simple Summary - -A standard layout and naming format for walletstore and keystore for both hierarchical (e.g. filesystem, Amazon S3) and non-hierarchical (key/value) storage systems. - -## Abstract - -Ethereum wallets have no standards for their layout in persistent storage, making different wallet implementations incompatible. This defines a standard for the placement of Ethereum walletstores and keystores, making it possible for different software to work with the same wallets and keys. - -## Motivation - -A standard layout for wallets and accounts allows interoperability between validators. This benefits users, as they can move from one validator software to another (and back) without requiring movement of files. This is important because any movement of files containing keys involves danger of either deleting them or duplicating them, both of which could cause loss of access to funds. - -## Specification - -There are four elements for a wallet that need to be addressed. These are defined below. - -### Base location -The base location is required to be well-known, either pre-defined or defined by the storage system's connection parameters. - -For filesystems the pre-defined base location for different operating systems is as follows: - - - Windows: `%APPDATA%\ethereum2\wallets` - - MacOSX: `${HOME}/Library/Application Support/ethereum2/wallets` - - Linux: `${HOME}/.config/ethereum2/wallets` - -For other hierarchical stores, for example Amazon S3, the base location MUST be the lower-case hex string representing the [SHA-256](../assets/eip-2680/sha256-384-512.pdf) hash of the string "Ethereum 2 wallet:" appended with the identifier for the hierarchical store. For example, if the account ID for a user's Amazon S3 account is "AbC0438EB" then: - - - string would be `Ethereum 2 wallet:AbC0438EB` - - SHA-256 hash of string would be the byte array `0x991ec14a8d13836b10d8c3039c9e30876491cb8aa9c9c16967578afc815c9229` - - base location would be the string `991ec14a8d13836b10d8c3039c9e30876491cb8aa9c9c16967578afc815c9229` - -For non-hierarchical stores there is no base location. - -### Wallet container -The wallet container holds the walletstore and related keystores. - -The wallet container is identified by the wallet's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Walletstore -The walletstore element contains the walletstore and is held within the wallet container. It is identified by the wallet's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -### Keystore -The keystore element contains the keystore for a given key and is held within the wallet container. It is identified by the key's UUID. It MUST be a string following the syntactic structure as laid out in [section 3 of RFC 4122](https://tools.ietf.org/html/rfc4122#section-3). - -## Hierarchical store example -Hierarchical stores are a common way to store and organize information. The most common example is the filesystem, but a number of object-based stores such as Amazon S3 also provide hierarchical naming. - -Putting these elements together for a sample wallet with wallet UUID `1f031fff-c51d-44fc-8baf-d6b304cb70a7` and key UUIDs `1302106c-8441-4e2e-b687-6c77f49fc624` and `4a320100-83fd-4db7-8126-6d6d205ba834` gives the following layout: - -``` -- 1f031fff-c51d-44fc-8baf-d6b304cb70a7 -+- 1302106c-8441-4e2e-b687-6c77f49fc624 -+- 1f031fff-c51d-44fc-8baf-d6b304cb70a7 -+- 4a320100-83fd-4db7-8126-6d6d205ba834 -``` - -### Non-hierarchical store example -Non-hierarchical stores use a simplified approach where the wallet UUID and key UUIDs are concatenated using the ':' character. Using the same example wallet and key UUIDs as above would result in objects with the following keys: - -``` -1f031fff-c51d-44fc-8baf-d6b304cb70a7:1302106c-8441-4e2e-b687-6c77f49fc624 -1f031fff-c51d-44fc-8baf-d6b304cb70a7:1f031fff-c51d-44fc-8baf-d6b304cb70a7 -1f031fff-c51d-44fc-8baf-d6b304cb70a7:4a320100-83fd-4db7-8126-6d6d205ba834 -``` - -### Protecting against concurrent write access -TBD - -### Iterating over wallets -In the case of hierarchical stores and iteration-capable non-hierarchical stores iteration over wallets is a matter of iterating over the files in the root container. - -An implementer MAY include an index in the base location. If so then it MUST follow the structure as specified in the following "Index format" section. - -### Iterating over accounts -In the case of hierarchical stores iteration over accounts is a matter of iterating over the files in the wallet container. - -An implementer MAY include an index within a wallet container for accounts within that wallet. If so then it MUST follow the structure as specified in the following "Index format" section. - -### Index format -The index format is the same for both wallets and accounts, following a standard JSON schema. - -```json -{ - "type": "array", - "items": { - "type": "object", - "properties": { - "uuid": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": [ - "uuid", - "name" - ] - } -} -``` - -The index MUST use the identifier 'index'. - -Public keys must NOT be stored in the index. - -## Rationale - -A standard for walletstores, similar to that for keystores, provides a higher level of compatibility between wallets and allows for simpler wallet and key interchange between them. - -## Implementation - -A Go implementation of the filesystem layout can be found at [https://github.com/wealdtech/go-eth2-wallet-filesystem](https://github.com/wealdtech/go-eth2-wallet-filesystem). - -A Go implementation of the Amazon S3 layout can be found at [https://github.com/wealdtech/go-eth2-wallet-s3](https://github.com/wealdtech/go-eth2-wallet-s3). - -## Security Considerations - -Locations for wallet stores are defined to be within each user's personal space, reducing the possibility of accidental exposure of information. It is, however, still possible for permissions to be set such that this data is world-readable, and applications implementing this EIP should attempt to set, and reset, permissions to ensure that only the relevant user has access to the information. - -The names for both wallet and key stores are UUIDs, ensuring that no data is leaked from the metadata. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2680.md diff --git a/EIPS/eip-2711.md b/EIPS/eip-2711.md index 1f4d5139ce1255..4c733e9dc9dd57 100644 --- a/EIPS/eip-2711.md +++ b/EIPS/eip-2711.md @@ -96,7 +96,7 @@ While we could save one byte in the common case by bundling the y-parity bit of ### Optionality of ChainID Sometimes it is useful to have a transaction that *can* be replayed on multiple chains. An example of this is when you construct a vanity signature for a transaction and have the `from` be whatever address that signature recovers to. With the ability to have someone else be a gas payer (setting both the gas limit and the gas price), one can have transactions that deploy contracts which live at the same address on every chain. While this can be accomplished with CREATE2 using legacy transactions, we have the opportunity here to simplify the process and enable potentially other future uses of deterministic transactions by making ChainID optional. ### Optionality of ValidUntil -A user can set `ValidUntil` to a very large number which effectively makes it non-expiring. By making `ValidUntil` optional, we can save some bytes on the wire by allowing such transcations to simply have a `0` (1 byte in RLP) value for this field. +A user can set `ValidUntil` to a very large number which effectively makes it non-expiring. By making `ValidUntil` optional, we can save some bytes on the wire by allowing such transactions to simply have a `0` (1 byte in RLP) value for this field. ### `SENDER` sets `gasLimit` and `gasPrice` This type of transaction is useful when the transaction may execute differently depending on what these values are set to. By having the `SENDER` set both, we ensure that the `SENDER` has full control over the transaction details. ### `SENDER` sets `gasLimit`, `GAS_PAYER` sets `gasPrice` diff --git a/EIPS/eip-2733.md b/EIPS/eip-2733.md index 04b276efdb09b7..067265651ba557 100644 --- a/EIPS/eip-2733.md +++ b/EIPS/eip-2733.md @@ -249,7 +249,7 @@ limit. These fields are included to better support future changes to the transaction type. This would likely be used in conjunction with the `flags` and `type` fields. A benefit of explicitly defining them is that specialized serialization -of RLP can be avoided, simplifing clients and downstream infrastructure. The +of RLP can be avoided, simplifying clients and downstream infrastructure. The author believe the cost of 2 bytes per transaction is acceptable for smoother integration of future features. diff --git a/EIPS/eip-2746.md b/EIPS/eip-2746.md index 22aa20efbabfb9..ef688895dcf679 100644 --- a/EIPS/eip-2746.md +++ b/EIPS/eip-2746.md @@ -1,220 +1,7 @@ --- eip: 2746 -title: Rules Engine Standard -author: Aaron Kendall (@jaerith), Juan Blanco (@juanfranblanco) -discussions-to: https://ethereum-magicians.org/t/eip-2746-rules-engine-interface/4435 -status: Stagnant -type: Standards Track category: ERC -created: 2020-06-20 +status: Moved --- -## Simple Summary -An interface for using a smart contract as a rules engine. A single deployed contract can register a data domain, create sets of rules that perform actions on that domain, and then invoke a set as an atomic transaction. - -## Abstract -This standard proposes an interface that will allow the creation of hierarchal sets of rules (i.e., RuleTrees) that can be invoked to evaluate and manipulate a registered data domain. At the time of this draft, all intentions to insert additional functionality onto the blockchain requires the coding and creation of a newly deployed contract. However, this standard will allow users to deploy a contract just once, one which will then allow them to create (and invoke) pipelines of commands within that contract. - -## Motivation -At the time of this draft, all development for Ethereum requires writing the code that forms smart contracts and then deploying those contracts to Ethereum. In order to create a proper contract, many considerations must be taken into account when designing and implementing the code, especially in terms of efficiency (i.e., gas cost) and security. Even the simplest contracts require a certain amount of vigilance and examination, before and after deployment. These requirements pertain to all cases, even for simple cases of examining a value and/or altering it. - -These technical challenges might form an obstacle for many others who might wish to create software around Ethereum. Less technical companies and users might also want to configure and deploy simple functionality onto the chain, without knowing the relevant languages or details necessary. By having the data domain and the predefined actions (i.e., types of rules) implemented along with this interface, a deployed instance of such a rules engine contract can provide efficient and safe functionality to no-code or little-code clients, allowing more users of various technical proficiency to interact with the Ethereum ecosystem. - -## Specification -For the clarification of terminology, an Attribute is a registered data point within the data domain, representing data that exists either in the rules engine contract or elsewhere. A Rule is an predefined action that occurs upon a single data point (i.e., Attribute) in the predefined data domain. For example, a Rule could check whether the Attribute 'TokenAmt' has a value less than the RHL (i.e., right-hand value) of 10. A RuleSet is a collection of Rules, where their collection invocation creates a boolean result that determines the navigational flow of execution between RuleSets. A RuleTree is a collection of RuleSets that are organized within a hierarchy, where RuleSets can contain other RuleSets. - -```solidity -pragma solidity ^0.6.0; - -/** - @title ERC-2746 Rules Engine Standard - @dev See https://eips.ethereum.org/EIPS/eip-2746 - */ - interface ERCRulesEngine { - - /** - @dev Should emit when a RuleTree is invoked. - The `ruler` is the ID and owner of the RuleTree being invoked. It is also likely msg.sender. - */ - event CallRuleTree( - address indexed ruler - ); - - /** - @dev Should emit when a RuleSet is invoked. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - */ - event CallRuleSet( - address indexed ruler, - bytes32 indexed tmpRuleSetId - ); - - /** - @dev Should emit when a Rule is invoked. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - The 'ruleId' is the ID of the Rule being invoked. - The 'ruleType' is the type of the rule being invoked. - */ - event CallRule( - address indexed ruler, - bytes32 indexed ruleSetId, - bytes32 indexed ruleId, - uint ruleType - ); - - /** - @dev Should emit when a RuleSet fails. - The `ruler` is the ID and owner of the RuleTree in which the RuleSet is stored. It is also likely msg.sender. - The 'ruleSetId' is the ID of the RuleSet being invoked. - The 'severeFailure' is the indicator of whether or not the RuleSet is a leaf with a 'severe' error flag. - */ - event RuleSetError ( - address indexed ruler, - bytes32 indexed ruleSetId, - bool severeFailure - ); - - /** - @notice Adds a new Attribute to the data domain. - @dev Caller should be the deployer/owner of the rules engine contract. An Attribute value can be an optional alternative if it's not a string or numeric. - @param _attrName Name/ID of the Attribute - @param _maxLen Maximum length of the Attribute (if it is a string) - @param _maxNumVal Maximum numeric value of the Attribute (if it is numeric) - @param _defaultVal The default value for the Attribute (if one is not found from the source) - @param _isString Indicator of whether or not the Attribute is a string - @param _isNumeric Indicator of whether or not the Attribute is numeric - */ - function addAttribute(bytes32 _attrName, uint _maxLen, uint _maxNumVal, string calldata _defaultVal, bool _isString, bool _isNumeric) external; - - /** - @notice Adds a new RuleTree. - @param _owner Owner/ID of the RuleTree - @param _ruleTreeName Name of the RuleTree - @param _desc Verbose description of the RuleTree's purpose - */ - function addRuleTree(address _owner, bytes32 _ruleTreeName, string calldata _desc) external; - - /** - @notice Adds a new RuleSet onto the hierarchy of a RuleTree. - @dev RuleSets can have child RuleSets, but they will only be called if the parent's Rules execute to create boolean 'true'. - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet - @param _desc Verbose description of the RuleSet - @param _parentRSName ID/Name of the parent RuleSet, to which this will be added as a child - @param _severalFailFlag Indicator of whether or not the RuleSet's execution (as failure) will result in a failure of the RuleTree. (This flag only applies to leaves in the RuleTree.) - @param _useAndOp Indicator of whether or not the rules in the RuleSet will execute with 'AND' between them. (Otherwise, it will be 'OR'.) - @param _failQuickFlag Indicator of whether or not the RuleSet's execution (as failure) should immediately stop the RuleTree. - */ - function addRuleSet(address _owner, bytes32 _ruleSetName, string calldata _desc, bytes32 _parentRSName, bool _severalFailFlag, bool _useAndOp, bool _failQuickFlag) external; - - /** - @notice Adds a new Rule into a RuleSet. - @dev Rule types can be implemented as any type of action (greater than, less than, etc.) - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet to which the Rule will be added - @param _ruleName ID/Name of the Rule being added - @param _attrName ID/Name of the Attribute upon which the Rule is invoked - @param _ruleType ID of the type of Rule - @param _rightHandValue The registered value to be used by the Rule when performing its action upon the Attribute - @param _notFlag Indicator of whether or not the NOT operator should be performed on this Rule. - */ - function addRule(address _owner, bytes32 _ruleSetName, bytes32 _ruleName, bytes32 _attrName, uint _ruleType, string calldata _rightHandValue, bool _notFlag) external; - - /** - @notice Executes a RuleTree. - @param _owner Owner/ID of the RuleTree - */ - function executeRuleTree(address _owner) external returns (bool); - - /** - @notice Retrieves the properties of a Rule. - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet where the Rule resides - @param _ruleIdx Index of the rule in the RuleSet's listing - @return bytes32 ID/Name of Rule - @return uint Type of Rule - @return bytes32 Target Attribute of Rule - @return string Value mentioned in Rule - @return bool Flag for NOT operator in Rule - @return bytes32[] Values that should be provided in delegated call (if Rule is custom operator) - */ - function getRuleProps(address _owner, bytes32 _ruleSetName, uint _ruleIdx) external returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory); - - /** - @notice Retrieves the properties of a RuleSet - @param _owner Owner/ID of the RuleTree - @param _ruleSetName ID/Name of the RuleSet - @return string Verbose description of the RuleSet - @return bool Flag that indicates whether this RuleSet's failure (if a leaf) will cause the RuleTree to fail - @return bool Flag that indicates whether this RuleSet uses the AND operator when executing rules collectively - @return uint Indicates the number of rules hosted by this RuleSet - @return bytes32[] The list of RuleSets that are children of this RuleSet - */ - function getRuleSetProps(address _owner, bytes32 _ruleSetName) external returns (string memory, bool, bool, uint, uint, bytes32[] memory); - - /** - @notice Retrieves the properties of a RuleSet - @param _owner Owner/ID of the RuleTree - @return bytes32 Name of the RuleTree - @return string Verbose description of the RuleTree - @return bytes32 ID/Name of the RuleSet that serves as the root node for the RuleTree - */ - function getRuleTreeProps(address _owner) external returns (bytes32, string memory, bytes32); - - /** - @notice Removes a RuleTree. - @param _owner Owner/ID of the RuleTree - */ - function removeRuleTree(address _owner) external returns (bool); -} -``` - -### Considerations - -An argument could be made for interface functions that allow a RuleTree's owner to include others users as executors of the RuleTree. - -Another argument could be made for interface functions that allow an administrator to configure the origin point of an Attribute, such as whether the Attribute's value comes from a data structure (internal to the rules engine contract) or from calling a contract method (like an implementation of the [Diamond Standard](https://github.com/ethereum/EIPs/issues/2535)). - -Yet another argument could be made for interface functions that allow an administrator to extend the functionality catalog provided by the rules engine, by allowing other contracts' methods to be added as a rule operation. - -Also, an argument could be made for functions that calculate and report the range of potential cost for invoking a RuleTree. Unlike the normal execution of a contract method, the Ethereum transaction costs of invoking a RuleTree are more dynamic, depending on its depth/breadth and the navigational flow during invocation. Since the general cost of a RuleTree is unknown until the time of invocation, these functions could report the minimal amount of gas for a transaction (i.e., none of the Rules in a RuleTree are invoked) and the maximum amount for a transaction (i.e., all Rules in a RuleTree are invoked). - -### Example - -A company wishes to deploy a contract with data points and functionality that are predefined and/or under the control of an administrator, and it aims to build a no-code client that will allow less-technical users to define actions within the rules engine contract. In this example, the company wants one of its users to write the rules in a proprietary markup language, in order for the calculation of a VAT to be determined. For the sake of transparency, [these rules](https://ipfs.infura.io/ipfs/QmPrZ9959c7SzzqdLkVgX28xM7ZrqLeT3ydvRAHCaL1Hsn) are published onto IPFS, so that they are accessible to auditors and possibly government officials. The no-code client will then know how to parse the rules from the markup and communicate with the rules engine contract, establishing the RuleTree to be invoked later by the company's user(s) or off-chain programs. - -In order to calculate the value of the VAT, these provided rules invoke simple mathematical operations that can perform the calculation. However, the implementation of the rules engine contract could possess other functionality called by rules, ones that could execute more complicated logic or call the methods of other contracts. - -## Rationale - -### Attributes - -The data points are abstracted in order to let the implementation provide the mechanism for retrieving/populating the data. Data can be held by an internal data structure, another contract's method, or any number of other options. - -### Events - -The events specified will help the caller of the RuleTree after execution, so that they may ascertain the navigational flow of RuleSet execution within the RuleTree and so that they may understand which RuleSets failed. - -### Right-Hand Value - -In the function addRule(), the data type for the right-hand value is 'string' since the rule's action depends on its type, meaning that the value must be provided in a generic form. In the case of a Rule that performs numerical operations, the provided value could be transformed into a number when stored in the Rule. - -## Implementation -- [Wonka](https://github.com/Nethereum/Wonka/tree/master/Solidity/WonkaEngine) -- [Wonka Rules Editor](https://github.com/jaerith/WonkaRulesBlazorEditor) - -The Wonka implementation supports this proposed interface and also implements all of the additional considerations mentioned above. - -## Security Considerations - -The deployer of the contract should be the owner and administrator, allowing for the addition of Attributes and RuleTrees. Since a RuleTree is owned by a particular EOA (or contract address), the only accounts that should be able to execute the RuleTree should be its owner or the contract's owner/administrator. If Attributes are defined to exist as data within other contracts, the implementation must take into account the possibility that RuleTree owners must have the security to access the data in those contracts. - -## References - -**Standards** -- [EIP-2535 Diamond Standard](./eip-2535.md) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2746.md diff --git a/EIPS/eip-2767.md b/EIPS/eip-2767.md index 87ac14f0f4c6d7..e78cf4776e1ff8 100644 --- a/EIPS/eip-2767.md +++ b/EIPS/eip-2767.md @@ -1,123 +1,7 @@ --- eip: 2767 -title: Contract Ownership Governance -author: Soham Zemse (@zemse), Nick Mudge (@mudgen) -discussions-to: https://github.com/ethereum/EIPs/issues/2766 -status: Stagnant -type: Standards Track category: ERC -created: 2020-07-04 -requires: 20, 165, 173 +status: Moved --- -## Simple Summary - -A standard for Governance contracts that holds the administrative ownership of other smart contracts with voting power distributed as `ERC-20` tokens. - -## Abstract - -The following standard defines the implementation of a standard API for a Governance smart contract based on `ERC-20`. Existing `ERC-173` compatible contracts can upgrade from private key wallet ownership to a Governance smart contract. Adhering to a standard API enables general tools to populate governance information of various projects, thus increasing transparency. - -## Motivation - -Traditionally, many contracts that require that they be owned or controlled in some way use `ERC-173` which standardized the use of ownership in the smart contracts. For example to withdraw funds or perform administrative actions. - -```solidity -contract dApp { - function doSomethingAdministrative() external onlyOwner { - // admin logic that can be performed by a single wallet - } -} -``` - -Often, such administrative rights for a contract are written for maintenance purpose but users need to trust the owner. Rescue operations by an owner have raised questions on decentralised nature of the projects. Also, there is a possibility of compromise of an owner's private key. - -At present, many governance implementations by ambitious projects need users to visit a specific UI to see governance information about their project. Some examples of live implementations having different API that does the same thing are [Compound Governance](https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol#L27), [Uniswap Governance](https://github.com/Uniswap/governance/blob/master/contracts/GovernorAlpha.sol#L27) and [Sushiswap Governance](https://github.com/sushiswap/sushiswap/blob/master/contracts/GovernorAlpha.sol#L45). It's just like if the ERC-20 standard wasn't finalized, then token projects would have their own block explorer. Adhering to a standard API would enable general tools (like Etherscan) to populate governance information, thus increasing transparency to users. Using widely popular `ERC-20` token as a governance token, existing tools built to work with `ERC-20` can already display voters. This can result in a wide adoption for contract governance over private key based ownership. - -## Specification - -A Governance contract that is compliant with `ERC-2767` shall implement the following interfaces: - -```solidity -/// @title ERC-2767 Governance -/// @dev ERC-165 InterfaceID: 0xd8b04e0e -interface ERC2767 is ERC165 { - /// @notice Gets number votes required for achieving consensus - /// @dev Should cost less than 30000 gas - /// @return Required number of votes for achieving consensus - function quorumVotes() external view returns (uint256); - - /// @notice The address of the Governance ERC20 token - function token() external view returns (address); -} -``` - -### `ERC-20` Governance Token - -An `ERC-2767` Governance Contract should reference an address through `token()` that implements `ERC-20` interface. `token()` is allowed to return self address (`address(this)`), if `ERC-20` functionalities are implemented in the same contract (one can consider checking out Diamond Standard [`ERC-2535`](https://eips.ethereum.org/EIPS/eip-2535) to optimise contract size). - -Implementations are allowed to have varying `ERC-20`'s `totalSupply()` (through any standard of minting or burning). But having a fixed `quorumVotes()` return value in this case would cause required votes consensus in `%` with respect to `totalSupply()` to change. To automatically account for this, any custom logic under `quorumVotes()` is allowed to return for e.g. `51%` of `totalSupply()`. - -### `ERC-165` Interface Identification - -An `ERC-2767` Governance Contract should also implement `ERC-165`. This helps general tools to identify whether a contract is a `ERC-2767` Governance contract. - -```solidity -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - -The goals of this EIP have been the following: - -- Standardize API of Governance contracts to make it easy for analysis tools to be built. -- Encourage use of `ERC-20` based weighted governance over existing multi-sig (_generally limited to 50 max owners_) for big projects. -- Encourage existing `ERC-173` ownership smart contracts / projects to move to Governance based ownership by removing the effort needed to host custom UI for their project. -- Encourage availability of publicly audited governance contracts, just like `ERC-20` which anyone can use. -- Make it possible to utilize existing `ERC-20` tools for owners of governance token analysis. -- Make future protocols possible that need to interact with governances of multiple projects. -- Keep this EIP minimal and allow another EIPs to standardize any specific functionalities. - -## Backwards Compatibility - -Smart contracts that are `ERC-173` compliant can transfer their ownership to a Governance contract. This enables such contracts to become compatible with `ERC-2767` Governance. - -However, there are some existing projects with governance implementations and most of them have custom APIs ([Compound Governance](https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol#L27), [Uniswap Governance](https://github.com/Uniswap/governance/blob/master/contracts/GovernorAlpha.sol#L27) and [Sushiswap Governance](https://github.com/sushiswap/sushiswap/blob/master/contracts/GovernorAlpha.sol#L45)), since a standard did not exist. Not having an `ERC-2767` compatible governance contract means only that general tools might not be able to populate their governance information without including some special code for the project. - -For existing governance contracts to get compatible with `ERC-2767`: - -1. Projects can deploy a new governance contract and transfer ownership to it to be `ERC-2767` compatible. This is suitable for those who use Multi-sig wallets for Governance. -2. It is understood that redeploying governance contracts would be a troublesome task, and contracts who already have functionality similar to `ERC-20` based (weighted votes) have a bit advanced way to avoid it. Basically, they can create a forwarder contract implements `ERC-2767` and forwards all calls to the actual non-standard methods. Projects can list the forwarder contract to display the information project's governance info without requiring any custom code in analysys tool, but this might have certain limitations depending on the project's existing governance implementation. Specification of forwarder contract is out of scope for this EIP and it may be addressed in another EIP if required. - - - -## Implementation - -The reference implementations are available in this [repository](https://github.com/zemse/contract-ownership-governance). Publicly audited implementations will be included in future. - -## Security Considerations - -Implementers are free to choose between On-chain and Off-chain consensus. Exact specification is out of scope for this standard (open for other EIPs to standardize). However, this section mentions points that implementers can consider. - -#### On-chain - -In such implementations, community can create transaction proposals and vote on it by sending on-chain transactions. - -- OpenZeppelin Snapshots can be used to prevent double voting. - -#### Off-chain - -- The signatures in off-chain governance implementation can follow recommendations of `ERC-191` or `ERC-712`. -- To prevent replaying signatures, it'd be best if executer is required to sort the signatures based on increasing addresses. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2767.md diff --git a/EIPS/eip-2770.md b/EIPS/eip-2770.md index db0b5d726f7a40..85c594e1ec4b01 100644 --- a/EIPS/eip-2770.md +++ b/EIPS/eip-2770.md @@ -1,207 +1,7 @@ --- eip: 2770 -title: Meta-Transactions Forwarder Contract -author: Alex Forshtat (@forshtat), Dror Tirosh (@drortirosh) -discussions-to: https://ethereum-magicians.org/t/erc-2770-meta-transactions-forwarder-contract/5391 -status: Stagnant -type: Standards Track category: ERC -created: 2020-07-01 -requires: 712, 2771 +status: Moved --- -## Simple Summary -Standardized contract interface for extensible meta-transaction forwarding. - -## Abstract - -This proposal defines an external API of an extensible Forwarder whose responsibility is to validate transaction -signatures on-chain and expose the signer to the destination contract, that is expected to accommodate all use-cases. -The ERC-712 structure of the forwarding request can be extended allowing wallets to display readable data even -for types not known during the Forwarder contract deployment. - -## Motivation - -There is a growing interest in making it possible for Ethereum contracts to -accept calls from externally owned accounts that do not have ETH to pay for -gas. - -This can be accomplished with meta-transactions, which are transactions that have been signed as plain data by one -externally owned account first and then wrapped into an Ethereum transaction by a different account. - -`msg.sender` is a transaction parameter that can be inspected by a contract to -determine who signed the transaction. The integrity of this parameter is -guaranteed by the Ethereum EVM, but for a meta-transaction verifying -`msg.sender` is insufficient, and signer address must be recovered as well. - -The Forwarder contract described here allows multiple Gas Relays and Relay Recipient contracts to rely -on a single instance of the signature verifying code, improving reliability and security -of any participating meta-transaction framework, as well as avoiding on-chain code duplication. - -## Specification -The Forwarder contract operates by accepting a signed typed data together with it's ERC-712 signature, -performing signature verification of incoming data, appending the signer address to the data field and -performing a call to the target. - -### Forwarder data type registration -Request struct MUST contain the following fields in this exact order: -``` -struct ForwardRequest { - address from; - address to; - uint256 value; - uint256 gas; - uint256 nonce; - bytes data; - uint256 validUntil; -} -``` -`from` - an externally-owned account making the request \ -`to` - a destination address, normally a smart-contract\ -`value` - an amount of Ether to transfer to the destination\ -`gas` - an amount of gas limit to set for the execution\ -`nonce` - an on-chain tracked nonce of a transaction\ -`data` - the data to be sent to the destination\ -`validUntil` - the highest block number the request can be forwarded in, or 0 if request validity is not time-limited - -The request struct MAY include any other fields, including nested structs, if necessary. -In order for the Forwarder to be able to enforce the names of the fields of this struct, only registered types are allowed. - -Registration MUST be performed in advance by a call to the following method: -``` -function registerRequestType(string typeName, string typeSuffix) -``` -`typeName` - a name of a type being registered\ -`typeSuffix` - an ERC-712 compatible description of a type - -For example, after calling -``` -registerRequestType("ExtendedRequest", "uint256 x,bytes z,ExtraData extraData)ExtraData(uint256 a,uint256 b,uint256 c)") -``` -the following ERC-712 type will be registered with forwarder: -``` -/* primary type */ -struct ExtendedRequest { - address from; - address to; - uint256 value; - uint256 gas; - uint256 nonce; - bytes data; - uint256 validUntil; - uint256 x; - bytes z; - ExtraData extraData; -} - -/* subtype */ -struct ExtraData { - uint256 a; - uint256 b; - uint256 c; -} -``` - -### Signature verification - -The following method performs an ERC-712 signature check on a request: -``` -function verify( - ForwardRequest forwardRequest, - bytes32 domainSeparator, - bytes32 requestTypeHash, - bytes suffixData, - bytes signature -) view; -``` -`forwardRequest` - an instance of the `ForwardRequest` struct -`domainSeparator` - caller-provided domain separator to prevent signature reuse across dapps (refer to ERC-712) -`requestTypeHash` - hash of the registered relay request type -`suffixData` - RLP-encoding of the remainder of the request struct -`signature` - an ERC-712 signature on the concatenation of `forwardRequest` and `suffixData` - -### Command execution - -In order for the Forwarder to perform an operation, the following method is to be called: -``` -function execute( - ForwardRequest forwardRequest, - bytes32 domainSeparator, - bytes32 requestTypeHash, - bytes suffixData, - bytes signature -) -public -payable -returns ( - bool success, - bytes memory ret -) -``` - -Performs the ‘verify’ internally and if it succeeds performs the following call: -``` -bytes memory data = abi.encodePacked(forwardRequest.data, forwardRequest.from); -... -(success, ret) = forwardRequest.to.call{gas: forwardRequest.gas, value: forwardRequest.value}(data); -``` -Regardless of whether the inner call succeeds or reverts, the nonce is incremented, invalidating the signature and preventing a replay of the request. - -Note that `gas` parameter behaves according to EVM rules, specifically EIP-150. The forwarder validates internally that -there is enough gas for the inner call. In case the `forwardRequest` specifies non-zero value, extra `40000 gas` is -reserved in case inner call reverts or there is a remaining Ether so there is a need to transfer value from the `Forwarder`: -```solidity -uint gasForTransfer = 0; -if ( req.value != 0 ) { - gasForTransfer = 40000; // buffer in case we need to move Ether after the transaction. -} -... -require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas"); -``` -In case there is not enough `value` in the Forwarder the execution of the inner call fails.\ -Be aware that if the inner call ends up transferring Ether to the `Forwarder` in a call that did not originally have `value`, this -Ether will remain inside `Forwarder` after the transaction is complete. - -### ERC-712 and 'suffixData' parameter -`suffixData` field must provide a valid 'tail' of an ERC-712 typed data. -For instance, in order to sign on the `ExtendedRequest` struct, the data will be a concatenation of the following chunks: -* `forwardRequest` fields will be RLP-encoded as-is, and variable-length `data` field will be hashed -* `uint256 x` will be appended entirely as-is -* `bytes z` will be hashed first -* `ExtraData extraData` will be hashed as a typed data - -So a valid `suffixData` is calculated as following: -``` -function calculateSuffixData(ExtendedRequest request) internal pure returns (bytes) { - return abi.encode(request.x, keccak256(request.z), hashExtraData(request.extraData)); -} - -function hashExtraData(ExtraData extraData) internal pure returns (bytes32) { - return keccak256(abi.encode( - keccak256("ExtraData(uint256 a,uint256 b,uint256 c)"), - extraData.a, - extraData.b, - extraData.c - )); -} -``` - -### Accepting Forwarded calls -In order to support calls performed via the Forwarder, the Recipient contract must read the signer address from the -last 20 bytes of `msg.data`, as described in ERC-2771. - -## Rationale -Further relying on `msg.sender` to authenticate end users by their externally-owned accounts is taking the Ethereum dapp ecosystem to a dead end. - -A need for users to own Ether before they can interact with any contract has made a huge portion of use-cases for smart contracts non-viable, -which in turn limits the mass adoption and enforces this vicious cycle. - -`validUntil` field uses a block number instead of timestamp in order to allow for better precision and integration -with other common block-based timers. - -## Security Considerations -All contracts introducing support for the Forwarded requests thereby authorize this contract to perform any operation under any account. -It is critical that this contract has no vulnerabilities or centralization issues. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2770.md diff --git a/EIPS/eip-2771.md b/EIPS/eip-2771.md index 9fb1ba84e03cf8..4d87023ef42f2b 100644 --- a/EIPS/eip-2771.md +++ b/EIPS/eip-2771.md @@ -1,140 +1,7 @@ --- eip: 2771 -title: Secure Protocol for Native Meta Transactions -description: A contract interface for receiving meta transactions through a trusted forwarder -author: Ronan Sandford (@wighawag), Liraz Siri (@lirazsiri), Dror Tirosh (@drortirosh), Yoav Weiss (@yoavw), Alex Forshtat (@forshtat), Hadrien Croubois (@Amxx), Sachin Tomar (@tomarsachin2271), Patrick McCorry (@stonecoldpat), Nicolas Venturo (@nventuro), Fabian Vogelsteller (@frozeman), Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/erc-2771-secure-protocol-for-native-meta-transactions/4488 -status: Final -type: Standards Track category: ERC -created: 2020-07-01 +status: Moved --- -## Abstract - -This EIP defines a contract-level protocol for `Recipient` contracts to accept meta-transactions through trusted `Forwarder` contracts. No protocol changes are made. `Recipient` contracts are sent the effective `msg.sender` (referred to as `_msgSender()`) and `msg.data` (referred to as `_msgData()`) by appending additional calldata. - -## Motivation - -There is a growing interest in making it possible for Ethereum contracts to accept calls from externally owned accounts that do not have ETH to pay for gas. Solutions that allow for third parties to pay for gas costs are called meta transactions. For the purposes of this EIP, meta transactions are transactions that have been authorized by a **Transaction Signer** and relayed by an untrusted third party that pays for the gas (the **Gas Relay**). - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Definitions - -**Transaction Signer**: Signs & sends transactions to a Gas Relay - -**Gas Relay**: Receives signed requests off-chain from Transaction Signers and pays gas to turn it into a valid transaction that goes through a Trusted Forwarder - -**Trusted Forwarder**: A contract trusted by the `Recipient` to correctly verify signatures and nonces before forwarding the request from Transaction Signers - -**Recipient**: A contract that accepts meta-transactions through a Trusted Forwarder - -### Example Flow - -![Example flow](../assets/eip-2771/example-flow.png) - -### Extracting The Transaction Signer address - -The **Trusted Forwarder** is responsible for calling the **Recipient** contract and MUST append the address of the **Transaction Signer** (20 bytes of data) to the end of the call data. - -For example : - -```solidity -(bool success, bytes memory returnData) = to.call.value(value)(abi.encodePacked(data, from)); -``` - -The **Recipient** contract can then extract the **Transaction Signer** address by performing 3 operations: - -1. Check that the **Forwarder** is trusted. How this is implemented is out of the scope of this proposal. -2. Extract the **Transaction Signer** address from the last 20 bytes of the call data and use that as the original `sender` of the transaction (instead of `msg.sender`) -3. If the `msg.sender` is not a trusted forwarder (or if the `msg.data` is shorter than 20 bytes), then return the original `msg.sender` as it is. - -The **Recipient** MUST check that it trusts the Forwarder to prevent it from -extracting address data appended from an untrusted contract. This could result -in a forged address. - -### Protocol Support Discovery Mechanism - -Unless a **Recipient** contract is being used by a particular frontend that knows that this contract has support for native meta transactions, it would not be possible to offer the user the choice of using meta-transaction to interact with the contract. We thus need a mechanism by which the **Recipient** can let the world know that it supports meta transactions. - -This is especially important for meta transactions to be supported at the Web3 wallet level. Such wallets may not necessarily know anything about the **Recipient** contract users may wish to interact with. - -As a **Recipient** could trust forwarders with different interfaces and capabilities (e.g., transaction batching, different message signing formats), we need to allow wallets to discover which Forwarder is trusted. - -To provide this discovery mechanism a **Recipient** contract MUST implement this function: - -```solidity -function isTrustedForwarder(address forwarder) external view returns(bool); -``` - -`isTrustedForwarder` MUST return `true` if the forwarder is trusted by the Recipient, otherwise it MUST return `false`. `isTrustedForwarder` MUST NOT revert. - -Internally, the **Recipient** MUST then accept a request from forwarder. - -`isTrustedForwarder` function MAY be called on-chain, and as such gas restrictions MUST be put in place. It SHOULD NOT consume more than 50,000 gas - -## Rationale - -* Make it easy for contract developers to add support for meta - transactions by standardizing the simplest viable contract interface. -* Without support for meta transactions in the recipient contract, an externally owned - account can not use meta transactions to interact with the recipient contract. -* Without a standard contract interface, there is no standard way for a client - to discover whether a recipient supports meta transactions. -* Without a standard contract interface, there is no standard way to send a - meta transaction to a recipient. -* Without the ability to leverage a trusted forwarder every recipient contract - has to internally implement the logic required to accept meta transactions securely. -* Without a discovery protocol, there is no mechanism for a client to discover - whether a recipient supports a specific forwarder. -* Making the contract interface agnostic to the internal implementation - details of the trusted forwarder, makes it possible for a recipient contract - to support multiple forwarders with no change to code. -* `msg.sender` is a transaction parameter that can be inspected by a contract to determine who signed the transaction. The integrity of this parameter is guaranteed by the Ethereum EVM, but for a meta transaction securing `msg.sender` is insufficient. - * The problem is that for a contract that is not natively aware of meta transactions, the `msg.sender` of the transaction will make it appear to be coming from the **Gas Relay** and not the **Transaction Signer**. A secure protocol for a contract to accept meta transactions needs to prevent the **Gas Relay** from forging, modifying or duplicating requests by the **Transaction Signer**. - -## Reference Implementation - -### Recipient Example - -```solidity -contract RecipientExample { - - function purchaseItem(uint256 itemId) external { - address sender = _msgSender(); - // ... perform the purchase for sender - } - - address immutable _trustedForwarder; - constructor(address trustedForwarder) internal { - _trustedForwarder = trustedForwarder; - } - - function isTrustedForwarder(address forwarder) public returns(bool) { - return forwarder == _trustedForwarder; - } - - function _msgSender() internal view returns (address payable signer) { - signer = msg.sender; - if (msg.data.length>=20 && isTrustedForwarder(signer)) { - assembly { - signer := shr(96,calldataload(sub(calldatasize(),20))) - } - } - } - -} -``` - -## Security Considerations - -A malicious forwarder may forge the value of `_msgSender()` and effectively send transactions from any address. Therefore, `Recipient` contracts must be very careful in trusting forwarders. If a forwarder is upgradeable, then one must also trust that the contract won't perform a malicious upgrade. - -In addition, modifying which forwarders are trusted must be restricted, since an attacker could "trust" their own address to forward transactions, and therefore be able to forge transactions. It is recommended to have the list of trusted forwarders be immutable, and if this is not feasible, then only trusted contract owners should be able to modify it. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2771.md diff --git a/EIPS/eip-2780.md b/EIPS/eip-2780.md index 3c75c91340940d..175d1e541c90cf 100644 --- a/EIPS/eip-2780.md +++ b/EIPS/eip-2780.md @@ -42,7 +42,7 @@ not by imposing artificial restrictions to encourage it. Reducing the intrinsic cost of a transaction from `21,000` to `7,000` gas will make sending transactions cheaper, is easily achievable, and does not incur technical debt. -However, such a change should only be made after it is determined that it does not impose non-negligble externalities, specifically: +However, such a change should only be made after it is determined that it does not impose non-negligible externalities, specifically: * Increases uncle-rate. diff --git a/EIPS/eip-2848.md b/EIPS/eip-2848.md index 5212f677e59255..e1bf77a5c8cf0e 100644 --- a/EIPS/eip-2848.md +++ b/EIPS/eip-2848.md @@ -1,202 +1,7 @@ --- eip: 2848 -title: My Own Messages (MOM) -author: Giuseppe Bertone (@Neurone) -discussions-to: https://github.com/InternetOfPeers/EIPs/issues/1 -status: Stagnant -type: Standards Track category: ERC -created: 2020-08-02 +status: Moved --- -## Simple Summary - -My Own Messages (MOM) is a standard to create your very own public, always updated, unstoppable, verifiable, message board. - -## Abstract - -My Own Messages (MOM) use Ethereum as a certification layer for commands and multihash of your messages. It don't use smart contracts but simple self-send transactions with specific payload attached. - -To ge more insights, you can test a [live client](http://internetofpeers.org/mom-client/), watch a [full video overview and demo](https://www.youtube.com/watch?v=z1SnoQkQYkU) and read a [brief presentation](../assets/eip-2848/presentation.pdf). - -## Motivation - -As a _developer_ or _pool's owner_, I'd like to send messages to my users in a decentralized way. They must be able to easily verify my role in the smart contract context (owner, user, and so on) and they must be able to do it without relying on external, insecure and hackable social media sites (Facebook, Twitter, you name it). Also, I'd like to read messages from my userbase, in the same secure and verifiable manner. - -As a _user_, I want a method to easily share my thoughts and idea, publish content, send messages, receive feedback, receive tips, and so on, without dealing with any complexity: just write a message, send it and it's done. Also, I want to write to some smart contract's owner or to the sender of some transaction. - -As an _explorer service_, I want to give my users an effective way to read information by smart contract owners and a place to share ideas and information without using third party services (i.e. Etherscan uses Disqus, and so on) - -And in _any role_, I want a method that does not allow scams - transactions without values, no smart contract's address to remember or to fake - and it does not allow spam - it's cheap but not free, and even if you can link/refer other accounts, you cannot send them messages directly, and others must explicitly follow and listen to your transactions if they want to read your messages. - -Main advantages: - -- You can send messages to users of your ÐApp or Smart Contract, and they always know it is a voice reliable as the smart contract is. -- Create your Ethereum account dedicated to your personal messages, say something only once and it can be seen on every social platform (no more reply of the same post/opinion on dozens of sites like Reddit, Twitter, Facebook, Medium, Disqus, and so on...) -- Small fee to be free: pay just few cents of dollar to notarize your messages, and distribute them with IPFS, Swarm or any other storage you prefer. Because the multihash of the content is notarized, you can always check the integrity of the message you download even from centralized storage services. -- Finally, you can ask and get tips for your words directly into your wallet. - -I know, My Own Messages (MOM) sounds like _mom_. And yes, pun intended :) - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) when, and only when, they appear in all capitals as shown here. - -Clients following MOM standard **MUST** allow users to send and to read MOM transaction, creating an _updated message list_ for each address the users are interested in. - -Reading MOM transactions, MOM clients **MUST** be able to show the current and updated message list, and they **SHOULD** be able to show also all the message history if users ask for it. - -Apart from message list, MOM clients **SHOULD** be able to download the content of the messages and to show them to the user. - -Clients **SHOULD** allow users to choose and set the source to download content from, and they **SHOULD** be able to use common Content Addressable Networks - i.e. IPFS or Swarm - or HTTP servers. If content is downloaded from HTTP servers, clients **MUST** check the content against the declared multihash. - -As the default setting, clients **MUST** consider `text/markdown` ([RFC 7763](https://www.ietf.org/rfc/rfc7763.txt)) as the media type of the content represented by a multihash, and in particular [Markdown](https://en.wikipedia.org/wiki/Markdown) text in [UTF-8](https://en.wikipedia.org/wiki/UTF-8) without [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). - -Clients **MAY** let users choose to parse messages considering other content types. In this case they **SHOULD** cast a warning to users stating that a content type other than `text/markdown` is used while processing messages. - -It's **RECOMMENDED** that clients inform users about the actual setting of the default content type. - -### MOM transactions - -Clients **MUST** assume that **invalid MOM transactions don't exist**. If a transaction does not strictly follow the MOM standard, clients **MUST** ignore it and they **MUST NOT** consider it a MOM transaction at all. - -Because there can be security implications parsing data sent by users, clients **SHOULD NOT** try to keep track or interpret transactions as _invalid_ MOM transactions. - -#### Valid MOM transaction's data structure - -| ATTRIBUTE | VALUE | -|:--------|:------------| -| `to` | **MUST** be the same account signing the transaction. | -| `value` | **MUST** be `0` wei. | -| `data` | **MUST** be at least `2` bytes. The first byte **MUST** be operational code and following bytes **MUST** be based on the operational codes listed below. | - -#### List of supported operations and messages - -Each operational code has one or more parameters, and all parameters **MUST** be considered mandatory. - -Optional parameters don't exist: if parameters for the specific operational code are not all present or they don't follow the rules, clients **MUST** ignore the transaction completely. - -Messages **MUST** be always referenced with the multihash of their content. - -Operations are divided into two sets: **CORE** and **EXTENDED** operations. - -- Clients **MUST** support all core operations and they **SHOULD** support as much extended operations as possible. -- Clients **SHOULD** support and implement as much extended operations as possible, but they **MAY** choose to implement only some specific extended operations they are interested in. - -#### Core operations - -| OPERATION | CODE | PARAMETERS | MEANING | EFFECT | -|-----------|:--------:|------------|---------|--------| -| ADD | `0x00` | multihash | Add a message. The parameter **MUST** be the multihash of the message. | Clients **MUST** add the message to the message list of the sender. | -| UPDATE | `0x01` | multihash, multihash | Update a message. The first parameter **MUST** be the multihash of the message to be updated. The second parameter **MUST** be the multihash of the updated message. | Clients **MUST** update the message list to show the updated message. | -| REPLY | `0x02` | multihash, multihash | Reply to a message. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. | -| DELETE | `0x03` | multihash | Delete a message. The parameter **MUST** be the multihash of the message to delete. | Clients **MUST** remove the message from the message list. | -| CLOSE ACCOUNT | `0xFD` | multihash | Close an account. The parameter **MUST** be the multihash of the message with the motivations for closing the account. | Clients **MUST** add the message with motivations to the message list and they **MUST NOT** consider MOM messages sent by that address to be valid anymore, ever. In other words, MOM clients **MUST** ignore any other transaction sent by that address while creating the message list. This is useful when users want to change account, for example because the private key seems compromised. | -| RAW | `0xFF` | any | The parameter **MUST** be at least `1` byte. Content type is not disclosed and it **MUST NOT** be considered as `text/markdown`. | Clients **MUST** add the message to the message list but they **MUST NOT** try to decode the content. Clients **SHOULD** allow users to see this message only if explicitly asked for. This operation can be used for _blind_ notarization that general client can ignore. | - -#### Note about `DELETE` operational code - -Please note that sending a `DELETE` command users are not asking to actually delete anything from the blockchain, they are just asking clients to hide that specific message because it's not valid anymore for some reasons. You can think of it like if users say: _I changed my mind so please ÐApps don't show this anymore_. As already stated in the specifications above, clients **MUST** follow this request by the author, unless expressly asked otherwise by the user. - -Please also note that, because it's usually up to the author of a message to be sure the content is available to everyone, if a `DELETE` message was sent it's very likely the content referenced by the multihash isn't available anymore, simply because probably it's not shared by anyone. - -#### Extended operations - -| OPERATION | CODE | PARAMETERS | MEANING | EFFECT | -|-----------|:--------:|------------|---------|--------| -| ADD & REFER | `0x04` | multihash, address | Add a message and refer an account. The first parameter **MUST** be the multihash of the message. The second parameter **MUST** be an address referenced by the message. | Clients **MUST** add the message to the message list and they **MUST** track the reference to the specified account. This can be useful _to invite_ the owner of the referenced account to read this specific message. | -| UPDATE & REFER | `0x05` | multihash, multihash, address | Update a message. The first parameter **MUST** be the multihash of the message to be updated. The second parameter **MUST** be the multihash of the updated message. The third parameter **MUST** be an address referenced by the message.| Clients **MUST** update the message list to show the updated message and they **MUST** track the reference to the specified account. This can be useful _to invite_ the owner of the referenced account to read this specific message. | -| ENDORSE | `0x06` | multihash | Endorse a message identified by the specified multihash. The parameter **MUST** be the multihash of the message to be endorsed. | Clients **MUST** record and track the endorsement for that specific message. Think it as a _like_, a _retwitt_, etc. | -| REMOVE ENDORSEMENT | `0x07` | multihash | Remove endorsement to the message identified by the specified multihash. The parameter **MUST** be the multihash of the message. | Clients **MUST** remove the endorsement for that specific message. | -| DISAPPROVE | `0x08` | multihash | Disapprove a message identified by the specified multihash. The parameter **MUST** be the multihash of the message to disapprove. | Clients **MUST** record and track the disapproval for that specific message. Think it as a _I don't like it_. | -| REMOVE DISAPPROVAL | `0x09` | multihash | Remove disapproval of a message identified by the specified multihash. The parameter **MUST** be the multihash of the message. | Clients **MUST** remove the disapproval for that specific message. | -| ENDORSE & REPLY | `0x0A` | multihash, multihash | Endorse a message and reply to it. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** be the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. Clients **MUST** also record and track the endorsement for that specific message. | -| DISAPPROVE & REPLY | `0x0B` | multihash, multihash | Disapprove a message and reply to it. The first parameter **MUST** be the multihash of the message to reply to. The second parameter **MUST** be the multihash of the message. | Clients **MUST** insert a new message in the message list and they **MUST** preserve the relationship with the referenced message. Clients **MUST** also record and track the disapproval for that specific message. | - -## Rationale - -Ethereum is _account based_, so it's good to be identified as a single source of information. - -It is also able of doing notarization very well and to impose some restrictions on transaction's structure, so it's good for commands. - -IPFS, Swarm or other CANs (Content Addressable Networks) or storage methods are good to store a lot of information. So, the union of both worlds it's a good solution to achieve the objectives of this message standard. - -The objective is also to avoid in the first place any kind of scam and malicious behaviors, so MOM don't allow to send transactions to other accounts and the value of a MOM transaction is always 0. - -### Why not using a smart contract? - -MOM wants to be useful, easy to implement and read, error proof, fast and cheap, but: - -- using a smart contract for messages can leads more easily to errors and misunderstandings: - - address of the contract can be wrong - - smart contract must be deployed on that specific network to send messages -- executing a smart contract costs much more than sending transactions -- executing a smart contract just to store static data is the best example of an anti-pattern (expensive and almost useless) - -Without a specific smart contract to rely on, the MOM standard can be implemented and used right now in any existing networks, and even in future ones. - -Finally, if you can achieve exactly the same result without a smart contract, you didn't need a smart contract at the first place. - -### Why not storing messages directly on-chain? - -There's no benefit to store _static_ messages on-chain, if they are not related to some smart contract's state or if they don't represent exchange of value. The cost of storing data on-chain is also very high. - -### Why not storing op codes inside the message? - -While cost effectiveness is a very important feature in a blockchain related standard, there's also a compromise to reach with usability and usefulness. - -Storing commands inside the messages forces the client to actually download messages to understand what to do with them. This is very inefficient, bandwidth and time consuming. - -Being able to see the commands before downloading the content, it allows the client to recreate the history of all messages and then, at the end, download only updated messages. - -Creating a structure for the content of the messages leads to many issues and considerations in parsing the content, if it's correct, misspelled, and so on. - -Finally, the **content must remain clean**. You really want to notarize the content and not to refer to a data structure, because this can lead to possible false-negative when checking if a content is the same of another. - -### Why multihash? - -[Multihash](https://github.com/multiformats/multihash) is flexible, future-proof and there are already tons of library supporting it. Ethereum must be easily integrable with many different platforms and architectures, so MOM standard follows that idea. - -## Backwards Compatibility - -You can already find few transactions over the Ethereum network that use a pattern similar to this EIP. Sometimes it's done to invalidate a previous transaction in memory pool, using the same nonce but with more gas price, so that transaction is mined cancelling the previous one still in the memory pool. This kind of transactions can be easily ignored if created before the approval of this EIP or just checking if the payload follows the correct syntax. - -## Test Cases - -A MOM-compliant client can be found and tested on [GitHub](https://github.com/InternetOfPeers/mom-client). - -You can use the latest version of MOM client directly via [GitHub Pages](https://internetofpeers.github.io/mom-client) or via IPFS (see the [client repo](https://github.com/InternetOfPeers/mom-client) for the latest updated address). - -## Implementation - -You can use an already working MOM JavaScript package on [GitHub Packages](https://github.com/InternetOfPeers/mom-js/packages/323930) or [npmjs](https://www.npmjs.com/package/@internetofpeers/mom-js). The package is already used by the MOM client above, and you can use it in your ÐApps too with: - -```bash -npm install @internetofpeers/mom-js -``` - -Transaction [`0x8e49485c56897757a6f2707b92cd5dad06126afed92261b9fe1a19b110bc34e6`](https://etherscan.io/tx/0x8e49485c56897757a6f2707b92cd5dad06126afed92261b9fe1a19b110bc34e6) is an example of a valid MOM transaction already mined on the Main net; it's an `ADD` message. - -## Security Considerations - -MOM is very simple and it has no real security concerns by itself. The standard already considers valid only transactions with `0` value and where `from` and `to` addresses are equals. - -The only concerns can come from the payload, but it is more related to the client and not to the standard itself, so here you can find some security suggestions related to clients implementing the standard. - -### Parsing commands - -MOM standard involves parsing payloads generated by potentially malicious clients, so attention must be made to avoid unwanted code execution. - -- Strictly follow only the standard codes -- Don't execute any commands outside of the standard ones, unless expressly acknowledged by the user -- Ignore malformed transactions (transactions that don't strictly follow the rules) - -### Messages - -Default content-type of a message following the MOM standard is Markdown text in UTF8 without BOM. It is highly recommended to disallow the reading of any not-text content-type, unless expressly acknowledged by the user. - -Because content multihash is always stored into the chain, clients can download that content from Content Addressable Network (like IPFS or Swarm) or from central servers. In the latter case, a client should always check the integrity of the received messages, or it must warn the user if it cannot do that (feature not implemented or in error). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2848.md diff --git a/EIPS/eip-2876.md b/EIPS/eip-2876.md index e2b55e433260fb..0edca2a8be05ce 100644 --- a/EIPS/eip-2876.md +++ b/EIPS/eip-2876.md @@ -1,184 +1,7 @@ --- eip: 2876 -title: Deposit contract and address standard -author: Jonathan Underwood (@junderw) -discussions-to: https://github.com/junderw/deposit-contract-poc/issues/1 -status: Stagnant -type: Standards Track category: ERC -created: 2020-08-13 +status: Moved --- -## Simple Summary -This ERC defines a simple contract interface for managing deposits. It also defines a new address format that encodes the extra data passed into the interface's main deposit function. - -## Abstract -An ERC-2876 compatible **deposit system** can accept ETH payments from multiple depositors without the need for managing multiple keys or requiring use of a hot wallet. - -An ERC-2876 compatible **wallet application** can send ETH to ERC-2876 compatible **deposit systems** in a way that the **deposit system** can differentiate their payment using the 8 byte id specified in this standard. - -Adoption of ERC-2876 by all exchanges (as a deposit system and as a wallet for their withdrawal systems), merchants, and all wallet applications/libraries will likely decrease total network gas usage by these systems, since two value transactions cost 42000 gas while a simple ETH forwarding contract will cost closer to 30000 gas depending on the underlying implementation. - -This also has the benefit for deposit system administrators of allowing for all deposits to be forwarded to a cold wallet directly without any manual operations to gather deposits from multiple external accounts. - -## Motivation -Centralized exchanges and merchants (Below: "apps") require an address format for accepting deposits. Currently the address format used refers to an account (external or contract), but this creates a problem. It requires that apps create a new account for every invoice / user. If the account is external, that means the app must have the deposit addresses be hot wallets, or have increased workload for cold wallet operators (as each deposit account will create 1 value tx to sweep). If the account is contract, generating an account costs at least 60k gas for a simple proxy, which is cost-prohibitive. - -Therefore, merchant and centralized exchange apps are forced between taking on one of the following: - -- Large security risk (deposit accounts are hot wallets) -- Large manual labor cost (cold account manager spends time sweeping thousands of cold accounts) -- Large service cost (deploying a contract-per-deposit-address model). - -The timing of this proposal is within the context of increased network gas prices. During times like this, more and more services who enter the space are being forced into hot wallets for deposits, which is a large security risk. - -The motivation for this proposal is to lower the cost of deploying and managing a system that accepts deposits from many users, and by standardizing the methodology for this, services across the world can easily use this interface to send value to and from each other without the need to create multiple accounts. - -## Specification - -### Definitions -- The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. -- `The contract interface` is the contract component of this ERC. -- `The deposit address format` is the newly made format described in "Deposit Address Format" for encoding the 20 byte account address and the 8 byte id. -- `The contract` refers to the contract that implements `the contract interface` of this ERC. -- `The 8 byte "id"` is an 8 byte id used as the input parameter for the contract interface. -- `The 5 byte "nonce"` is the first 5 most significant bytes of the `"id"`. -- `The 3 byte "checksum"` is the last 3 least significant bytes of the `"id"` -- `deposit(bytes8)` refers to the function of that signature, which is defined in `the contract interface`. -- `The parent application` refers to the application that will use the information gained within the `deposit(bytes8)` function. (ie. an exchange backend or a non-custodial merchant application) -- `The depositor` refers to the person that will send value to `the contract` via the `deposit(bytes8)` call. -- `The wallet` refers to any application or library that sends value transactions upon the request of `the depositor`. (ie. MyEtherWallet, Ledger, blockchain.com, various libraries) - -### Deposit Address Format - -In order to add the 8 byte "id" data, we need to encode it along with the 20 byte -account address. The 8 bytes are appended to the 20 byte address. - -A 3 byte checksum is included in the id, which is the first 3 bytes of the keccak256 -hash of the 20 byte address and first 5 byte nonce of the id concatenated (25 bytes). - -The Deposit Address format can be generated with the following JavaScript code: - -```js -/** - * Converts a 20 byte account address and a 5 byte nonce to a deposit address. - * The format of the return value is 28 bytes as follows. The + operator is byte - * concatenation. - * (baseAddress + nonce + keccak256(baseAddress + nonce)[:3]) - * - * @param {String} baseAddress the given HEX address (20 byte hex string with 0x prepended) - * @param {String} nonce the given HEX nonce (5 byte hex string with 0x prepended) - * @return {String} - */ -function generateAddress (baseAddress, nonce) { - if ( - !baseAddress.match(/^0x[0-9a-fA-F]{40}$/) || - !nonce.match(/^0x[0-9a-fA-F]{10}$/) - ) { - throw new Error('Base Address and nonce must be 0x hex strings'); - } - const ret = - baseAddress.toLowerCase() + nonce.toLowerCase().replace(/^0x/, ''); - const myHash = web3.utils.keccak256(ret); - return ret + myHash.slice(2, 8); // first 3 bytes from the 0x hex string -}; -``` - -The checksum can be verified within the deposit contract itself using the following: - -```solidity -function checksumMatch(bytes8 id) internal view returns (bool) { - bytes32 chkhash = keccak256( - abi.encodePacked(address(this), bytes5(id)) - ); - bytes3 chkh = bytes3(chkhash); - bytes3 chki = bytes3(bytes8(uint64(id) << 40)); - return chkh == chki; -} -``` - -### The Contract Interface - -A contract that follows this ERC: - -- `The contract` MUST revert if sent a transaction where `msg.data` is null (A pure value transaction). -- `The contract` MUST have a deposit function as follows: - -```solidity -interface DepositEIP { - function deposit(bytes8 id) external payable returns (bool); -} -``` - -- `deposit(bytes8)` MUST return `false` when the contract needs to keep the value, but signal to the depositor that the deposit (in terms of the parent application) itself has not yet succeeded. (This can be used for partial payment, ie. the invoice is for 5 ETH, sending 3 ETH returns false, but sending a second tx with 2 ETH will return true.) -- `deposit(bytes8)` MUST revert if the deposit somehow failed and the contract does not need to keep the value sent. -- `deposit(bytes8)` MUST return `true` if the value will be kept and the payment is logically considered complete by the parent application (exchange/merchant). -- `deposit(bytes8)` SHOULD check the checksum contained within the 8 byte id. (See "Deposit Address Format" for an example) -- `The parent application` SHOULD return any excess value received if the deposit id is a one-time-use invoice that has a set value and the value received is higher than the set value. However, this SHOULD NOT be done by sending back to `msg.sender` directly, but rather should be noted in the parent application and the depositor should be contacted out-of-band to the best of the application manager's ability. - -### Depositing Value to the Contract from a Wallet - -- `The wallet` MUST accept `the deposit address format` anywhere the 20-byte address format is accepted for transaction destination. -- `The wallet` MUST verify the 3 byte checksum and fail if the checksum doesn't match. -- `The wallet` MUST fail if the destination address is `the deposit address format` and the `data` field is set to anything besides null. -- `The wallet` MUST set the `to` field of the underlying transaction to the first 20 bytes of the deposit address format, and set the `data` field to `0x3ef8e69aNNNNNNNNNNNNNNNN000000000000000000000000000000000000000000000000` where `NNNNNNNNNNNNNNNN` is the last 8 bytes of the deposit address format. (ie. if the deposit address format is set to `0x433e064c42e87325fb6ffa9575a34862e0052f26913fd924f056cd15` then the `to` field is `0x433e064c42e87325fb6ffa9575a34862e0052f26` and the `data` field is `0x3ef8e69a913fd924f056cd15000000000000000000000000000000000000000000000000`) - -## Rationale -The contract interface and address format combination has one notable drawback, which was brought up in discussion. This ERC can only handle deposits for native value (ETH) and not other protocols such as ERC-20. However, this is not considered a problem, because it is best practice to logically AND key-wise separate wallets for separate currencies in any exchange/merchant application for accounting reasons and also for security reasons. Therefore, using this method for the native value currency (ETH) and another method for ERC-20 tokens etc. is acceptable. Any attempt at doing something similar for ERC-20 would require modifying the ERC itself (by adding the id data as a new input argument to the transfer method etc.) which would grow the scope of this ERC too large to manage. However, if this address format catches on, it would be trivial to add the bytes8 id to any updated protocols (though adoption might be tough due to network effects). - -The 8 byte size of the id and the checksum 3 : nonce 5 ratio were decided with the following considerations: - -- 24 bit checksum is better than the average 15 bit checksum of an EIP-55 address. -- 40 bit nonce allows for over 1 trillion nonces. -- 64 bit length of the id was chosen as to be long enough to support a decent checksum and plenty of nonces, but not be too long. (Staying under 256 bits makes hashing cheaper in gas costs as well.) - -## Backwards Compatibility -An address generated with the deposit address format will not be considered a valid address for applications that don't support it. If the user is technical enough, they can get around lack of support by verifying the checksum themselves, creating the needed data field by hand, and manually input the data field. (assuming the wallet app allows for arbitrary data input on transactions) A tool could be hosted on github for users to get the needed 20 byte address and msg.data field from a deposit address. - -Since a contract following this ERC will reject any plain value transactions, there is no risk of extracting the 20 byte address and sending to it without the calldata. - -However, this is a simple format, and easy to implement, so the author of this ERC will first implement in web3.js and encourage adoption with the major wallet applications. - -## Test Cases -``` -[ - { - "address": "0x083d6b05729c58289eb2d6d7c1bb1228d1e3f795", - "nonce": "0xbdd769c69b", - "depositAddress": "0x083d6b05729c58289eb2d6d7c1bb1228d1e3f795bdd769c69b3b97b9" - }, - { - "address": "0x433e064c42e87325fb6ffa9575a34862e0052f26", - "nonce": "0x913fd924f0", - "depositAddress": "0x433e064c42e87325fb6ffa9575a34862e0052f26913fd924f056cd15" - }, - { - "address": "0xbbc6597a834ef72570bfe5bb07030877c130e4be", - "nonce": "0x2c8f5b3348", - "depositAddress": "0xbbc6597a834ef72570bfe5bb07030877c130e4be2c8f5b3348023045" - }, - { - "address": "0x17627b07889cd22e9fae4c6abebb9a9ad0a904ee", - "nonce": "0xe619dbb618", - "depositAddress": "0x17627b07889cd22e9fae4c6abebb9a9ad0a904eee619dbb618732ef0" - }, - { - "address": "0x492cdf7701d3ebeaab63b4c7c0e66947c3d20247", - "nonce": "0x6808043984", - "depositAddress": "0x492cdf7701d3ebeaab63b4c7c0e66947c3d202476808043984183dbe" - } -] -``` - -## Implementation -A sample implementation with an example contract and address generation (in the tests) is located here: - -https://github.com/junderw/deposit-contract-poc - -## Security Considerations -In general, contracts that implement the contract interface should forward funds received to the deposit(bytes8) function to their cold wallet account. This address SHOULD be hard coded as a constant OR take advantage of the `immutable` keyword in solidity versions `>=0.6.5`. - -To prevent problems with deposits being sent after the parent application is shut down, a contract SHOULD have a kill switch that will revert all calls to deposit(bytes8) rather than using `selfdestruct(address)` (since users who deposit will still succeed, since an external account will receive value regardless of the calldata, and essentially the self-destructed contract would become a black hole for any new deposits) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2876.md diff --git a/EIPS/eip-2917.md b/EIPS/eip-2917.md index cc88c591047469..8ff04516b1ce20 100644 --- a/EIPS/eip-2917.md +++ b/EIPS/eip-2917.md @@ -1,165 +1,7 @@ --- eip: 2917 -title: Staking Reward Calculation -author: Tony Carson , Mehmet Sabir Kiraz , Süleyman Kardaş -discussions-to: https://github.com/ethereum/EIPs/issues/2925 -status: Stagnant -type: Standards Track category: ERC -created: 2020-08-28 +status: Moved --- -## Simple Summary -ERC2917 is a new standardization for on-chain calculation of staking reward. - -## Abstract -Based on the product of effective collateral and time, ERC2917 calculates the reward a user can get at any time, and realize the real decentralized DeFi. Here below is the formula for the calculation of reward for a user U: - -![concept image](../assets/eip-2917/erc-reward-formula.png "erc-reward-formula") - -where ∆pi denotes individual productivity of the user U between the consecutive block numbers ti-1 and ti, ∆Pi denotes global productivity between the consecutive block numbers ti-1 and ti, and ∆Gi denotes gross product between the consecutive block numbers ti-1 and ti. The formula ensures that there is no benefit in case of exiting earlier or entering later in the computation. The reward a user can get for a period is based on his total productivity during that specific time. The formula has been simplified through Solidity and generalized design to make it available across all DeFi products. -We note that the smart contract can be triggered for every computation of on the following events: -- whenever the productivity of a user changes (increase/decrease), -- whenever a user withdraws. - -## Motivation - -One of the main drawbacks of many DeFi projects is the reward distribution mechanism within the smart contract. In fact, there are two main mechanisms are adopted so far. -1. Distribution of rewards is only given when all users exit the contract -2. The project collects on-chain data, conducts calculation off-chain, and sends the results -to the chain before starting rewards distribution accordingly - -The first approach conducts all calculation in an on-chain fashion, the cycle of its rewards distribution is too long. Furthermore, users need to remove their collateral before getting the rewards, which can be harmful for their rewards. The second approach is a semi-decentralized model since the main algorithm involves an off-chain computation. Therefore, the fairness and transparency properties cannot be reflected and this can even create the investment barrier for users. - -Since there is more DeFi projects coming out everyday, users could not find a proper way to get to know: -1) amount of interests he/she would get -2) how the interest calculated -3) what is his/her contribution compare to the overall - -By standardizing ERC2917, it abstracts the interface for interests generation process. Making wallet applications easier to collect each DeFi's metrics, user friendlier. - -## Specification - -Every ERC-2917 compliant contract must implement the ERC2917 and ERC20 interfaces (if necessary): - -```solidity -interface IERC2917 is IERC20 { - - /// @dev This emit when interests amount per block is changed by the owner of the contract. - /// It emits with the old interests amount and the new interests amount. - event InterestRatePerBlockChanged (uint oldValue, uint newValue); - - /// @dev This emit when a users' productivity has changed - /// It emits with the user's address and the the value after the change. - event ProductivityIncreased (address indexed user, uint value); - - /// @dev This emit when a users' productivity has changed - /// It emits with the user's address and the the value after the change. - event ProductivityDecreased (address indexed user, uint value); - - - /// @dev Return the current contract's interests rate per block. - /// @return The amount of interests currently producing per each block. - function interestsPerBlock() external view returns (uint); - - /// @notice Change the current contract's interests rate. - /// @dev Note the best practice will be restrict the gross product provider's contract address to call this. - /// @return The true/false to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. - function changeInterestRatePerBlock(uint value) external returns (bool); - - /// @notice It will get the productivity of given user. - /// @dev it will return 0 if user has no productivity proved in the contract. - /// @return user's productivity and overall productivity. - function getProductivity(address user) external view returns (uint, uint); - - /// @notice increase a user's productivity. - /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. - /// @return true to confirm that the productivity added success. - function increaseProductivity(address user, uint value) external returns (bool); - - /// @notice decrease a user's productivity. - /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. - /// @return true to confirm that the productivity removed success. - function decreaseProductivity(address user, uint value) external returns (bool); - - /// @notice take() will return the interests that callee will get at current block height. - /// @dev it will always calculated by block.number, so it will change when block height changes. - /// @return amount of the interests that user are able to mint() at current block height. - function take() external view returns (uint); - - /// @notice similar to take(), but with the block height joined to calculate return. - /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. - /// @return amount of interests and the block height. - function takeWithBlock() external view returns (uint, uint); - - /// @notice mint the available interests to callee. - /// @dev once it mint, the amount of interests will transfer to callee's address. - /// @return the amount of interests minted. - function mint() external returns (uint); -} -``` - -### InterestRatePerBlockChanged - -This emit when interests amount per block is changed by the owner of the contract. It emits with the old interests amount and the new interests amount. - - -### ProductivityIncreased - -It emits with the user's address and the the value after the change. - - -### ProductivityDecreased - -It emits with the user's address and the the value after the change. - -### interestsPerBlock - -It returns the amount of interests currently producing per each block. - -### changeInterestRatePerBlock - -Note the best practice will be restrict the gross product provider's contract address to call this. - -The true/false to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. - -### getProductivity - -It returns user's productivity and overall productivity. It returns 0 if user has no productivity proved in the contract. - -### increaseProductivity - -It increases a user's productivity. - -### decreaseProductivity - -It decreases a user's productivity. - -### take - -It returns the interests that callee will get at current block height. - -### takeWithBlock - -Similar to take(), but with the block height joined to calculate return. - -For instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. - -It returns amount of interests and the block height. - -### mint -it mints the amount of interests will transfer to callee's address. It returns the amount of interests minted. - -## Rationale -TBD - -## Implementation -The implementation code is on the github: - -- [ERC2917 Demo](https://github.com/gnufoo/ERC3000-Proposal) - -## Security Considerations -TBD - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2917.md diff --git a/EIPS/eip-2935.md b/EIPS/eip-2935.md index bbe12f21b04e06..68d54a80a4f5b9 100644 --- a/EIPS/eip-2935.md +++ b/EIPS/eip-2935.md @@ -1,62 +1,218 @@ --- eip: 2935 -title: Save historical block hashes in state -author: Vitalik Buterin (@vbuterin), Tomasz Stanczak (@tkstanczak) +title: Serve historical block hashes from state +description: Store and serve last 8192 block hashes as storage slots of a system contract to allow for stateless execution +author: Vitalik Buterin (@vbuterin), Tomasz Stanczak (@tkstanczak), Guillaume Ballet (@gballet), Gajinder Singh (@g11tech), Tanishq Jasoria (@tanishqjasoria), Ignacio Hagopian (@jsign), Jochem Brouwer (@jochem-brouwer) discussions-to: https://ethereum-magicians.org/t/eip-2935-save-historical-block-hashes-in-state/4565 -status: Stagnant +status: Review type: Standards Track category: Core created: 2020-09-03 --- -## Simple Summary +## Abstract -Store historical block hashes in a contract, and modify the `BLOCKHASH (0x40)` opcode to read this contract. +Store last `HISTORY_SERVE_WINDOW` historical block hashes in the storage of a system contract as part of the block processing logic. Furthermore this EIP has no impact on `BLOCKHASH` resolution mechanism (and hence its range/costs etc). ## Motivation -There is increasingly a desire to remove the need for most clients to store history older than some relatively short duration (often between 1 week and 1 year) to save disk space. This requires some form of layer-2 network to help clients access historical information. These protocols can be made much simpler if blocks contained a quick Merkle path to historical blocks. +EVM implicitly assumes the client has the recent block (hashes) at hand. This assumption is not future-proof given the prospect of stateless clients. Including the block hashes in the state will allow bundling these hashes in the witness provided to a stateless client. This is already possible in the MPT and will become more efficient post-Verkle. -Additional secondary motivations include: +Extending the range of blocks which `BLOCKHASH` can serve (`BLOCKHASH_SERVE_WINDOW`) would have been a semantics change. Using extending that via this contract storage would allow a soft-transition. Rollups can benefit from the longer history window through directly querying this contract. -* The protocol can be used to make more secure efficient light clients with flyclient-like technology (while the "optimal" flyclient protocol is fairly complex, large security gains over the status quo (trusted "canonical hash trees") can be made cheaply) -* Improving cleanness of the protocol, as the BLOCKHASH opcode would then access state and not history. +A side benefit of this approach could be that it allows building/validating proofs related to last `HISTORY_SERVE_WINDOW` ancestors directly against the current state. ## Specification | Parameter | Value | | - | - | -| `FORK_BLKNUM` | TBD | -| `HISTORY_STORAGE_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe`| - -At the start of processing any block where `block.number > FORK_BLKNUM` (ie. before processing any transactions), run `sstore(HISTORY_STORAGE_ADDRESS, block.number - 1, block.prevhash)`. - -When `block.number > FORK_BLKNUM + 256`, change the logic of the `BLOCKHASH` opcode as follows: if `FORK_BLKNUM <= arg < block.number`, return `sload(HISTORY_STORAGE_ADDRESS, arg)`. Otherwise return 0. +| `FORK_TIMESTAMP` | TBD | +| `BLOCKHASH_SERVE_WINDOW` | `256` | +| `HISTORY_SERVE_WINDOW` | `8192` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `HISTORY_STORAGE_ADDRESS` | `0x0aae40965e6800cd9b1f4b05ff21581047e3f91e`| + +This EIP specifies for storing last `HISTORY_SERVE_WINDOW` block hashes in a ring buffer storage of `HISTORY_SERVE_WINDOW` length. Note that `HISTORY_SERVE_WINDOW` > `BLOCKHASH_SERVE_WINDOW` (which remains unchanged). + +At the start of processing any block where `block.timestamp >= FORK_TIMESTAMP` (ie. before processing any transactions), update the state directly in the following way: + +```python +def process_block_hash_history(block: Block, state: State): + if block.timestamp >= FORK_TIMESTAMP: + state.insert_slot(HISTORY_STORAGE_ADDRESS, (block.number-1) % HISTORY_SERVE_WINDOW , block.parent.hash) +``` + +Alternatively clients can also choose to do a system update via a system call to the contract `set` mechanism defined in the following sections. + +Note that, it will take `HISTORY_SERVE_WINDOW` blocks after `FORK_TIMESTAMP` to completely fill up the ring buffer. The contract will only contain the parent hash of the fork block and no hashes prior to that. + +As mentioned earlier the `BLOCKHASH` opcode semantics remains the same as before. However the clients which want to leverage the history from state may do so making sure the query is within `BLOCKHASH_SERVE_WINDOW` and is available in the contract. + +### Contract Implementation + +Exact evm assembly that can be used for the history contract: + +``` +// if system call then jump to the set operation +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x57 +jumpi + +// check if input > 8 byte value and revert if this isn't the case +// the check is performed by comparing the biggest 8 byte number with +// the call data, which is a right-padded 32 byte number. +push8 0xffffffffffffffff +push0 +calldataload +gt +push1 0x53 +jumpi + +// check if input > blocknumber-1 then return 0 +push1 0x1 +number +sub +push0 +calldataload +gt +push1 0x4b +jumpi + +// check if blocknumber > input + 8192 then return 0, no overflow expected for input of < max 8 byte value +push0 +calldataload +push2 0x2000 +add +number +gt +push1 0x4b +jumpi + +// mod 8192 and sload +push2 0x1fff +push0 +calldataload +and +sload + +// load into mem and return 32 bytes +push0 +mstore +push1 0x20 +push0 +return + +// 0x4b: return 0 +jumpdest +push0 +push0 +mstore +push1 0x20 +push0 +return + +// 0x53: revert +jumpdest +push0 +push0 +revert + +// 0x57: set op - sstore the input to number-1 mod 8192 +jumpdest +push0 +calldataload +push2 0x1fff +push1 0x1 +number +sub +and +sstore + +stop +``` + +Corresponding bytecode: +`0x3373fffffffffffffffffffffffffffffffffffffffe1460575767ffffffffffffffff5f3511605357600143035f3511604b575f35612000014311604b57611fff5f3516545f5260205ff35b5f5f5260205ff35b5f5ffd5b5f35611fff60014303165500` + +#### Contract `get` and `set` mechanism + +Similar to [EIP-4788](./eip-4788.md) above contract provides a `set` mechanism which clients can choose to update the block's parent hash in the ring buffer instead of direct state update. For this clients should call this contract with `SYSTEM_ADDRESS` as caller and provide `32` bytes parent block hash as input. + +If caller is not `SYSTEM_ADDRESS` the contract treats it as `get` with contract reading `32` bytes input via `calldataload` as the `arg` to resolve the block hash for. Users and clients doing `get` EVM call should left pad the `arg` correctly. + +#### Deployment + +A special synthetic address is generated by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x60648060095f395ff33373fffffffffffffffffffffffffffffffffffffffe1460575767ffffffffffffffff5f3511605357600143035f3511604b575f35612000014311604b57611fff5f3516545f5260205ff35b5f5f5260205ff35b5f5ffd5b5f35611fff60014303165500", + "v": "0x1b", + "r": "0x539", + "s": "0x1b9b6eb1f0", + "hash": "0x3c769a03d6e2212f1d26ab59ba797dce0900df29ffd23c1dd391fd6b217973ad", +} +``` + +Note, the input in the transaction has a simple constructor prefixing the desired runtime code. + +The sender of the transaction can be calculated as `0xe473f7e92ba2490e9fcbbe8bb9c3be3adbb74efc`. The address of the first contract deployed from the account is `rlp([sender, 0])` which equals `0x0aae40965e6800cd9b1f4b05ff21581047e3f91e`. This is how `HISTORY_STORAGE_ADDRESS` is determined. Although this style of contract creation is not tied to any specific initcode like create2 is, the synthetic address is cryptographically bound to the input data of the transaction (e.g. the initcode). + + +Some activation scenarios: + + * For the fork to be activated at genesis, no history is written to the genesis state, and at the start of block `1`, genesis hash will be written as a normal operation to slot `0`. + * for activation at block `1`, only genesis hash will be written at slot `0`. + * for activation at block `32`, block `31`'s hash will be written to slot `31`. Every other slot will be `0`. + +### [EIP-158](./eip-158.md) handling + +The bytecode above will be deployed à la [EIP-4788](./eip-4788.md). As such the account at `HISTORY_STORAGE_ADDRESS` will have code and a nonce of 1, and will be exempt from EIP-158 cleanup. + +### Gas costs + +The system update at the beginning of the block, i.e. `process_block_hash_history` (or via system call to the contract with `SYSTEM_ADDRESS` caller), will not warm the `HISTORY_STORAGE_ADDRESS` account or its storage slots as per [EIP-2929](./eip-2929.md) rules. As such the first call to the contract will pay for warming up the account and storage slots it accesses.To clarify further any contract call to the `HISTORY_STORAGE_ADDRESS` will follow normal EVM execution semantics. + +Since `BLOCKHASH` semantics doesn't change, this EIP has no impact on `BLOCKHASH` mechanism and costs. ## Rationale -Very similar ideas were proposed before in EIP-98 and EIP-210. This EIP is a simplification, removing two sources of needless complexity: +Very similar ideas were proposed before. This EIP is a simplification, removing two sources of needless complexity: 1. Having a tree-like structure with multiple layers as opposed to a single list 2. Writing the EIP in EVM code +3. Serial unbounded storage of hashes for a deep access to the history -The former was intended to save space. Since then, however, storage usage has increased massively, to the point where even eg. 5 million new storage slots are fairly negligible compared to existing usage. The latter was intended as a first step toward "writing the Ethereum protocol in EVM" as much as possible, but this goal has since been de-facto abandoned. +However after weighing pros and cons, we decided to go with just a limited ring buffer to only serve the requisite `HISTORY_SERVE_WINDOW` as [EIP-4788](./eip-4788.md) and beacon state accumulators allow (albeit a bit more complex) proof against any ancestor since merge. -## Backwards Compatibility +Second concern was how to best transition the BLOCKHASH resolution logic post fork by: -The range of `BLOCKHASH` is increased by this opcode, but behavior within the previous 256-block range remains unchanged. +1. Either waiting for `HISTORY_SERVE_WINDOW` blocks for the entire relevant history to persist +2. Storing of all last `HISTORY_SERVE_WINDOW` block hashes on the fork block. -## Test Cases +We choose to go with the former. It simplifies the logic greatly. It will take roughly a day to bootstrap the contract. Given that this is a new way of accessing history and no contract depends on it, it is deemed a favorable tradeoff. -TBD +## Backwards Compatibility -## Implementation +This EIP introduces backwards incompatible changes to the block validation rule set. But neither of these changes break anything related to current user activity and experience. + +## Test Cases TBD ## Security Considerations -Adding ~2.5 million storage slots per year bloats the state somewhat (but not much relative to the hundreds of millions of existing state objects). However, this EIP is not intended to be permanent; when eth1 is merged into eth2, the BLOCKHASH opcode would likely be repurposed to use eth2's built-in history accumulator structure (see [phase 0 spec](https://github.com/ethereum/annotated-spec/blob/master/phase0/beacon-chain.md#slots_per_historical_root)). +Having contracts (system or otherwise) with hot update paths (branches) poses a risk of "branch" poisioning attacks where attacker could sprinkle trivial amounts of eth around these hot paths (branches). But it has been deemed that cost of attack would escalate significantly to cause any meaningful slow down of state root updates. ## Copyright diff --git a/EIPS/eip-2942.md b/EIPS/eip-2942.md index ea2ec7e3fdb579..265660ceaee3b1 100644 --- a/EIPS/eip-2942.md +++ b/EIPS/eip-2942.md @@ -1,66 +1,7 @@ --- eip: 2942 -title: EthPM URI Specification -author: Nick Gheorghita (@njgheorghita), Piper Merriam (@pipermerriam), g. nicholas d'andrea (@gnidan), Benjamin Hauser (@iamdefinitelyahuman) -discussions-to: https://ethereum-magicians.org/t/ethpm-v3-specification-working-group/4086/7 -status: Stagnant -type: Standards Track category: ERC -created: 2020-09-04 -requires: 2678 +status: Moved --- -## Simple Summary -A custom URI scheme to identify an EthPM registry, package, release, or specific contract asset within a release. - -## Abstract -When interacting with the EthPM ecosystem, users and tooling can benefit from a URI scheme to identify EthPM assets. Being able to specify a package, registry, or release with a single string makes simplifies the steps required to install, publish, or distribute EthPM packages. - -## Specification -`scheme://registry_address[:chain_id][/package_name[@package_version[/json_pointer]]]` - -#### `scheme` -- Required -- Must be one of `ethpm` or `erc1319`. If future versions of the EthPM registry standard are designed and published via the ERC process, those ERCs will also be valid schemes. - -#### `registry_address` -- Required -- This **SHOULD** be either an ENS name or a 0x-prefixed, checksummed address. ENS names are more suitable for cases where mutability of the underlying asset is acceptable and there is implicit trust in the owner of the name. 0x prefixed addresses are more preferable in higher security cases to avoid needing to trust the controller of the name. - -#### `chain_id` -- Optional -- Integer representing the chain id on which the registry is located -- If omitted, defaults to `1` (mainnet). - -#### `package_name` -- Optional -- String of the target package name - -#### `package_version` -- Optional -- String of the target package version -- If the package version contains any [url unsafe characters](https://en.wikipedia.org/wiki/Percent-encoding), they **MUST** be safely escaped -- Since semver is not strictly enforced by the ethpm spec, if the `package_version` is omitted from a uri, tooling **SHOULD** avoid guessing in the face of any ambiguity and present the user with a choice from the available versions. - -#### `json_pointer` -- Optional -- A path that identifies a specific asset within a versioned package release. -- This path **MUST** conform to the [JSON pointer](https://tools.ietf.org/html/rfc6901) spec and resolve to an available asset within the package. - -## Rationale -Most interactions within the EthPM ecosystem benefit from a single-string representation of EthPM assets; from installing a package, to identifying a registry, to distributing a package. A single string that can faithfully represent any kind of EthPM asset, across the mainnet or testnets, reduces the mental overload for new users, minimizes configuration requirements for frameworks, and simplifies distribution of packages for package authors. - -## Test Cases -A JSON file for testing various URIs can be found in the [`ethpm-spec`](https://github.com/ethpm/ethpm-spec/) repository fixtures. - -## Implementation -The EthPM URI scheme has been implemented in the following libraries: -- [Brownie](https://eth-brownie.readthedocs.io/en/stable/) -- [Truffle](https://www.trufflesuite.com/docs/truffle/overview) -- [EthPM CLI](https://ethpm-cli.readthedocs.io/en/latest/) - -## Security Considerations -In most cases, an EthPM URI points to an immutable asset, giving full security that the target asset has not been modified. However, in the case where an EthPM URI uses an ENS name as its registry address, it is possible that the ENS name has been redirected to a new registry, in which case the guarantee of immutability no longer exists. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2942.md diff --git a/EIPS/eip-2976.md b/EIPS/eip-2976.md index 6f8056f967d75a..36bd2d463a7f48 100644 --- a/EIPS/eip-2976.md +++ b/EIPS/eip-2976.md @@ -34,7 +34,7 @@ All changes specified below apply to all protocol/versions retroactively. * `Transaction` is either `TypedTransaction` or `LegacyTransaction` * `TypedTransaction` is a byte array containing `TransactionType || TransactionPayload` * `TypedTransactionHash` is `keccak256(TypedTransaction)` -* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transcation +* `TransactionType` is a positive unsigned 8-bit number between `0` and `0x7f` that represents the type of the transaction * `TransactionPayload` is an opaque byte array whose interpretation is dependent on the `TransactionType` and defined in future EIPs * `LegacyTransaction` is an array of the form `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` * `LegacyTransactionHash` is `keccak256(rlp(LegacyTransaction))` diff --git a/EIPS/eip-2980.md b/EIPS/eip-2980.md index ec74e0e5fcf248..84cdaf8aa83904 100644 --- a/EIPS/eip-2980.md +++ b/EIPS/eip-2980.md @@ -1,197 +1,7 @@ --- eip: 2980 -title: Swiss Compliant Asset Token -description: An interface for asset tokens, compliant with Swiss Law and compatible with [ERC-20](./eip-20.md). -author: Gianluca Perletti (@Perlets9), Alan Scarpellini (@alanscarpellini), Roberto Gorini (@robertogorini), Manuel Olivi (@manvel79) -discussions-to: https://github.com/ethereum/EIPs/issues/2983 -status: Stagnant -type: Standards Track category: ERC -created: 2020-09-08 -requires: 20 +status: Moved --- -## Abstract - -This new standard is an [ERC-20](./eip-20.md) compatible token with restrictions that comply with the following Swiss laws: the [Stock Exchange Act](../assets/eip-2980/Swiss-Confederation-SESTA.pdf), the [Banking Act](../assets/eip-2980/Swiss-Confederation-BA.pdf), the [Financial Market Infrastructure Act](../assets/eip-2980/Swiss-Confederation-FMIA.pdf), the [Act on Collective Investment Schemes](../assets/eip-2980/Swiss-Confederation-CISA.pdf) and the [Anti-Money Laundering Act](../assets/eip-2980/Swiss-Confederation-AMLA.pdf). The [Financial Services Act](../assets/eip-2980/Swiss-Confederation-FINSA.pdf) and the [Financial Institutions Act](../assets/eip-2980/Swiss-Confederation-FINIA.pdf) must also be considered. The solution achieved meet also the European jurisdiction. - -This new standard meets the new era of asset tokens (known also as "security tokens"). These new methods manage securities ownership during issuance and trading. The issuer is the only role that can manage a white-listing and the only one that is allowed to execute “freeze” or “revoke” functions. - -## Motivation - -In its ICO guidance dated February 16, 2018, FINMA (Swiss Financial Market Supervisory Authority) defines asset tokens as tokens representing assets and/or relative rights ([FINMA ICO Guidelines](../assets/eip-2980/Finma-ICO-Guidelines.pdf)). It explicitly mentions that asset tokens are analogous to and can economically represent shares, bonds, or derivatives. The long list of relevant financial market laws mentioned above reveal that we need more methods than with Payment and Utility Token. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -The words "asset tokens" and "security tokens" can be considered synonymous. - -Every ERC-2980 compliant contract MUST implement the ERC-2980 interface. - -### ERC-2980 (Token Contract) - -``` solidity -interface ERC2980 extends ERC20 { - - /// @dev This emits when funds are reassigned - event FundsReassigned(address from, address to, uint256 amount); - - /// @dev This emits when funds are revoked - event FundsRevoked(address from, uint256 amount); - - /// @dev This emits when an address is frozen - event FundsFrozen(address target); - - /** - * @dev getter to determine if address is in frozenlist - */ - function frozenlist(address _operator) external view returns (bool); - - /** - * @dev getter to determine if address is in whitelist - */ - function whitelist(address _operator) external view returns (bool); - -} -``` - -The ERC-2980 extends [ERC-20](./eip-20.md). Due to the indivisible nature of asset tokens, the decimals number MUST be zero. - -### Whitelist and Frozenlist - -The accomplishment of the Swiss Law requirements is achieved by the use of two distinct lists of address: the Whitelist and the Frozenlist. -Addresses can be added to one or the other list at any time by operators with special privileges, called Issuers, and described below. -Although these lists may look similar, they differ for the following reasons: the Whitelist members are the only ones who can receive tokens from other addresses. There is no restriction on the possibility that these addresses can transfer the tokens already in their ownership. -This can occur when an address, present in the Whitelist, is removed from this list, without however being put in the Frozenlist and remaining in possession of its tokens. -On the other hand, the addresses assigned to the Frozenlist, as suggested by the name itself, have to be considered "frozen", so they cannot either receive tokens or send tokens to anyone. - -Below is an example interface for the implementation of a whitelist-compatible and a frozenlist-compratible contract. - -``` solidity -Interface Whitelistable { - - /** - * @dev add an address to the whitelist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to add - * @return true if the address was added to the whitelist, false if the address was already in the whitelist - */ - function addAddressToWhitelist(address _operator) external returns (bool); - - /** - * @dev remove an address from the whitelist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to remove - * @return true if the address was removed from the whitelist, false if the address wasn't in the whitelist in the first place - */ - function removeAddressFromWhitelist(address _operator) external returns (bool); - -} - -Interface Freezable { - - /** - * @dev add an address to the frozenlist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to add - * @return true if the address was added to the frozenlist, false if the address was already in the frozenlist - */ - function addAddressToFrozenlist(address _operator) external returns (bool); - - /** - * @dev remove an address from the frozenlist - * Throws unless `msg.sender` is an Issuer operator - * @param _operator address to remove - * @return true if the address was removed from the frozenlist, false if the address wasn't in the frozenlist in the first place - */ - function removeAddressFromFrozenlist(address _operator) external returns (bool); - -} -``` - -### Issuers - -A key role is played by the Issuer. This figure has the permission to manage Whitelists and Frozenlists, to revoke tokens and reassign them and to transfer the role to another address. No restrictions on the possibility to have more than one Issuer per contract. Issuers are nominated by the Owner of the contract, who also is in charge of remove the role. The possibility of nominating the Owner itself as Issuer at the time of contract creation (or immediately after) is not excluded. - -Below is an example interface for the implementation of the Issuer functionalities. - -``` solidity -Interface Issuable { - - /** - * @dev getter to determine if address has issuer role - */ - function isIssuer(address _addr) external view returns (bool); - - /** - * @dev add a new issuer address - * Throws unless `msg.sender` is the contract owner - * @param _operator address - * @return true if the address was not an issuer, false if the address was already an issuer - */ - function addIssuer(address _operator) external returns (bool); - - /** - * @dev remove an address from issuers - * Throws unless `msg.sender` is the contract owner - * @param _operator address - * @return true if the address has been removed from issuers, false if the address wasn't in the issuer list in the first place - */ - function removeIssuer(address _operator) external returns (bool); - - /** - * @dev Allows the current issuer to transfer its role to a newIssuer - * Throws unless `msg.sender` is an Issuer operator - * @param _newIssuer The address to transfer the issuer role to - */ - function transferIssuer(address _newIssuer) external; - -} -``` - -### Revoke and Reassign - -Revoke and Reassign methods allow Issuers to move tokens from addresses, even if they are in the Frozenlist. The Revoke method transfers the entire balance of the target address to the Issuer who invoked the method. The Reassign method transfers the entire balance of the target address to another address. These rights for these operations MUST be allowed only to Issuers. - -Below is an example interface for the implementation of the Revoke and Reassign functionalities. - -``` solidity -Interface RevokableAndReassignable { - - /** - * @dev Allows the current Issuer to transfer token from an address to itself - * Throws unless `msg.sender` is an Issuer operator - * @param _from The address from which the tokens are withdrawn - */ - function revoke(address _from) external; - - /** - * @dev Allows the current Issuer to transfer token from an address to another - * Throws unless `msg.sender` is an Issuer operator - * @param _from The address from which the tokens are withdrawn - * @param _to The address who receives the tokens - */ - function reassign(address _from, address _to) external; - -} -``` - -## Rationale - -There are currently no token standards that expressly facilitate conformity to securities law and related regulations. EIP-1404 (Simple Restricted Token Standard) it’s not enough to address FINMA requirements around re-issuing securities to Investors. -In Swiss law, an issuer must eventually enforce the restrictions of their token transfer with a “freeze” function. The token must be “revocable”, and we need to apply a white-list method for AML/KYC checks. - -## Backwards Compatibility - -This EIP does not introduce backward incompatibilities and is backward compatible with the older ERC-20 token standard. -This standard allows the implementation of ERC-20 functions transfer, transferFrom, approve and allowance alongside to make a token fully compatible with ERC-20. -The token MAY implement decimals() for backward compatibility with ERC-20. If implemented, it MUST always return 0. - -## Security Considerations - -The security considerations mainly concern the role played by the Issuers. This figure, in fact, is not generally present in common ERC-20 tokens but has very powerful rights that allow him to move tokens without being in possession and freeze other addresses, preventing them from transferring tokens. It must be the responsibility of the owner to ensure that the addresses that receive this charge remain in possession of it only for the time for which they have been designated to do so, thus preventing any abuse. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2980.md diff --git a/EIPS/eip-2981.md b/EIPS/eip-2981.md index a24821bd229ed5..9b6e89e7e50d44 100644 --- a/EIPS/eip-2981.md +++ b/EIPS/eip-2981.md @@ -1,183 +1,7 @@ --- eip: 2981 -title: NFT Royalty Standard -author: Zach Burks (@vexycats), James Morgan (@jamesmorgan), Blaine Malone (@blmalone), James Seibel (@seibelj) -discussions-to: https://github.com/ethereum/EIPs/issues/2907 -status: Final -type: Standards Track category: ERC -created: 2020-09-15 -requires: 165 +status: Moved --- -## Simple Summary - -A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal support for royalty payments across all NFT marketplaces and ecosystem participants. - -## Abstract - -This standard allows contracts, such as NFTs that support [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) interfaces, to signal a royalty amount to be paid to the NFT creator or rights holder every time the NFT is sold or re-sold. This is intended for NFT marketplaces that want to support the ongoing funding of artists and other NFT creators. The royalty payment must be voluntary, as transfer mechanisms such as `transferFrom()` include NFT transfers between wallets, and executing them does not always imply a sale occurred. Marketplaces and individuals implement this standard by retrieving the royalty payment information with `royaltyInfo()`, which specifies how much to pay to which address for a given sale price. The exact mechanism for paying and notifying the recipient will be defined in future EIPs. This ERC should be considered a minimal, gas-efficient building block for further innovation in NFT royalty payments. - -## Motivation -There are many marketplaces for NFTs with multiple unique royalty payment implementations that are not easily compatible or usable by other marketplaces. Just like the early days of ERC-20 tokens, NFT marketplace smart contracts are varied by ecosystem and not standardized. This EIP enables all marketplaces to retrieve royalty payment information for a given NFT. This enables accurate royalty payments regardless of which marketplace the NFT is sold or re-sold at. - -Many of the largest NFT marketplaces have implemented bespoke royalty payment solutions that are incompatible with other marketplaces. This standard implements standardized royalty information retrieval that can be accepted across any type of NFT marketplace. This minimalist proposal only provides a mechanism to fetch the royalty amount and recipient. The actual funds transfer is something which the marketplace should execute. - -This standard allows NFTs that support [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) interfaces, to have a standardized way of signalling royalty information. More specifically, these contracts can now calculate a royalty amount to provide to the rightful recipient. - -Royalty amounts are always a percentage of the sale price. If a marketplace chooses *not* to implement this EIP, then no funds will be paid for secondary sales. It is believed that the NFT marketplace ecosystem will voluntarily implement this royalty payment standard; in a bid to provide ongoing funding for artists/creators. NFT buyers will assess the royalty payment as a factor when making NFT purchasing decisions. - -Without an agreed royalty payment standard, the NFT ecosystem will lack an effective means to collect royalties across all marketplaces and artists and other creators will not receive ongoing funding. This will hamper the growth and adoption of NFTs and demotivate NFT creators from minting new and innovative tokens. - -Enabling all NFT marketplaces to unify on a single royalty payment standard will benefit the entire NFT ecosystem. - -While this standard focuses on NFTs and compatibility with the ERC-721 and ERC-1155 standards, EIP-2981 does not require compatibility with ERC-721 and ERC-1155 standards. Any other contract could integrate with EIP-2981 to return royalty payment information. ERC-2981 is, therefore, a universal royalty standard for many asset types. - -At a glance, here's an example conversation summarizing NFT royalty payments today: - ->**Artist**: "Do you support royalty payments on your platform?" ->**Marketplace**: "Yes we have royalty payments, but if your NFT is sold on another marketplace then we cannot enforce this payment." ->**Artist**: "What about other marketplaces that support royalties, don't you share my royalty information to make this work?" ->**Marketplace**: "No, we do not share royalty information." - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL -NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and -"OPTIONAL" in this document are to be interpreted as described in -RFC 2119. - -**ERC-721 and ERC-1155 compliant contracts MAY implement this ERC for royalties to provide a standard method of specifying royalty payment information.** - -Marketplaces that support this standard **SHOULD** implement some method of transferring royalties to the royalty recipient. Standards for the actual transfer and notification of funds will be specified in future EIPs. - -Marketplaces **MUST** pay the royalty in the same unit of exchange as that of the `_salePrice` passed to `royaltyInfo()`. This is equivalent to saying that the `_salePrice` parameter and the `royaltyAmount` return value **MUST** be denominated in the same monetary unit. For example, if the sale price is in ETH, then the royalty payment must also be paid in ETH, and if the sale price is in USDC, then the royalty payment must also be paid in USDC. - -Implementers of this standard **MUST** calculate a percentage of the `_salePrice` when calculating the royalty amount. Subsequent invocations of `royaltyInfo()` **MAY** return a different `royaltyAmount`. Though there are some important considerations for implementers if they choose to perform different percentage calculations between `royaltyInfo()` invocations. - -The `royaltyInfo()` function is not aware of the unit of exchange for the sale and royalty payment. With that in mind, implementers **MUST NOT** return a fixed/constant `royaltyAmount`, wherein they're ignoring the `_salePrice`. For the same reason, implementers **MUST NOT** determine the `royaltyAmount` based on comparing the `_salePrice` with constant numbers. In both cases, the `royaltyInfo()` function makes assumptions on the unit of exchange, which **MUST** be avoided. - -The percentage value used must be independent of the sale price for reasons previously mentioned (i.e. if the percentage value 10%, then 10% **MUST** apply whether `_salePrice` is 10, 10000 or 1234567890). If the royalty fee calculation results in a remainder, implementers **MAY** round up or round down to the nearest integer. For example, if the royalty fee is 10% and `_salePrice` is 999, the implementer can return either 99 or 100 for `royaltyAmount`, both are valid. - -The implementer **MAY** choose to change the percentage value based on other predictable variables that do not make assumptions about the unit of exchange. For example, the percentage value may drop linearly over time. An approach like this **SHOULD NOT** be based on variables that are unpredictable like `block.timestamp`, but instead on other more predictable state changes. One more reasonable approach **MAY** use the number of transfers of an NFT to decide which percentage value is used to calculate the `royaltyAmount`. The idea being that the percentage value could decrease after each transfer of the NFT. Another example could be using a different percentage value for each unique `_tokenId`. - -Marketplaces that support this standard **SHOULD NOT** send a zero-value transaction if the `royaltyAmount` returned is `0`. This would waste gas and serves no useful purpose in this EIP. - -Marketplaces that support this standard **MUST** pay royalties no matter where the sale occurred or in what currency, including on-chain sales, over-the-counter (OTC) sales and off-chain sales such as at auction houses. As royalty payments are voluntary, entities that respect this EIP must pay no matter where the sale occurred - a sale conducted outside of the blockchain is still a sale. The exact mechanism for paying and notifying the recipient will be defined in future EIPs. - -Implementers of this standard **MUST** have all of the following functions: - -```solidity -pragma solidity ^0.6.0; -import "./IERC165.sol"; - -/// -/// @dev Interface for the NFT Royalty Standard -/// -interface IERC2981 is IERC165 { - /// ERC165 bytes to add to interface array - set in parent contract - /// implementing this standard - /// - /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a - /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; - /// _registerInterface(_INTERFACE_ID_ERC2981); - - /// @notice Called with the sale price to determine how much royalty - // is owed and to whom. - /// @param _tokenId - the NFT asset queried for royalty information - /// @param _salePrice - the sale price of the NFT asset specified by _tokenId - /// @return receiver - address of who should be sent the royalty payment - /// @return royaltyAmount - the royalty payment amount for _salePrice - function royaltyInfo( - uint256 _tokenId, - uint256 _salePrice - ) external view returns ( - address receiver, - uint256 royaltyAmount - ); -} - -interface IERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -### Examples - -This standard being used on an ERC-721 during deployment: - -#### Deploying an ERC-721 and signaling support for ERC-2981 - -```solidity -constructor (string memory name, string memory symbol, string memory baseURI) { - _name = name; - _symbol = symbol; - _setBaseURI(baseURI); - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(_INTERFACE_ID_ERC721); - _registerInterface(_INTERFACE_ID_ERC721_METADATA); - _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); - // Royalties interface - _registerInterface(_INTERFACE_ID_ERC2981); - } -``` - -#### Checking if the NFT being sold on your marketplace implemented royalties - -```solidity -bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; - -function checkRoyalties(address _contract) internal returns (bool) { - (bool success) = IERC165(_contract).supportsInterface(_INTERFACE_ID_ERC2981); - return success; - } -``` - -## Rationale - -### Optional royalty payments - -It is impossible to know which NFT transfers are the result of sales, and which are merely wallets moving or consolidating their NFTs. Therefore, we cannot force every transfer function, such as `transferFrom()` in ERC-721, to involve a royalty payment as not every transfer is a sale that would require such payment. We believe the NFT marketplace ecosystem will voluntarily implement this royalty payment standard to provide ongoing funding for artists/creators. NFT buyers will assess the royalty payment as a factor when making NFT purchasing decisions. - -### Simple royalty payments to a single address - -This EIP does not specify the manner of payment to the royalty recipient. Furthermore, it is impossible to fully know and efficiently implement all possible types of royalty payments logic. With that said, it is on the royalty payment receiver to implement all additional complexity and logic for fee splitting, multiple receivers, taxes, accounting, etc. in their own receiving contract or off-chain processes. Attempting to do this as part of this standard, it would dramatically increase the implementation complexity, increase gas costs, and could not possibly cover every potential use-case. This ERC should be considered a minimal, gas-efficient building block for further innovation in NFT royalty payments. Future EIPs can specify more details regarding payment transfer and notification. - -### Royalty payment percentage calculation - -This EIP mandates a percentage-based royalty fee model. It is likely that the most common case of percentage calculation will be where the `royaltyAmount` is always calculated from the `_salePrice` using a fixed percent i.e. if the royalty fee is 10%, then a 10% royalty fee must apply whether `_salePrice` is 10, 10000 or 1234567890. - -As previously mentioned, implementers can get creative with this percentage-based calculation but there are some important caveats to consider. Mainly, ensuring that the `royaltyInfo()` function is not aware of the unit of exchange and that unpredictable variables are avoided in the percentage calculation. To follow up on the earlier `block.timestamp` example, there is some nuance which can be highlighted if the following events ensued: - -1. Marketplace sells NFT. -2. Marketplace delays `X` days before invoking `royaltyInfo()` and sending payment. -3. Marketplace receives `Y` for `royaltyAmount` which was significantly different from the `royaltyAmount` amount that would've been calculated `X` days prior if no delay had occurred. -4. Royalty recipient is dissatisfied with the delay from the marketplace and for this reason, they raise a dispute. - -Rather than returning a percentage and letting the marketplace calculate the royalty amount based on the sale price, a `royaltyAmount` value is returned so there is no dispute with a marketplace over how much is owed for a given sale price. The royalty fee payer must pay the `royaltyAmount` that `royaltyInfo()` stipulates. - -### Unit-less royalty payment across all marketplaces, both on-chain and off-chain - -This EIP does not specify a currency or token used for sales and royalty payments. The same percentage-based royalty fee must be paid regardless of what currency, or token was used in the sale, paid in the same currency or token. This applies to sales in any location including on-chain sales, over-the-counter (OTC) sales, and off-chain sales using fiat currency such as at auction houses. As royalty payments are voluntary, entities that respect this EIP must pay no matter where the sale occurred - a sale outside of the blockchain is still a sale. The exact mechanism for paying and notifying the recipient will be defined in future EIPs. - -### Universal Royalty Payments - -Although designed specifically with NFTs in mind, this standard does not require that a contract implementing EIP-2981 is compatible with either ERC-721 or ERC-1155 standards. Any other contract could use this interface to return royalty payment information, provided that it is able to uniquely identify assets within the constraints of the interface. ERC-2981 is, therefore, a universal royalty standard for many other asset types. - -## Backwards Compatibility - -This standard is compatible with current ERC-721 and ERC-1155 standards. - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-2981.md diff --git a/EIPS/eip-2982.md b/EIPS/eip-2982.md index eba2dd8153ff85..502cd346407dab 100644 --- a/EIPS/eip-2982.md +++ b/EIPS/eip-2982.md @@ -43,7 +43,7 @@ In addition to the above, PoS has synergies with the sharding scaling solution. ## Specification -Phase 0 is designed to require _no breaking consensus changes_ to existing Ethereum mainnet. Instead, this is the bootstraping a new PoS consensus that can, once stable, supplant the current PoW consensus. +Phase 0 is designed to require _no breaking consensus changes_ to existing Ethereum mainnet. Instead, this is the bootstrapping a new PoS consensus that can, once stable, supplant the current PoW consensus. Phase 0 specifications are maintained in a repository independent of this EIP. `SPEC_RELEASE_VERSION` release of the specs at `SPEC_RELEASE_COMMIT` are considered the canonical Phase 0 specs for this EIP. @@ -394,7 +394,7 @@ The deposit contract maintains a Merkle root of all deposits made so far. Once a #### Activation -The validator immediately joins the validator registry, but is at first inactive. The validator becomes active after $N \ge 4$ epochs; the minimum of 4 is there to ensure the RANDAO is not manipulable, and $N$ may exceed 4 if too many validators try to join at the same time. If the active validator set has size $|V|$, a maximum of $max(4, \frac{|V|}{65536})$ valdators can join per epoch; if more validators try to join, they are put in a queue and processed as quickly as possible. +The validator immediately joins the validator registry, but is at first inactive. The validator becomes active after $N \ge 4$ epochs; the minimum of 4 is there to ensure the RANDAO is not manipulable, and $N$ may exceed 4 if too many validators try to join at the same time. If the active validator set has size $|V|$, a maximum of $max(4, \frac{|V|}{65536})$ validators can join per epoch; if more validators try to join, they are put in a queue and processed as quickly as possible. #### Exiting diff --git a/EIPS/eip-3000.md b/EIPS/eip-3000.md index 7b36755eda0b64..fd185a40d8b10d 100644 --- a/EIPS/eip-3000.md +++ b/EIPS/eip-3000.md @@ -1,154 +1,7 @@ --- eip: 3000 -title: Optimistic enactment governance standard -author: Jorge Izquierdo (@izqui), Fabien Marino (@bonustrack) -discussions-to: https://github.com/ethereum/EIPs/issues/3042 -status: Stagnant -type: Standards Track category: ERC -created: 2020-09-24 +status: Moved --- -## Simple Summary - -Interface for scheduling, executing and challenging contract executions based on off-chain approval - -## Abstract - -ERC-3000 presents a basic on-chain spec for contracts to optimistically enact governance decisions made off-chain. - -The standard is opinionated in defining the 6 entrypoint functions to contracts supporting the standard. But it allows for any sort of resolver mechanism for the challenge/response games characteristic of optimistic contracts. - -While the authors currently believe resolving challenges [using a subjective oracle](https://aragon.org/blog/snapshot) is the right tradeoff, the standard has been designed such that changing to another mechanism is possible (a deterministic resolver like [Optimism's OVM](https://optimism.io) uses), even allowing to hot-swap it in the same live instance. - -## Specification - -### Data structures - -Some data structures are defined which are later used in the standard interfaces: - -```solidity -library ERC3000Data { - struct Container { - Payload payload; - Config config; - } - - struct Payload { - uint256 nonce; - uint256 executionTime; - address submitter; - IERC3000Executor executor; - Action[] actions; - bytes proof; - } - - struct Action { - address to; - uint256 value; - bytes data; - } - - struct Config { - uint256 executionDelay; - Collateral scheduleDeposit; - Collateral challengeDeposit; - Collateral vetoDeposit; - address resolver; - bytes rules; - } - - struct Collateral { - address token; - uint256 amount; - } -} -``` - -### Interface and events - -Given the data structures above, by taking advantage of the Solidity ABI encoder v2, we define four required functions and two optional functions as the interface for contracts to comply with ERC-3000. - -All standard functions are expected to revert (whether to include error messages/revert reasons as part of the standard is yet to be determined) when pre-conditions are not met or an unexpected error occurs. On success, each function must emit its associated event once and only once. - -```solidity -abstract contract IERC3000 { - /** - * @notice Schedules an action for execution, allowing for challenges and vetos on a defined time window - * @param container A Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - */ - function schedule(ERC3000Data.Container memory container) virtual public returns (bytes32 containerHash); - event Scheduled(bytes32 indexed containerHash, ERC3000Data.Payload payload, ERC3000Data.Collateral collateral); - - /** - * @notice Executes an action after its execution delayed has passed and its state hasn't been altered by a challenge or veto - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * should be a MUST payload.executor.exec(payload.actions) - */ - function execute(ERC3000Data.Container memory container) virtual public returns (bytes[] memory execResults); - event Executed(bytes32 indexed containerHash, address indexed actor, bytes[] execResults); - - /** - * @notice Challenge a container in case its scheduling is illegal as per Config.rules. Pulls collateral and dispute fees from sender into contract - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * @param reason Hint for case reviewers as to why the scheduled container is illegal - */ - function challenge(ERC3000Data.Container memory container, bytes memory reason) virtual public returns (uint256 resolverId); - event Challenged(bytes32 indexed containerHash, address indexed actor, bytes reason, uint256 resolverId, ERC3000Data.Collateral collateral); - - /** - * @notice Apply arbitrator's ruling over a challenge once it has come to a final ruling - * @param container A ERC3000Data.Container struct holding both the paylaod being scheduled for execution and - the current configuration of the system - * @param resolverId disputeId in the arbitrator in which the dispute over the container was created - */ - function resolve(ERC3000Data.Container memory container, uint256 resolverId) virtual public returns (bytes[] memory execResults); - event Resolved(bytes32 indexed containerHash, address indexed actor, bool approved); - - /** - * @dev OPTIONAL - * @notice Apply arbitrator's ruling over a challenge once it has come to a final ruling - * @param payloadHash Hash of the payload being vetoed - * @param config A ERC3000Data.Config struct holding the config attached to the payload being vetoed - */ - function veto(bytes32 payloadHash, ERC3000Data.Config memory config, bytes memory reason) virtual public; - event Vetoed(bytes32 indexed containerHash, address indexed actor, bytes reason, ERC3000Data.Collateral collateral); - - /** - * @dev OPTIONAL: implementer might choose not to implement (initial Configured event MUST be emitted) - * @notice Apply a new configuration for all *new* containers to be scheduled - * @param config A ERC3000Data.Config struct holding all the new params that will control the queue - */ - function configure(ERC3000Data.Config memory config) virtual public returns (bytes32 configHash); - event Configured(bytes32 indexed containerHash, address indexed actor, ERC3000Data.Config config); -} -``` - -## Rationale - -The authors believe that it is very important that this standard leaves the other open to any resolver mechanism to be implemented and adopted. - -That's why a lot of the function and variable names were left intentionally bogus to be compatible with future resolvers without changing the standard. - -ERC-3000 should be seen as a public good of top of which public infrastrastructure will be built, being way more important than any particular implementation or the interests of specific companies or projects. - -## Security Considerations - -The standard allows for the resolver for challenges to be configured, and even have different resolvers for coexisting scheduled payloads. Choosing the right resolver requires making the right tradeoff between security, time to finality, implementation complexity, and external dependencies. - -Using a subjective oracle as resolver has its risks, since security depends on the crypto-economic properties of the system. For an analysis of crypto-economic considerations of Aragon Court, you can check [the following doc](https://github.com/aragon/aragon-court/tree/master/docs/3-cryptoeconomic-considerations). - -On the other hand, implementing a deterministic resolver is prone to dangerous bugs given its complexity, and will rely on a specific version of the off-chain protocol, which could rapidly evolve while the standard matures and gets adopted. - -## Implementations - -### 1. Aragon Govern - -- [ERC-3000 interface (MIT license)](https://github.com/aragon/govern/blob/master/packages/erc3k) -- [Implementation (GPL-3.0 license)](https://github.com/aragon/govern/blob/master/packages/govern-core) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3000.md diff --git a/EIPS/eip-3005.md b/EIPS/eip-3005.md index c3f1219dfda2b8..1b8dc33c0f8ba9 100644 --- a/EIPS/eip-3005.md +++ b/EIPS/eip-3005.md @@ -1,416 +1,7 @@ --- eip: 3005 -title: Batched meta transactions -author: Matt (@defifuture) -discussions-to: https://ethereum-magicians.org/t/eip-3005-the-economic-viability-of-batched-meta-transactions/4673 -status: Stagnant -type: Standards Track category: ERC -created: 2020-09-25 +status: Moved --- -## Simple Summary - -Defines an extension function for ERC-20 (and other fungible token standards), which allows receiving and processing a batch of meta transactions. - -## Abstract - -This EIP defines a new function called `processMetaBatch()` that extends any fungible token standard, and enables batched meta transactions coming from many senders in one on-chain transaction. - -The function must be able to receive multiple meta transactions data and process it. This means validating the data and the signature, before proceeding with token transfers based on the data. - -The function enables senders to make gasless transactions, while reducing the relayer's gas cost due to batching. - -## Motivation - -Meta transactions have proven useful as a solution for Ethereum accounts that don't have any ether, but hold ERC-20 tokens and would like to transfer them (gasless transactions). - -The current meta transaction relayer implementations only allow relaying one meta transaction at a time. Some also allow batched meta transactions from the same sender. But none offers batched meta transactions from **multiple** senders. - -The motivation behind this EIP is to find a way to allow relaying batched meta transactions from **many senders** in **one on-chain transaction**, which also **reduces the total gas cost** that a relayer needs to cover. - -![](../assets/eip-3005/meta-txs-directly-to-token-smart-contract.png) - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -The key words "MUST (BUT WE KNOW YOU WON'T)", "SHOULD CONSIDER", "REALLY SHOULD NOT", "OUGHT TO", "WOULD PROBABLY", "MAY WISH TO", "COULD", "POSSIBLE", and "MIGHT" in this document are to be interpreted as described in RFC 6919. - -### Meta transaction data - -In order to successfully validate and transfer tokens, the `processMetaBatch()` function MUST process the following data about a meta transaction: - -- sender address -- receiver address -- token amount -- relayer fee -- a (meta tx) nonce -- an expiration date (this COULD be a block number, or it COULD be a block timestamp) -- a token address -- a relayer address -- a signature - -Not all of the data needs to be sent to the function by the relayer (see the function interface specification). Some of the data can be deduced or extracted from other sources (from transaction data and contract state). - -### `processMetaBatch()` function input data - -The `processMetaBatch()` function MUST receive the following data: - -- sender address -- receiver address -- token amount -- relayer fee -- an expiration date (this COULD be a block number, or it COULD be a block timestamp) -- a signature - -The following data is OPTIONAL to be sent to the function, because it can be extracted or derived from other sources: - -- a (meta tx) nonce -- a token address -- a relayer address - -### Meta transaction data hash - -The pseudocode for creating a hash of meta transaction data is the following: - -``` -keccak256(address(sender) - ++ address(recipient) - ++ uint256(amount) - ++ uint256(relayerFee) - ++ uint256(nonce) - ++ uint256(expirationDate) - ++ address(tokenContract) - ++ address(relayer) -) -``` - -The created hash MUST then be signed with the sender's private key. - -### Validation rules - -- Nonce of a new transaction MUST always be bigger by exactly 1 from the nonce of the last successfully processed meta transaction of the same sender to the same token contract. -- Sending to and from a 0x0 address MUST be prohibited. -- A meta transaction MUST be processed before the expiration date. -- Each sender's token balance MUST be equal or greater than the sum of their respective meta transaction token amount and relayer fee. -- A transaction where at least one meta transaction in the batch does not satisfy the above requirements MUST not be reverted. Instead, a failed meta transaction MUST be skipped or ignored. - -### `processMetaBatch()` function interface - -The `processMetaBatch()` function MUST have the following interface: - -```solidity -function processMetaBatch(address[] memory senders, - address[] memory recipients, - uint256[] memory amounts, - uint256[] memory relayerFees, - uint256[] memory blocks, - uint8[] memory sigV, - bytes32[] memory sigR, - bytes32[] memory sigS) public returns (bool); -``` - -The overview of parameters that are passed: - -- `senders`: an array of meta transaction sender addresses (token senders) -- `recipients `: an array of token recipients addresses -- `amounts`: an array of token amounts that are sent from each sender to each recipient, respectively -- `relayerFees`: an array of the relayer fees paid in tokens by senders. The fee receiver is a relayer (`msg.address`) -- `blocks`: an array of block numbers that represent an expiration date by which the meta transaction must be processed (alternatively, a timestamp could be used instead of a block number) -- `sigV`, `sigR`, `sigS`: three arrays that represent parts of meta transaction signatures - -Each entry in each of the arrays MUST represent data from one meta transaction. The order of the data is very important. Data from a single meta transaction MUST have the same index in every array. - -### Meta transaction nonce - -The token smart contract must keep track of a meta transaction nonce for each token holder. - -```solidity -mapping (address => uint256) private _metaNonces; -``` - -The interface for the `nonceOf()` function is the following: - -```solidity -function nonceOf(address account) public view returns (uint256); -``` - -### Token transfers - -After a meta transaction is successfully validated, the meta nonce of the meta transaction sender MUST be increased by 1. - -Then two token transfers MUST occur: - -- The specified token amount MUST go to the recipient. -- The relayer fee MUST go to the relayer (`msg.sender`). - -## Implementation - -The **reference implementation** adds a couple of functions to the existing ERC-20 token standard: - -- `processMetaBatch()` -- `nonceOf()` - -You can see the implementation of both functions in this file: [ERC20MetaBatch.sol](https://github.com/defifuture/erc20-batched-meta-transactions/blob/master/contracts/ERC20MetaBatch.sol). This is an extended ERC-20 contract with added meta transaction batch transfer capabilities. - -### `processMetaBatch()` - -The `processMetaBatch()` function is responsible for receiving and processing a batch of meta transactions that change token balances. - -```solidity -function processMetaBatch(address[] memory senders, - address[] memory recipients, - uint256[] memory amounts, - uint256[] memory relayerFees, - uint256[] memory blocks, - uint8[] memory sigV, - bytes32[] memory sigR, - bytes32[] memory sigS) public returns (bool) { - - address sender; - uint256 newNonce; - uint256 relayerFeesSum = 0; - bytes32 msgHash; - uint256 i; - - // loop through all meta txs - for (i = 0; i < senders.length; i++) { - sender = senders[i]; - newNonce = _metaNonces[sender] + 1; - - if(sender == address(0) || recipients[i] == address(0)) { - continue; // sender or recipient is 0x0 address, skip this meta tx - } - - // the meta tx should be processed until (including) the specified block number, otherwise it is invalid - if(block.number > blocks[i]) { - continue; // if current block number is bigger than the requested number, skip this meta tx - } - - // check if meta tx sender's balance is big enough - if(_balances[sender] < (amounts[i] + relayerFees[i])) { - continue; // if sender's balance is less than the amount and the relayer fee, skip this meta tx - } - - // check if the signature is valid - msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx - } - - // set a new nonce for the sender - _metaNonces[sender] = newNonce; - - // transfer tokens - _balances[sender] -= (amounts[i] + relayerFees[i]); - _balances[recipients[i]] += amounts[i]; - relayerFeesSum += relayerFees[i]; - } - - // give the relayer the sum of all relayer fees - _balances[msg.sender] += relayerFeesSum; - - return true; -} -``` - -### `nonceOf()` - -Nonces are needed due to the replay protection (see *Replay attacks* under *Security Considerations*). - -```solidity -mapping (address => uint256) private _metaNonces; - -// ... - -function nonceOf(address account) public view returns (uint256) { - return _metaNonces[account]; -} -``` - -The link to the complete implementation (along with gas usage results) is here: [https://github.com/defifuture/erc20-batched-meta-transactions](https://github.com/defifuture/erc20-batched-meta-transactions). - -> Note that the OpenZeppelin ERC-20 implementation was used here. Some other implementation may have named the `_balances` mapping differently, which would require minor changes in the `processMetaBatch()` function. - -## Rationale - -### All-in-one - -Alternative implementations (like GSN) use multiple smart contracts to enable meta transactions, although this increases gas usage. This implementation (EIP-3005) intentionally keeps everything within one function which reduces complexity and gas cost. - -The `processMetaBatch()` function thus does the job of receiving a batch of meta transactions, validating them, and then transferring tokens from one address to another. - -### Function parameters - -As you can see, the `processMetaBatch()` function in the reference implementation takes the following parameters: - -- an array of **sender addresses** (meta txs senders, not relayers) -- an array of **receiver addresses** -- an array of **amounts** -- an array of **relayer fees** (relayer is `msg.sender`) -- an array of **block numbers** (a due "date" for meta tx to be processed) -- Three arrays that represent parts of a **signature** (v, r, s) - -**Each item** in these arrays represents **data of one meta transaction**. That's why the **correct order** in the arrays is very important. - -If a relayer gets the order wrong, the `processMetaBatch()` function would notice that (when validating a signature), because the hash of the meta transaction values would not match the signed hash. A meta transaction with an invalid signature is **skipped**. - -### The alternative way of passing meta transaction data into the function - -The reference implementation takes parameters as arrays. There's a separate array for each meta transaction data category (the ones that cannot be deduced or extracted from other sources). - -A different approach would be to bitpack all data of a meta transaction into one value and then unpack it within the smart contract. The data for a batch of meta transactions would be sent in an array, but there would need to be only one array (of packed data), instead of multiple arrays. - -### Why is nonce not one of the parameters in the reference implementation? - -Meta nonce is used for constructing a signed hash (see the `msgHash` line where a `keccak256` hash is constructed - you'll find a nonce there). - -Since a new nonce has to always be bigger than the previous one by exactly 1, there's no need to include it as a parameter array in the `processMetaBatch()` function, because its value can be deduced. - -This also helps avoid the "Stack too deep" error. - -### Can EIP-2612 nonces mapping be re-used? - -The EIP-2612 (`permit()` function) also requires a nonce mapping. At this point, I'm not sure yet if this mapping should be **re-used** in case a smart contract implements both EIP-3005 and EIP-2612. - -At the first glance, it seems the `nonces` mapping from EIP-2612 could be re-used, but this should be thought through (and tested) for possible security implications. - -### Token transfers - -Token transfers in the reference implementation could alternatively be done by calling the `_transfer()` function (part of the OpenZeppelin ERC-20 implementation), but it would increase the gas usage and it would also revert the whole batch if some meta transaction was invalid (the current implementation just skips it). - -Another gas usage optimization is to assign total relayer fees to the relayer at the end of the function, and not with every token transfer inside the for loop (thus avoiding multiple SSTORE calls that cost 5'000 gas). - -## Backwards Compatibility - -The code implementation of batched meta transactions is backwards compatible with any fungible token standard, for example, ERC-20 (it only extends it with one function). - -## Test Cases - -Link to tests: [https://github.com/defifuture/erc20-batched-meta-transactions/tree/master/test](https://github.com/defifuture/erc20-batched-meta-transactions/tree/master/test). - -## Security Considerations - -Here is a list of potential security issues and how are they addressed in this implementation. - -### Forging a meta transaction - -The solution against a relayer forging a meta transaction is for a user to sign the meta transaction with their private key. - -The `processMetaBatch()` function then verifies the signature using `ecrecover()`. - -### Replay attacks - -The `processMetaBatch()` function is secure against two types of a replay attack: - -**Using the same meta transaction twice in the same token smart contract** - -A nonce prevents a replay attack where a relayer would send the same meta transaction more than once. - -**Using the same meta transaction twice in different token smart contracts** - -A token smart contract address must be added into the signed hash (of a meta transaction). - -This address does not need to be sent as a parameter into the `processMetaBatch()` function. Instead, the function uses `address(this)` when constructing a hash in order to verify the signature. This way a meta transaction not intended for the token smart contract would be rejected (skipped). - -### Signature validation - -Signing a meta transaction and validating the signature is crucial for this whole scheme to work. - -The `processMetaBatch()` function validates a meta transaction signature, and if it's **invalid**, the meta transaction is **skipped** (but the whole on-chain transaction is **not reverted**). - -```solidity -msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - -if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx -} -``` - -Why not reverting the whole on-chain transaction? Because there could be only one problematic meta transaction, and the others should not be dropped just because of one rotten apple. - -That said, it is expected of relayers to validate meta transactions in advance before relaying them. That's why relayers are not entitled to a relayer fee for an invalid meta transaction. - -### Malicious relayer forcing a user into over-spending - -A malicious relayer could delay sending some user's meta transaction until the user would decide to make the token transaction on-chain. - -After that, the relayer would relay the delayed meta transaction which would mean that the user would have made two token transactions (over-spending). - -**Solution:** Each meta transaction should have an "expiry date". This is defined in a form of a block number by which the meta transaction must be relayed on-chain. - -```solidity -function processMetaBatch(... - uint256[] memory blocks, - ...) public returns (bool) { - - //... - - // loop through all meta txs - for (i = 0; i < senders.length; i++) { - - // the meta tx should be processed until (including) the specified block number, otherwise it is invalid - if(block.number > blocks[i]) { - continue; // if current block number is bigger than the requested number, skip this meta tx - } - - //... -``` - -### Front-running attack - -A malicious relayer could scout the Ethereum mempool to steal meta transactions and front-run the original relayer. - -**Solution:** The protection that `processMetaBatch()` function uses is that it requires the meta transaction sender to add the relayer's Ethereum address as one of the values in the hash (which is then signed). - -When the `processMetaBatch()` function generates a hash it includes the `msg.sender` address in it: - -```solidity -msgHash = keccak256(abi.encode(sender, recipients[i], amounts[i], relayerFees[i], newNonce, blocks[i], address(this), msg.sender)); - -if(sender != ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)), sigV[i], sigR[i], sigS[i])) { - continue; // if sig is not valid, skip to the next meta tx -} -``` - -If the meta transaction was "stolen", the signature check would fail because the `msg.sender` address would not be the same as the intended relayer's address. - -### A malicious (or too impatient) user sending a meta transaction with the same nonce through multiple relayers at once - -A user that is either malicious or just impatient could submit a meta transaction with the same nonce (for the same token contract) to various relayers. Only one of them would get the relayer fee (the first one on-chain), while the others would get an invalid meta transaction. - -**Solution:** Relayers could **share a list of their pending meta transactions** between each other (sort of an info mempool). - -The relayers don't have to fear that someone would steal their respective pending transactions, due to the front-running protection (see above). - -If relayers see meta transactions from a certain sender address that have the same nonce and are supposed to be relayed to the same token smart contract, they can decide that only the first registered meta transaction goes through and others are dropped (or in case meta transactions were registered at the same time, the remaining meta transaction could be randomly picked). - -At a minimum, relayers need to share this meta transaction data (in order to detect meta transaction collision): - -- sender address -- token address -- nonce - -### Too big due block number - -The relayer could trick the meta transaction sender into adding too big due block number - this means a block by which the meta transaction must be processed. The block number could be far in the future, for example, 10 years in the future. This means that the relayer would have 10 years to submit the meta transaction. - -**One way** to solve this problem is by adding an upper bound constraint for a block number within the smart contract. For example, we could say that the specified due block number must not be bigger than 100'000 blocks from the current one (this is around 17 days in the future if we assume 15 seconds block time). - -```solidity -// the meta tx should be processed until (including) the specified block number, otherwise it is invalid -if(block.number > blocks[i] || blocks[i] > (block.number + 100000)) { - // If current block number is bigger than the requested due block number, skip this meta tx. - // Also skip if the due block number is too big (bigger than 100'000 blocks in the future). - continue; -} -``` - -This addition could open new security implications, that's why it is left out of this proof-of-concept. But anyone who wishes to implement it should know about this potential constraint, too. - -**The other way** is to keep the `processMetaBatch()` function as it is and rather check for the too big due block number **on the relayer level**. In this case, the user could be notified about the problem and could issue a new meta transaction with another relayer that would have a much lower block parameter (and the same nonce). - -## Copyright - -Copyright and related rights are waived via [CC0](../LICENSE.md). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3005.md diff --git a/EIPS/eip-3009.md b/EIPS/eip-3009.md index 1919a5d0efa13b..66ff691c786e23 100644 --- a/EIPS/eip-3009.md +++ b/EIPS/eip-3009.md @@ -1,536 +1,7 @@ --- eip: 3009 -title: Transfer With Authorization -author: Peter Jihoon Kim (@petejkim), Kevin Britz (@kbrizzle), David Knott (@DavidLKnott) -discussions-to: https://github.com/ethereum/EIPs/issues/3010 -status: Stagnant -type: Standards Track category: ERC -created: 2020-09-28 -requires: 20, 712 +status: Moved --- -## Simple Summary - -A contract interface that enables transferring of fungible assets via a signed authorization. - -## Abstract - -A set of functions to enable meta-transactions and atomic interactions with [ERC-20](./eip-20.md) token contracts via signatures conforming to the [EIP-712](./eip-712.md) typed message signing specification. - -This enables the user to: - -- delegate the gas payment to someone else, -- pay for gas in the token itself rather than in ETH, -- perform one or more token transfers and other operations in a single atomic transaction, -- transfer ERC-20 tokens to another address, and have the recipient submit the transaction, -- batch multiple transactions with minimal overhead, and -- create and perform multiple transactions without having to worry about them failing due to accidental nonce-reuse or improper ordering by the miner. - -## Motivation - -There is an existing spec, [EIP-2612](./eip-2612), that also allows meta-transactions, and it is encouraged that a contract implements both for maximum compatibility. The two primary differences between this spec and EIP-2612 are that: - -- EIP-2612 uses sequential nonces, but this uses random 32-byte nonces, and that -- EIP-2612 relies on the ERC-20 `approve`/`transferFrom` ("ERC-20 allowance") pattern. - -The biggest issue with the use of sequential nonces is that it does not allow users to perform more than one transaction at time without risking their transactions failing, because: - -- DApps may unintentionally reuse nonces that have not yet been processed in the blockchain. -- Miners may process the transactions in the incorrect order. - -This can be especially problematic if the gas prices are very high and transactions often get queued up and remain unconfirmed for a long time. Non-sequential nonces allow users to create as many transactions as they want at the same time. - -The ERC-20 allowance mechanism is susceptible to the [multiple withdrawal attack](https://blockchain-projects.readthedocs.io/multiple_withdrawal.html)/[SWC-114](https://swcregistry.io/docs/SWC-114), and encourages antipatterns such as the use of the "infinite" allowance. The wide-prevalence of upgradeable contracts have made the conditions favorable for these attacks to happen in the wild. - -The deficiencies of the ERC-20 allowance pattern brought about the development of alternative token standards such as the [ERC-777](./eip-777) and [ERC-677](https://github.com/ethereum/EIPs/issues/677). However, they haven't been able to gain much adoption due to compatibility and potential security issues. - -## Specification - -### Event - -```solidity -event AuthorizationUsed( - address indexed authorizer, - bytes32 indexed nonce -); - -// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") -bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; - -// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") -bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; - -/** - * @notice Returns the state of an authorization - * @dev Nonces are randomly generated 32-byte data unique to the authorizer's - * address - * @param authorizer Authorizer's address - * @param nonce Nonce of the authorization - * @return True if the nonce is used - */ -function authorizationState( - address authorizer, - bytes32 nonce -) external view returns (bool); - -/** - * @notice Execute a transfer with a signed authorization - * @param from Payer's address (Authorizer) - * @param to Payee's address - * @param value Amount to be transferred - * @param validAfter The time after which this is valid (unix time) - * @param validBefore The time before which this is valid (unix time) - * @param nonce Unique nonce - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function transferWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; - -/** - * @notice Receive a transfer with a signed authorization from the payer - * @dev This has an additional check to ensure that the payee's address matches - * the caller of this function to prevent front-running attacks. (See security - * considerations) - * @param from Payer's address (Authorizer) - * @param to Payee's address - * @param value Amount to be transferred - * @param validAfter The time after which this is valid (unix time) - * @param validBefore The time before which this is valid (unix time) - * @param nonce Unique nonce - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function receiveWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; -``` - -**Optional:** - -``` -event AuthorizationCanceled( - address indexed authorizer, - bytes32 indexed nonce -); - -// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") -bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; - -/** - * @notice Attempt to cancel an authorization - * @param authorizer Authorizer's address - * @param nonce Nonce of the authorization - * @param v v of the signature - * @param r r of the signature - * @param s s of the signature - */ -function cancelAuthorization( - address authorizer, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s -) external; -``` - - -The arguments `v`, `r`, and `s` must be obtained using the [EIP-712](./eip-712.md) typed message signing spec. - -**Example:** - -``` -DomainSeparator := Keccak256(ABIEncode( - Keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ), - Keccak256("USD Coin"), // name - Keccak256("2"), // version - 1, // chainId - 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 // verifyingContract -)) -``` - -With the domain separator, the typehash, which is used to identify the type of the EIP-712 message being used, and the values of the parameters, you are able to derive a Keccak-256 hash digest which can then be signed using the token holder's private key. - -**Example:** - -``` -// Transfer With Authorization -TypeHash := Keccak256( - "TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" -) -Params := { From, To, Value, ValidAfter, ValidBefore, Nonce } - -// ReceiveWithAuthorization -TypeHash := Keccak256( - "ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)" -) -Params := { From, To, Value, ValidAfter, ValidBefore, Nonce } - -// CancelAuthorization -TypeHash := Keccak256( - "CancelAuthorization(address authorizer,bytes32 nonce)" -) -Params := { Authorizer, Nonce } -``` - -``` -// "‖" denotes concatenation. -Digest := Keecak256( - 0x1901 ‖ DomainSeparator ‖ Keccak256(ABIEncode(TypeHash, Params...)) -) - -{ v, r, s } := Sign(Digest, PrivateKey) -``` - -Smart contract functions that wrap `receiveWithAuthorization` call may choose to reduce the number of arguments by accepting the full ABI-encoded set of arguments for the `receiveWithAuthorization` call as a single argument of the type `bytes`. - -**Example:** - -```solidity -// keccak256("receiveWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)")[0:4] -bytes4 private constant _RECEIVE_WITH_AUTHORIZATION_SELECTOR = 0xef55bec6; - -function deposit(address token, bytes calldata receiveAuthorization) - external - nonReentrant -{ - (address from, address to, uint256 amount) = abi.decode( - receiveAuthorization[0:96], - (address, address, uint256) - ); - require(to == address(this), "Recipient is not this contract"); - - (bool success, ) = token.call( - abi.encodePacked( - _RECEIVE_WITH_AUTHORIZATION_SELECTOR, - receiveAuthorization - ) - ); - require(success, "Failed to transfer tokens"); - - ... -} -``` - -### Use with web3 providers - -The signature for an authorization can be obtained using a web3 provider with the `eth_signTypedData{_v4}` method. - -**Example:** - -```javascript -const data = { - types: { - EIP712Domain: [ - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - ], - TransferWithAuthorization: [ - { name: "from", type: "address" }, - { name: "to", type: "address" }, - { name: "value", type: "uint256" }, - { name: "validAfter", type: "uint256" }, - { name: "validBefore", type: "uint256" }, - { name: "nonce", type: "bytes32" }, - ], - }, - domain: { - name: tokenName, - version: tokenVersion, - chainId: selectedChainId, - verifyingContract: tokenAddress, - }, - primaryType: "TransferWithAuthorization", - message: { - from: userAddress, - to: recipientAddress, - value: amountBN.toString(10), - validAfter: 0, - validBefore: Math.floor(Date.now() / 1000) + 3600, // Valid for an hour - nonce: Web3.utils.randomHex(32), - }, -}; - -const signature = await ethereum.request({ - method: "eth_signTypedData_v4", - params: [userAddress, JSON.stringify(data)], -}); - -const v = "0x" + signature.slice(130, 132); -const r = signature.slice(0, 66); -const s = "0x" + signature.slice(66, 130); -``` - -## Rationale - -### Unique Random Nonce, Instead of Sequential Nonce - -One might say transaction ordering is one reason why sequential nonces are preferred. However, sequential nonces do not actually help achieve transaction ordering for meta transactions in practice: - -- For native Ethereum transactions, when a transaction with a nonce value that is too-high is submitted to the network, it will stay pending until the transactions consuming the lower unused nonces are confirmed. -- However, for meta-transactions, when a transaction containing a sequential nonce value that is too high is submitted, instead of staying pending, it will revert and fail immediately, resulting in wasted gas. -- The fact that miners can also reorder transactions and include them in the block in the order they want (assuming each transaction was submitted to the network by different meta-transaction relayers) also makes it possible for the meta-transactions to fail even if the nonces used were correct. (e.g. User submits nonces 3, 4 and 5, but miner ends up including them in the block as 4,5,3, resulting in only 3 succeeding) -- Lastly, when using different applications simultaneously, in absence of some sort of an off-chain nonce-tracker, it is not possible to determine what the correct next nonce value is if there exists nonces that are used but haven't been submitted and confirmed by the network. -- Under high gas price conditions, transactions can often "get stuck" in the pool for a long time. Under such a situation, it is much more likely for the same nonce to be unintentionally reused twice. For example, if you make a meta-transaction that uses a sequential nonce from one app, and switch to another app to make another meta-transaction before the previous one confirms, the same nonce will be used if the app relies purely on the data available on-chain, resulting in one of the transactions failing. -- In conclusion, the only way to guarantee transaction ordering is for relayers to submit transactions one at a time, waiting for confirmation between each submission (and the order in which they should be submitted can be part of some off-chain metadata), rendering sequential nonce irrelevant. - -### Valid After and Valid Before - -- Relying on relayers to submit transactions for you means you may not have exact control over the timing of transaction submission. -- These parameters allow the user to schedule a transaction to be only valid in the future or before a specific deadline, protecting the user from potential undesirable effects that may be caused by the submission being made either too late or too early. - -### EIP-712 - -- EIP-712 ensures that the signatures generated are valid only for this specific instance of the token contract and cannot be replayed on a different network with a different chain ID. -- This is achieved by incorporating the contract address and the chain ID in a Keccak-256 hash digest called the domain separator. The actual set of parameters used to derive the domain separator is up to the implementing contract, but it is highly recommended that the fields `verifyingContract` and `chainId` are included. - -## Backwards Compatibility - -New contracts benefit from being able to directly utilize EIP-3009 in order to create atomic transactions, but existing contracts may still rely on the conventional ERC-20 allowance pattern (`approve`/`transferFrom`). - -In order to add support for EIP-3009 to existing contracts ("parent contract") that use the ERC-20 allowance pattern, a forwarding contract ("forwarder") can be constructed that takes an authorization and does the following: - -1. Extract the user and deposit amount from the authorization -2. Call `receiveWithAuthorization` to transfer specified funds from the user to the forwarder -3. Approve the parent contract to spend funds from the forwarder -4. Call the method on the parent contract that spends the allowance set from the forwarder -5. Transfer the ownership of any resulting tokens back to the user - -**Example:** - -```solidity -interface IDeFiToken { - function deposit(uint256 amount) external returns (uint256); - - function transfer(address account, uint256 amount) - external - returns (bool); -} - -contract DepositForwarder { - bytes4 private constant _RECEIVE_WITH_AUTHORIZATION_SELECTOR = 0xef55bec6; - - IDeFiToken private _parent; - IERC20 private _token; - - constructor(IDeFiToken parent, IERC20 token) public { - _parent = parent; - _token = token; - } - - function deposit(bytes calldata receiveAuthorization) - external - nonReentrant - returns (uint256) - { - (address from, address to, uint256 amount) = abi.decode( - receiveAuthorization[0:96], - (address, address, uint256) - ); - require(to == address(this), "Recipient is not this contract"); - - (bool success, ) = address(_token).call( - abi.encodePacked( - _RECEIVE_WITH_AUTHORIZATION_SELECTOR, - receiveAuthorization - ) - ); - require(success, "Failed to transfer to the forwarder"); - - require( - _token.approve(address(_parent), amount), - "Failed to set the allowance" - ); - - uint256 tokensMinted = _parent.deposit(amount); - require( - _parent.transfer(from, tokensMinted), - "Failed to transfer the minted tokens" - ); - - uint256 remainder = _token.balanceOf(address(this); - if (remainder > 0) { - require( - _token.transfer(from, remainder), - "Failed to refund the remainder" - ); - } - - return tokensMinted; - } -} -``` - -## Test Cases - -See [EIP3009.test.ts](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts). - -## Implementation - -**EIP3009.sol** -```solidity -abstract contract EIP3009 is IERC20Transfer, EIP712Domain { - // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") - bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; - - // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") - bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; - - mapping(address => mapping(bytes32 => bool)) internal _authorizationStates; - - event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); - - string internal constant _INVALID_SIGNATURE_ERROR = "EIP3009: invalid signature"; - - function authorizationState(address authorizer, bytes32 nonce) - external - view - returns (bool) - { - return _authorizationStates[authorizer][nonce]; - } - - function transferWithAuthorization( - address from, - address to, - uint256 value, - uint256 validAfter, - uint256 validBefore, - bytes32 nonce, - uint8 v, - bytes32 r, - bytes32 s - ) external { - require(now > validAfter, "EIP3009: authorization is not yet valid"); - require(now < validBefore, "EIP3009: authorization is expired"); - require( - !_authorizationStates[from][nonce], - "EIP3009: authorization is used" - ); - - bytes memory data = abi.encode( - TRANSFER_WITH_AUTHORIZATION_TYPEHASH, - from, - to, - value, - validAfter, - validBefore, - nonce - ); - require( - EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, - "EIP3009: invalid signature" - ); - - _authorizationStates[from][nonce] = true; - emit AuthorizationUsed(from, nonce); - - _transfer(from, to, value); - } -} -``` - -**IERC20Transfer.sol** -```solidity -abstract contract IERC20Transfer { - function _transfer( - address sender, - address recipient, - uint256 amount - ) internal virtual; -} -``` - -**EIP712Domain.sol** -```solidity -abstract contract EIP712Domain { - bytes32 public DOMAIN_SEPARATOR; -} -``` - -**EIP712.sol** -```solidity -library EIP712 { - // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") - bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; - - function makeDomainSeparator(string memory name, string memory version) - internal - view - returns (bytes32) - { - uint256 chainId; - assembly { - chainId := chainid() - } - - return - keccak256( - abi.encode( - EIP712_DOMAIN_TYPEHASH, - keccak256(bytes(name)), - keccak256(bytes(version)), - address(this), - bytes32(chainId) - ) - ); - } - - function recover( - bytes32 domainSeparator, - uint8 v, - bytes32 r, - bytes32 s, - bytes memory typeHashAndData - ) internal pure returns (address) { - bytes32 digest = keccak256( - abi.encodePacked( - "\x19\x01", - domainSeparator, - keccak256(typeHashAndData) - ) - ); - address recovered = ecrecover(digest, v, r, s); - require(recovered != address(0), "EIP712: invalid signature"); - return recovered; - } -} -``` - -A fully working implementation of EIP-3009 can be found in [this repository](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/contracts/lib/EIP3009.sol). The repository also includes [an implementation of EIP-2612](https://github.com/CoinbaseStablecoin/eip-3009/blob/master/contracts/lib/EI32612.sol) that uses the EIP-712 library code presented above. - -## Security Considerations - -Use `receiveWithAuthorization` instead of `transferWithAuthorization` when calling from other smart contracts. It is possible for an attacker watching the transaction pool to extract the transfer authorization and front-run the `transferWithAuthorization` call to execute the transfer without invoking the wrapper function. This could potentially result in unprocessed, locked up deposits. `receiveWithAuthorization` prevents this by performing an additional check that ensures that the caller is the payee. Additionally, if there are multiple contract functions accepting receive authorizations, the app developer could dedicate some leading bytes of the nonce could as the identifier to prevent cross-use. - -When submitting multiple transfers simultaneously, be mindful of the fact that relayers and miners will decide the order in which they are processed. This is generally not a problem if the transactions are not dependent on each other, but for transactions that are highly dependent on each other, it is recommended that the signed authorizations are submitted one at a time. - -The zero address must be rejected when using `ecrecover` to prevent unauthorized transfers and approvals of funds from the zero address. The built-in `ecrecover` returns the zero address when a malformed signature is provided. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3009.md diff --git a/EIPS/eip-3026.md b/EIPS/eip-3026.md index eee399550c04f8..560f13bc63a465 100644 --- a/EIPS/eip-3026.md +++ b/EIPS/eip-3026.md @@ -1,20 +1,19 @@ --- eip: 3026 title: BW6-761 curve operations -author: Youssef El Housni (@yelhousni), Michael Connor (@iAmMichaelConnor), Aurore Guillevic +description: Precompiles for BW6-761 curve operations +author: Youssef El Housni (@yelhousni), Michael Connor (@iAmMichaelConnor), Aurore Guillevic , hujw77 (@hujw77) discussions-to: https://ethereum-magicians.org/t/eip-3026-bw6-761-curve-operations/4790 status: Stagnant type: Standards Track category: Core -requires: 2539 created: 2020-10-05 +requires: 2539 --- -## Simple Summary -This precompile adds operations for the BW6-761 curve (from the EY/Inria [research paper](https://eprint.iacr.org/2020/351.pdf)) as a precompile in a set necessary to *efficiently* perform verification of one-layer composed zkSNARKs proofs. - ## Abstract +This precompile adds operations for the BW6-761 curve (from the EY/Inria **Optimized and secure pairing-friendly elliptic curves suitable for one layer proof composition** research paper) as a precompile in a set necessary to *efficiently* perform verification of one-layer composed zkSNARKs proofs. If `block.number >= X` we introduce *seven* separate precompiles to perform the following operations (addresses to be determined): - BW6_G1_ADD - to perform point addition on a curve defined over a prime field @@ -29,20 +28,20 @@ The multiexponentiation operations are a generalization of point multiplication, ## Motivation -This EIP is based on and tends to replace [EIP-2541](https://github.com/matter-labs/EIPs/blob/sw6_wrapping/EIPS/eip-2541.md) for significant performance reasons. In most applications, BW6-761 is used as an outer curve to BLS12-377 considered in [EIP-2539](https://github.com/ethereum/EIPs/pull/2539). +This EIP is based on and tends to replace matter-labs' proposol for significant performance reasons. In most applications, BW6-761 is used as an outer curve to BLS12-377 considered in [EIP-2539](./eip-2539.md). The motivation of this precompile is to allow efficient one-layer composition of SNARK proofs. Currently this is done by Zexe using the BLS12-377/CP6-782 pair of curves. This precompile proposes a replacement of CP6-782 by BW6-761, which allows much faster operations. For example, it was shown that verifying a Groth16 proof with BW6-761 is 30 times faster than with CP6-782. ### Proposed addresses table -|Precompile |Address | -|---|---| -|BW6_G1_ADD | 0x13 | -|BW6_G1_MUL | 0x14 | -|BW6_G1_MULTIEXP | 0x15 | -|BW6_G2_ADD | 0x16 | -|BW6_G2_MUL | 0x17 | -|BW6_G2_MULTIEXP | 0x18 | -|BW6_PAIRING | 0x19 | +| Precompile | Address | +| --------------- | ------- | +| BW6_G1_ADD | 0x1e | +| BW6_G1_MUL | 0x1f | +| BW6_G1_MULTIEXP | 0x20 | +| BW6_G2_ADD | 0x21 | +| BW6_G2_MUL | 0x22 | +| BW6_G2_MULTIEXP | 0x23 | +| BW6_PAIRING | 0x24 | ## Specification @@ -79,9 +78,9 @@ loop_count_1 is negative = false loop_count_2 is negative = false ``` -#### Encoding +### Encoding -##### Field elements encoding: +#### Field elements encoding: To encode points involved in the operation one has to encode elements of only the base field. @@ -89,16 +88,16 @@ The base field element (Fp) is encoded as `96` bytes by performing BigEndian enc If encodings do not follow this spec anywhere during parsing in the precompile, the precompile **MUST** revert with "endoding error". -##### Encoding of uncompressed points: +#### Encoding of uncompressed points: Points in both G1 and G2 can be expressed as `(x, y)` affine coordinates, where `x` and `y` are elements of the base field. Therefore, points in both G1 and G2 are encoded as the byte concatenation of the field element encodings of the `x` and `y` affine coordinates. The total encoding length for a G1/G2 point is thus `192` bytes. -##### Point at infinity encoding: +#### Point at infinity encoding: Also referred as the "zero point". For BW6-761 (`y^2=x^3-1`) and its M-twisted curves (`y^3=x^3+4`), the point with coordinates `(0, 0)` (formal zeros in Fp) is *not* on the curve, and so the encoding of `(0, 0)` is used as a convention to encode the point at infinity. -##### Encoding of scalars for multiplication and multiexponentiation operations: +#### Encoding of scalars for multiplication and multiexponentiation operations: For multiplication and multiexponentiation operations, a scalar is encoded as `64` bytes by performing BigEndian encoding of the corresponding (unsigned) integer. @@ -106,65 +105,74 @@ Note that the main subgroup order for BW6-761 is actually only `377` bits (`48` The corresponding integer **MAY** be greater than the main subgroup order. -#### ABI for operations +### ABI for operations -##### ABI for G1 addition +#### ABI for G1 addition G1 addition call expects `384` bytes as an input that is interpreted as the byte concatenation of two G1 points (point-encoded as `192` bytes each). Output is a point-encoding of the addition operation result. Error cases: + - Either of the points being not on the curve - Input has invalid length - Field element encoding rules apply (obviously) -##### ABI for G1 multiplication +#### ABI for G1 multiplication + G1 multiplication call expects `256` bytes as an input that is interpreted as the byte concatenation of the point-encoding of a G1 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is a point-encoding of the multiplication operation result. Error cases: + - Point being not on the curve - Input has invalid length - Field element encoding rules apply (obviously) - Scalar encoding rules apply (obviously) -##### ABI for G1 multiexponentiation +#### ABI for G1 multiexponentiation G1 multiplication call expects `256*k` bytes as an input that is interpreted as the byte concatenation of `k` slices, each of them being a byte concatenation of the point-encoding of a G1 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is an encoding of the multiexponentiation operation result. Error cases: + - Any of the G1 points being not on the curve - Input has invalid length - Field element encoding rules apply (obviously) - Scalar encoding rules apply (obviously) -##### ABI for G2 addition +#### ABI for G2 addition G2 addition call expects `384` bytes as an input that is interpreted as the byte concatenation of two G2 points (point-encoded as `192` bytes each). Output is a point-encoding of the addition operation result. Error cases: + - Either of points being not on the curve - Input has invalid length - Field elements encoding rules apply (obviously) -##### ABI for G2 multiplication +#### ABI for G2 multiplication + G2 multiplication call expects `256` bytes as an input that is interpreted as the byte concatenation of the point-encoding of a G2 point (`192` bytes) and the encoding of a scalar value (`64` bytes). Output is an encoding of multiplication operation result. Error cases: + - Point being not on the curve must result in error - Field elements encoding rules apply (obviously) - Input has invalid length -##### ABI for G2 multiexponentiation +#### ABI for G2 multiexponentiation G2 multiplication call expects `240*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`192` bytes) and encoding of a scalar value (`48` bytes). Output is an encoding of multiexponentiation operation result. Error cases: + - Any of G2 points being not on the curve must result in error - Field elements encoding rules apply (obviously) - Input has invalid length -##### ABI for pairing +#### ABI for pairing Pairing call expects `384*k` bytes as an input, that is interpreted as the byte concatenation of `k` slices. Each slice has the following structure: + - `192` bytes G1 point encoding - `192` bytes G2 point encoding @@ -174,46 +182,55 @@ Output is `32` bytes representing a boolean: - `0x0000000000000000000000000000000000000000000000000000000000000000` otherwise. Error cases: + - Any of the G1 or G2 points being not on the curve - Any of the G1 or G2 points being not in the correct subgroup - Input has invalid length - Field elements encoding rules apply (obviously) -#### Prevention of DDoS on error handling +### Prevention of DDoS on error handling + +This precompile performs extensive computations and in case of any errors during execution it **MUST** consume all gas from the gas schedule for the corresponding operation. + +### Gas schedule + +#### G1 addition -This precompile performs extensive computations and in case of any errors during execution it **MUST** consume all gas from the the gas schedule for the corresponding operation. +`180` gas -#### Gas schedule +#### G1 multiplication -##### G1 addition -`` gas +`64000` gas -##### G1 multiplication -`` gas +#### G2 addition -##### G2 addition -`` gas +`180` gas -##### G2 multiplication -`` gas +#### G2 multiplication + +`64000` gas + +#### G1/G2 Multiexponentiation -##### G1/G2 Multiexponentiation Discounts table as a vector of pairs `[k, discount]`: ``` - +[[1, 1266], [2, 733], [3, 561], [4, 474], [5, 422], [6, 387], [7, 362], [8, 344], [9, 329], [10, 318], [11, 308], [12, 300], [13, 296], [14, 289], [15, 283], [16, 279], [17, 275], [18, 272], [19, 269], [20, 266], [21, 265], [22, 260], [23, 259], [24, 256], [25, 255], [26, 254], [27, 252], [28, 251], [29, 250], [30, 249], [31, 249], [32, 220], [33, 228], [34, 225], [35, 223], [36, 219], [37, 216], [38, 214], [39, 212], [40, 209], [41, 209], [42, 205], [43, 203], [44, 202], [45, 200], [46, 198], [47, 196], [48, 199], [49, 195], [50, 192], [51, 192], [52, 191], [53, 190], [54, 187], [55, 186], [56, 185], [57, 184], [58, 184], [59, 181], [60, 181], [61, 181], [62, 180], [63, 178], [64, 179], [65, 176], [66, 177], [67, 176], [68, 175], [69, 174], [70, 173], [71, 171], [72, 171], [73, 170], [74, 170], [75, 169], [76, 168], [77, 168], [78, 167], [79, 167], [80, 166], [81, 165], [82, 167], [83, 166], [84, 166], [85, 165], [86, 165], [87, 164], [88, 164], [89, 163], [90, 163], [91, 162], [92, 162], [93, 160], [94, 163], [95, 159], [96, 162], [97, 159], [98, 160], [99, 159], [100, 159], [101, 158], [102, 158], [103, 158], [104, 158], [105, 157], [106, 157], [107, 156], [108, 155], [109, 155], [110, 156], [111, 155], [112, 155], [113, 154], [114, 155], [115, 154], [116, 153], [117, 153], [118, 153], [119, 152], [120, 152], [121, 152], [122, 152], [123, 151], [124, 151], [125, 151], [126, 151], [127, 151], [128, 150]] ``` -`max_discount = ` +`max_discount = 150` -##### Pairing operation -Base cost of the pairing operation is `*k + ` where `k` is a number of pairs. +#### Pairing operation + +Base cost of the pairing operation is `120000*k + 320000` where `k` is a number of pairs. ## Rationale -Gas costs are based on EIP1962 estimation strategy (but do not fully include yet parsing of ABI, decoding and encoding of the result as a byte array). -#### Gas estimation strategy -Gas cost is derived by taking the average timing of the same operations over different implementations and assuming a constant `30 MGas/second`. Since the execution time is machine-specific, this constant is determined based on execution times of [ECRECOVER](https://github.com/matter-labs/eip1962/blob/master/run_bn_pairing_estimate.sh) and [BNPAIR](https://github.com/matter-labs/eip1962/blob/master/run_bn_pairing_estimate.sh) precompiles on my machine and their proposed gas price (`43.5 MGas/s` for ECRECOVER and `16.5 MGas/s` for BNPAIR). Following are the proposed methods to time the precompile operations: +Gas costs are based on [EIP-1962](./eip-1962.md) estimation strategy (but do not fully include yet parsing of ABI, decoding and encoding of the result as a byte array). + +### Gas estimation strategy + +Gas cost is derived by taking the average timing of the same operations over different implementations and assuming a constant `30 MGas/second`. Since the execution time is machine-specific, this constant is determined based on execution times of *ECRECOVER* and *BNPAIR* precompiles on my machine and their proposed gas price (`43.5 MGas/s` for ECRECOVER and `16.5 MGas/s` for BNPAIR). Following are the proposed methods to time the precompile operations: - G1 addition: Average timing of 1000 random samples. - G1 multiplication: Average timing of 1000 samples of random worst-case of double-and-add algorithm (scalar of max bit length and max hamming weight and random base points in G1) @@ -222,13 +239,16 @@ Gas cost is derived by taking the average timing of the same operations over dif - G1 and G2 multiexponentiations: Expected to be performed by the Peppinger algorithm, with a table prepared for discount in case of `k <= 128` points in the multiexponentiation with a discount cup `max_discount` for `k > 128`. To avoid non-integer arithmetic call cost is calculated as `k * multiplication_cost * discount / multiplier` where `multiplier = 1000`, `k` is a number of (scalar, point) pairs for the call, `multiplication_cost` is a corresponding single multiplication call cost for G1/G2. - Pairing: Average timing of 1000 random samples (random points in G1 and G2) for different number of pairs with linear lifting. -#### Multiexponentiation as a separate call +### Multiexponentiation as a separate call + Explicit separate multiexponentiation operation that allows one to save execution time (so gas) by both the algorithm used (namely Peppinger algorithm) and (usually forgotten) by the fact that `CALL` operation in Ethereum is expensive (at the time of writing), so one would have to pay non-negigible overhead if e.g. for multiexponentiation of `100` points would have to call the multipication precompile `100` times and addition for `99` times (roughly `138600` would be saved). -#### Explicit subgroup checks +### Explicit subgroup checks + G2 subgroup check has the same cost as G1 subgroup check. Endomorphisms can be leverages to optimize this operation. ## Backwards Compatibility + There are no backward compatibility questions. ## Test Cases @@ -246,32 +266,39 @@ Requeired properties for basic ops (add/multiply): - Multiplication by the unnormalized scalar `(scalar + group_order) * P = scalar * P` Required properties for pairing operation: + - Degeneracy `e(P, 0*Q) = e(0*P, Q) = 1` - Bilinearity `e(a*P, b*Q) = e(a*b*P, Q) = e(P, a*b*Q)` (internal test, not visible through ABI) -Test vector for all operations are expanded in this [gist](https://gist.github.com/shamatar/506ab3193a7932fe9302a2f3a31a23e8) until it's final. +## Reference Implementation -## Implementation There is a various choice of existing implementations: **Libraries:** -- Rust implementation (EY/Zexe): https://github.com/yelhousni/zexe/tree/youssef/BW6-761-Fq-ABLR-2ML-M -- C++ implementation (EY/libff): https://github.com/EYBlockchain/zk-swap-libff -- Golang implementation (Consensys/gurvy): https://github.com/ConsenSys/gurvy + +- Rust implementation (EY/Zexe): github.com/yelhousni/zexe/tree/youssef/BW6-761-Fq-ABLR-2ML-M +- C++ implementation (EY/libff): github.com/EYBlockchain/zk-swap-libff +- Golang implementation (Consensys/gurvy): github.com/ConsenSys/gurvy **Stand-alone implementation:** -- Golang implementation with Intel assembly (Onur Kilic): https://github.com/kilic/bw6 + +- Golang implementation with Intel assembly (Onur Kilic): github.com/kilic/bw6 **Precompiles:** -- OpenEthereum (EY/Parity): https://github.com/EYBlockchain/solidity-elliptic-curves + +- OpenEthereum (EY/Parity): github.com/EYBlockchain/solidity-elliptic-curves +- Frontier (Parity): github.com/paritytech/frontier/pull/1049/files **Scripts:** -- SageMath and Magma scripts: https://gitlab.inria.fr/zk-curves/bw6-761/ + +- SageMath and Magma scripts: gitlab.inria.fr/zk-curves/bw6-761/ ## Security Considerations + Strictly following the spec will eliminate security implications or consensus implications in a contrast to the previous BN254 precompile. Important topic is a "constant time" property for performed operations. We explicitly state that this precompile **IS NOT REQUIRED** to perform all the operations using constant time algorithms. ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3074.md b/EIPS/eip-3074.md index 216c6b8bbdfef8..5199fd5d2bb8a8 100644 --- a/EIPS/eip-3074.md +++ b/EIPS/eip-3074.md @@ -4,7 +4,7 @@ title: AUTH and AUTHCALL opcodes description: Allow externally owned accounts to delegate control to a contract. author: Sam Wilson (@SamWilsn), Ansgar Dietrichs (@adietrichs), Matt Garnett (@lightclient), Micah Zoltu (@micahzoltu) discussions-to: https://ethereum-magicians.org/t/eip-3074-sponsored-transaction-precompile/4880 -status: Stagnant +status: Review type: Standards Track category: Core created: 2020-10-15 @@ -37,9 +37,9 @@ With the extraordinary growth of tokens on Ethereum, it has become common for EO | Constant | Value | | ---------------- | ------ | -| `MAGIC` | `0x03` | +| `MAGIC` | `0x04` | -`MAGIC` is used for EIP-3074 signatures to prevent signature collisions with other signing formats. +`MAGIC` is used for [EIP-3074](./eip-3074.md) signatures to prevent signature collisions with other signing formats. ### Context Variables @@ -69,10 +69,10 @@ A new opcode `AUTH` shall be created at `0xf6`. It shall take three stack elemen The final two stack arguments (`offset` and `length`) describe a range of memory. The format of the contents of that range is: - - `memory[offset : offset+32 ]` - `yParity` - - `memory[offset+32 : offset+64 ]` - `r` - - `memory[offset+64 : offset+96 ]` - `s` - - `memory[offset+96 : offset+128]` - `commit` + - `memory[offset : offset+1 ]` - `yParity` + - `memory[offset+1 : offset+33]` - `r` + - `memory[offset+33 : offset+65]` - `s` + - `memory[offset+65 : offset+97]` - `commit` #### Output @@ -88,16 +88,18 @@ Memory is not modified by this instruction. #### Behavior -If `length` is greater than 128, the extra bytes are ignored for signature verification (they still incur a gas cost as defined later). Bytes outside the range (in the event `length` is less than 128) are treated as if they had been zeroes. +If `length` is greater than 97, the extra bytes are ignored for signature verification (they still incur a gas cost as defined later). Bytes outside the range (in the event `length` is less than 97) are treated as if they had been zeroes. -`authority` is the address of the account which generated the signature. +`authority` is the address of the account which generated the signature. If `EXTCODESIZE` of `authority` is not zero, consider the operation unsuccessful and unset `authorized`. + +The arguments (`yParity`, `r`, `s`) are interpreted as an ECDSA signature on the secp256k1 curve over the message `keccak256(MAGIC || chainId || nonce || invokerAddress || commit)`, where: -The arguments (`yParity`, `r`, `s`) are interpreted as an ECDSA signature on the secp256k1 curve over the message `keccak256(MAGIC || chainId || paddedInvokerAddress || commit)`, where: - `chainId` is the current chain's [EIP-155](./eip-155.md) unique identifier padded to 32 bytes. - - `paddedInvokerAddress` is the address of the contract executing `AUTH` (or the active state address in the context of `CALLCODE` or `DELEGATECALL`), left-padded with zeroes to a total of 32 bytes (ex. `0x000000000000000000000000AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`). - - `commit`, one of the arguments passed into `AUTH`, is a 32-byte value that can be used to commit to specific additional validity conditions in the invoker's pre-processing logic (e.g. a nonce for replay protection). + - `nonce` is the signer's current nonce, left-padded to 32 bytes. + - `invokerAddress` is the address of the contract executing `AUTH` (or the active state address in the context of `CALLCODE` or `DELEGATECALL`), left-padded with zeroes to a total of 32 bytes (ex. `0x000000000000000000000000AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`). + - `commit`, one of the arguments passed into `AUTH`, is a 32-byte value that can be used to commit to specific additional validity conditions in the invoker's pre-processing logic. -Signature validity and signer recovery is handled analogously to transaction signatures, including the stricter `s` range for preventing ECDSA malleability. Note that `yParity` is expected to be `0` or `1`. +Signature validity and signer recovery are handled analogously to transaction signatures, including the stricter `s` range for preventing ECDSA malleability. Note that `yParity` is expected to be `0` or `1`. If the signature is valid and the signer address is equal to `authority`, the context variable `authorized` is set to the `authority`. In particular, this is also true if `authority == tx.origin`, which used to be handled separately in earlier versions of this EIP (see Security Considerations). If the signature is instead invalid or the signer address does not equal `authority`, `authorized` is reset to an unset value. @@ -108,7 +110,8 @@ If the signature is valid and the signer address is equal to `authority`, the co The gas cost for `AUTH` is equal to the sum of: - fixed fee `3100`. - - memory expansion gas cost (`auth_memory_expansion_fee`) + - memory expansion gas cost (`auth_memory_expansion_fee`). + - `100` if `authority` is warm, `2600` if it is cold (per [EIP-2929](./eip-2929.md)). The fixed fee is equal to the cost for the `ecrecover` precompile, plus a bit extra to cover a keccak256 hash and some additional logic. @@ -116,7 +119,7 @@ The memory expansion gas cost (`auth_memory_expansion_fee`) shall be calculated ### `AUTHCALL` (`0xf7`) -A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take eight stack elements and return one stack element. It matches the behavior of the existing `CALL` (`0xF1`) instruction, except where noted below. +A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take seven stack elements and return one stack element. It matches the behavior of the existing `CALL` (`0xF1`) instruction, except where noted below. #### Input @@ -125,11 +128,10 @@ A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take eight stack el | `top - 0` | `gas` | | `top - 1` | `addr` | | `top - 2` | `value` | -| `top - 3` | `valueExt` | -| `top - 4` | `argsOffset` | -| `top - 5` | `argsLength` | -| `top - 6` | `retOffset` | -| `top - 7` | `retLength` | +| `top - 3` | `argsOffset` | +| `top - 4` | `argsLength` | +| `top - 5` | `retOffset` | +| `top - 6` | `retLength` | #### Output @@ -146,8 +148,7 @@ A new opcode `AUTHCALL` shall be created at `0xf7`. It shall take eight stack el - If the `gas` operand is equal to `0`, the instruction will send all available gas as per [EIP-150](./eip-150). - If the gas available for the subcall would be less than `gas`, execution is invalid. - There is no gas stipend, even for non-zero `value`. - - `value` is deducted from the balance of the executing contract. It is not paid by `authorized`. If `value` is higher than the balance of the executing contract, execution is invalid. - - If `valueExt` is not zero, the instruction immediately returns 0. In this case the gas that would have been passed into the call is refunded, but not the gas consumed by the `AUTHCALL` opcode itself. In the future, this restriction may be relaxed to externally transfer value out of the `authorized` account. + - `value` is deducted from the balance of `authorized`. If `value` is higher than the balance of `authorized`, execution is invalid. `AUTHCALL` must increase the call depth by one. `AUTHCALL` must not increase the call depth by two as it would if it first called into the authorized account and then into the target. @@ -216,9 +217,9 @@ A well-behaved contract should never reach an `AUTHCALL` without having successf There are two general approaches to separating the "fee payer" from the "action originator". -The first is introducing a new transaction type. This requires significant changes to clients to support and is generally less upgradeable than other solutions (e.g. this EIP). This approach is also not immediately compatible with account abstraction (AA). These proposals require a _signed_ transaction from the sponsor's account, which is not possible from an AA contract, because it has no private key to sign with. The main advantage of new transaction types is that the validity requirements are enforced by the protocol, therefore invalid transactions do not pollute block space. +The first is introducing a new transaction type. This requires significant changes to clients to support and is generally less upgradeable than other solutions (e.g. this EIP). This approach is also not immediately compatible with account abstraction (AA). These proposals require a *signed* transaction from the sponsor's account, which is not possible from an AA contract, because it has no private key to sign with. The main advantage of new transaction types is that the validity requirements are enforced by the protocol, therefore invalid transactions do not pollute block space. -The other main approach is to introduce a new mechanism in the EVM to masquerade as other accounts. This EIP introduces `AUTH` and `AUTHCALL` to make calls as EOAs. There are many different permutations of this mechanism. An alternative mechanism would be add an opcode that can make arbitrary calls based on a similar address creation scheme as `CREATE2`. Although this mechanism would not benefit users today, it would immediately allow for those accounts to send and receive ether -- making it feel like a more first-class primitive. +The other main approach is to introduce a new mechanism in the EVM to masquerade as other accounts. This EIP introduces `AUTH` and `AUTHCALL` to make calls as EOAs. There are many different permutations of this mechanism. An alternative mechanism would be to add an opcode that can make arbitrary calls based on a similar address creation scheme as `CREATE2`. Although this mechanism would not benefit users today, it would immediately allow for those accounts to send and receive ether -- making it feel like a more first-class primitive. Besides better compatibility with AA, introducing a new mechanism into the EVM is a much less intrusive change than a new transaction type. This approach requires no changes in existing wallets, and little change in other tooling. @@ -228,7 +229,7 @@ More logic can be implemented around the `AUTHCALL` instruction, giving more con ### What to Sign? -As originally written, this proposal specified a precompile with storage to track nonces. Since a precompile with storage is unprecedented, a revision moved replay protection into the invoker contract, necessitating a certain level of user trust in the invoker. Expanding on this idea of trusted invokers, the other signed fields were eventually eliminated, one by one, until only `invoker` and `commit` remained. +As originally written, this proposal specified a precompile with storage to track nonces. Since a precompile with storage is unprecedented, a revision moved replay protection into the invoker contract, necessitating a certain level of user trust in the invoker. Expanding on this idea of trusted invokers, the other signed fields were eventually eliminated, one by one, until only `invoker` and `commit` remained. To appease concerns about cross-chain replay attacks and irrevocable signatures, the `chainId` and `nonce` fields returned to the signed message. The `invoker` binds a particular signed message to a single invoker. If invoker was not part of the message, any invoker could reuse the signature to completely compromise the EOA. This allows users to trust that their message will be validated as they expect, particularly the values committed to in `commit`. @@ -236,18 +237,22 @@ The `invoker` binds a particular signed message to a single invoker. If invoker Earlier iterations of this EIP included mechanisms for replay protection, and also signed over value, gas, and other arguments to `AUTHCALL`. After further investigation, we revised this EIP to its current state: explicitly delegate these responsibilities to the invoker contract. -A user will specifically interact with an invoker they trust. Because they trust this contract to execute faithfully, they will "commit" to certain properties of a call they would like to make by computing a hash of the call values. They can be certain that the invoker will only allow they call to proceed if it is able to verify the values committed to (e.g. a nonce to protect against replay attacks). This certainty arises from the `commit` value that is signed over by the user. This is the hash of values which the invoker will validate. A safe invoker should accept the values from the user and compute the commit hash itself. This ensures that invoker operated on the same input that user authorized. +A user will specifically interact with an invoker they trust. Because they trust this contract to execute faithfully, they will "commit" to certain properties of a call they would like to make by computing a hash of the call values. They can be certain that the invoker will only allow the call to proceed if it is able to verify the values committed to (e.g. a nonce to protect against replay attacks). This certainty arises from the `commit` value that is signed over by the user. This is the hash of values which the invoker will validate. A safe invoker should accept the values from the user and compute the commit hash itself. This ensures that invoker operated on the same input that user authorized. ![auth message format](../assets/eip-3074/auth-msg.png) -Using `commit` as a hash of values allows for invokers to implement arbitrary constraints. For example, they could allow accounts to have `N` parallel nonces. Or, they could allow a user to commit to multiple calls with a single signature. This would allow mult-tx flows, such as ERC-20 `approve`-`transfer` actions, to be condensed into a single transaction with a single signature verification. A commitment to multiple calls would look something like the diagram below. +Using `commit` as a hash of values allows for invokers to implement arbitrary constraints. For example, they could allow accounts to have `N` parallel nonces. Or, they could allow a user to commit to multiple calls with a single signature. This would allow multi-tx flows, such as [ERC-20](./eip-20.md) `approve`-`transfer` actions, to be condensed into a single transaction with a single signature verification. A commitment to multiple calls would look something like the diagram below. ![multi-call auth message](../assets/eip-3074/auth-msg-multi-call.png) +Another interesting use is to delegate control of the EOA to other key(s). This would mean the EOA signs a `commit` message with the address of the key(s) and an access policy, if applicable. When the delegate wants to make a call as the EOA it will construct a signature over the invoker-specified call format and relay it (with the actual call data) onto chain with the signature and commit that granted it access to the account. The invoker will then be able to determine that the EOA has allowed this alternative key to make calls on its behalf. + +![delegate auth message](../assets/eip-3074/auth-msg-delegate.png) + ### Invoker Contracts -The invoker contract is a trustless intermediary between the sponsor and sponsee. A sponsee signs over `invoker` to require they transaction to be processed only by a contract they trust. This allows them to interact with sponsors without needing to trust them. +The invoker contract is a trustless intermediary between the sponsor and sponsee. A sponsee signs over `invoker` to require the transaction to be processed only by a contract they trust. This allows them to interact with sponsors without needing to trust them. Choosing an invoker is similar to choosing a smart contract wallet implementation. It's important to choose one that has been thoroughly reviewed, tested, and accepted by the community as secure. We expect a few invoker designs to be utilized by most major transaction relay providers, with a few outliers that offer more novel mechanisms. @@ -261,12 +266,11 @@ It is, therefore, sufficient for the invoker to guarantee a minimum amount of ga ### Source of `value` -Any non-zero `value` passed into an `AUTHCALL` is deducted from the invoker's balance. A natural alternative source for `value` would be the `authorized` account. However, deducting value from an EOA mid-execution is problematic, as it breaks important invariants for handling pending transactions. Specifically: +In previous iterations of this EIP, it was thought that deducting value from an EOA mid-execution was problematic. This was due to an invariant of pending transactions which allows tx pools to statically determine the validity of a given transaction. -* Transaction pools expect transactions for a given EOA to only turn invalid when other transactions from the same EOA are included into a block, increasing its nonce and (possibly) decreasing its balance. Deducting `value` from the `authorized` account would make transaction invalidation an unpredictable side effect of any smart contract execution. -* Similarly, miners rely on the ability to statically pick a set of valid transactions from their transaction pool to include into a new block. Deducting `value` from the `authorized` account would break this ability, increasing the overhead and thus the time for block creation. +However, after further investigation we found that breaking the invariant is safe. This is mostly due to the fact that the worst case is similar in both instances. -At the same time, the ability to directly take ether out of the `authorized` account is an important piece of functionality and thus a desired future addition via an additional opcode similar to `AUTHCALL`. For this reason, it is included as `valueExt`, an operand of `AUTHCALL`, which may be activated in a future fork. The prerequisite for that would be to find satisfying mitigations to the transaction invalidation concerns outlined above. One potential avenue for that could be the addition of account access lists similar to EIP-2930, used to signal accounts whose balance can be reduced as a side effect of the transaction (without on their own constituting authorization to do so). +Currently an attacker can queue many transactions in the tx pool, across many accounts, and invalidate them all at once with a block where each of the queued accounts send a tx moving their entire balance. This attack will become easier and cheaper after this EIP, because it will no longer require direct access to the block builder and will not cost a full 21000 gas to originate each tx. However, the attack does not have a substantial impact on the network, so reducing the difficulty and cost is not of concern. ### Allowing `tx.origin` as Signer @@ -276,30 +280,46 @@ Allowing `authorized` to equal `tx.origin` enables simple transaction batching, 1. Ensuring that `msg.sender` is an EOA (given that `tx.origin` always has to be an EOA). This invariant does not depend on the execution layer depth and, therefore, is not affected. 2. Protecting against atomic sandwich attacks like flash loans, that rely on the ability to modify state before and after the execution of the target contract as part of the same atomic transaction. This protection would be broken by this EIP. However, relying on `tx.origin` in this way is considered bad practice, and can already be circumvented by miners conditionally including transactions in a block. - 3. Preventing re-entrancy. + 3. Preventing reentrancy. -Examples of (1) and (2) can be found in contracts deployed on Ethereum mainnet, with (1) being more common (and unaffected by this proposal.) On the other hand, use case (3) is more severely affected by this proposal, but the authors of this EIP did not find any examples of this form of re-entrancy protection, though the search was non-exhaustive. +Examples of (1) and (2) can be found in contracts deployed on Ethereum mainnet, with (1) being more common (and unaffected by this proposal.) On the other hand, use case (3) is more severely affected by this proposal, but the authors of this EIP did not find any examples of this form of reentrancy protection, though the search was non-exhaustive. This distribution of occurrences—many (1), some (2), and no (3)—is exactly what the authors of this EIP expect, because: - Determining if `msg.sender` is an EOA without `tx.origin` is difficult (if not impossible.) - The only execution context which is safe from atomic sandwich attacks is the topmost context, and `tx.origin == msg.sender` is the only way to detect that context. - - In contrast, there are many direct and flexible ways of preventing re-entrancy (ex. using a storage variable.) Since `msg.sender == tx.origin` is only true in the topmost context, it would make an obscure tool for preventing re-entrancy, rather than other more common approaches. + - In contrast, there are many direct and flexible ways of preventing reentrancy (ex. using a storage variable.) Since `msg.sender == tx.origin` is only true in the topmost context, it would make an obscure tool for preventing reentrancy, rather than other more common approaches. There are other approaches to mitigate this restriction which do not break the invariant: - * Set `tx.origin` to a constant `ENTRY_POINT` address for `AUTHCALL`s. - * Set `tx.origin` to the invoker address for `AUTHCALL`s. - * Set `tx.origin` to a special address derived from any of the sender, invoker, and/or signer addresses. - * Disallow `authorized == tx.origin`. This would make the simple batching use cases impossible, but could be relaxed in the future. + - Set `tx.origin` to a constant `ENTRY_POINT` address for `AUTHCALL`s. + - Set `tx.origin` to the invoker address for `AUTHCALL`s. + - Set `tx.origin` to a special address derived from any of the sender, invoker, and/or signer addresses. + - Disallow `authorized == tx.origin`. This would make the simple batching use cases impossible, but could be relaxed in the future. ### `AUTHCALL` cheaper than `CALL` when sending value Sending non-zero value with `CALL` increases its cost by 9,000. Of that, 6,700 covers the increased overhead of the balance transfer and 2,300 is used as a stipend into the subcall to seed its gas counter. `AUTHCALL` does not provide a stipend and thus only charges the base 6,700. +### In-Protocol Revocation + +This EIP has gone [back and forth](#what-to-sign) on how to deal with `AUTH` message revocation. Without revocation, this EIP is a supremely powerful and flexible primitive for developers. However, it does have risk for users who use insecure and/or actively malicious invokers. + +Much of the risk is due to the new ability for users to batch many operations in a single transaction. It becomes easier for an account to be drained. This is a risk that will continue to grow, regardless of the adoption of this EIP, due to overwhelming desire for the feature and attempts to support it at the protocol level and at the app level. + +A new class of risk is introduced for insecure and buggy invokers. If an invoker has implemented replay protection, as per the authors' recommendation, this should substantially contain the blast radius. However, if the bug allows an adversary to circumvent the replay protection mechanism, it may give them full access to any EOA which has interacted with the vulnerable invoker. + +Although this is a truly catastrophic event which is not expected to be possible via reputable wallets, it is a serious consideration. Without in-protocol revocation, users have no way to remove their account from the vulnerable invoker. + +For this reason, `AUTH` requires the `nonce` in the message to be equal to the signer's current nonce. This way, a single tx from the EOA will cause the nonce to increase, invalidating all outstanding authorizations. + +### Failing on `EXTCODESIZE` check + +In [EIP-3607](./eip-3607), it was determined that the protocol should reject any transaction which originates from an account with code. Although this EIP focused on transaction origination, the authors of EIP-3074 feel the intention is clear: an account that has both code and a known private key should not be allowed to make arbitrary calls on behalf of said account. Therefore, the property is upheld in this EIP. For full rationale, please refer to [EIP-3607](./eip-3607). + ## Backwards Compatibility -Although this EIP poses no issues for backwards compatibility, there are concerns that it limits future changes to accounts by further enshrining ECDSA signatures. For example, it might be desirable to erradicate the concept of EOAs altogether, and replace them with smart contract wallets that emulate the same behavior. This is fully compatible with the EIP as written, however, it gets tricky if users can then elect to "upgrade" their smart contract wallets to use other methods of authentication -- e.g. convert into a multisig. Without any changes, `AUTH` would not respect this new logic and continue allowing the old private key to perform actions on behalf of the account. +Although this EIP poses no issues for backwards compatibility, there are concerns that it limits future changes to accounts by further enshrining ECDSA signatures. For example, it might be desirable to eradicate the concept of EOAs altogether, and replace them with smart contract wallets that emulate the same behavior. This is fully compatible with the EIP as written, however, it gets tricky if users can then elect to "upgrade" their smart contract wallets to use other methods of authentication -- e.g. convert into a multi-sig. Without any changes, `AUTH` would not respect this new logic and continue allowing the old private key to perform actions on behalf of the account. A solution to this would be at the same time that EOAs are removed, to modify the logic of `AUTH` to actually call into the account with some standard message and allow the account to determine if the signature / witness is valid. Further research should be done to understand how invokers would need to change in this situation and how best to write them in a future-compatible manner. @@ -307,24 +327,28 @@ A solution to this would be at the same time that EOAs are removed, to modify th ### Secure Invokers -The following is a non-exhaustive list of checks/pitfalls/conditions that invokers _should_ be wary of: +The following is a non-exhaustive list of checks/pitfalls/conditions that invokers *should* be wary of: - Replay protection (ex. a nonce) should be implemented by the invoker, and included in `commit`. Without it, a malicious actor can reuse a signature, repeating its effects. - `value` should be included in `commit`. Without it, a malicious sponsor could cause unexpected effects in the callee. - `gas` should be included in `commit`. Without it, a malicious sponsor could cause the callee to run out of gas and fail, griefing the sponsee. - `addr` and `calldata` should be included in `commit`. Without them, a malicious actor may call arbitrary functions in arbitrary contracts. -A poorly implemented invoker can _allow a malicious actor to take near complete control over a signer's EOA_. +A poorly implemented invoker can *allow a malicious actor to take near complete control over a signer's EOA*. ### Allowing `tx.origin` as Signer Allowing `authorized` to equal `tx.origin` has the possibility to: - Break atomic sandwich protections which rely on `tx.origin`; - - Break re-entrancy guards of the style `require(tx.origin == msg.sender)`. + - Break reentrancy guards of the style `require(tx.origin == msg.sender)`. The authors of this EIP believe the risks of allowing `authorized` to equal `tx.origin` are acceptable for the reasons outlined in the Rationale section. +### Sponsored Transaction Relayers + +It is possible for the `authorized` account to cause sponsored transaction relayers to spend gas without being reimbursed by either invalidating the authorization (i.e. increasing the account's nonce) or by sweeping the relevant assets out of the account. Relayers should be designed with these cases in mind, possibly by requiring a bond to be deposited or by implementing a reputation system. + ## Copyright Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3076.md b/EIPS/eip-3076.md index 9023b9d95f0f6a..24b8245676872d 100644 --- a/EIPS/eip-3076.md +++ b/EIPS/eip-3076.md @@ -3,17 +3,17 @@ eip: 3076 title: Slashing Protection Interchange Format description: A JSON interchange format for proof of stake validators to migrate slashing protection data between clients. author: Michael Sproul (@michaelsproul), Sacha Saint-Leger (@sachayves), Danny Ryan (@djrtwo) -discussions-to: https://ethereum-magicians.org/t/eip-3076-validator-client-interchange-format-slashing-protection/ +discussions-to: https://ethereum-magicians.org/t/eip-3076-validator-client-interchange-format-slashing-protection/4883 status: Last Call +last-call-deadline: 2021-11-03 type: Standards Track category: Interface created: 2020-10-27 -last-call-deadline: 2021-11-03 --- ## Abstract -A standard format for transferring a key's signing history allows validators to easily switch between clients without the risk of signing conflicting messages. While a [common keystore format](https://eips.ethereum.org/EIPS/eip-2335) provides part of the solution, it does not contain any information about a key's signing history. For a validator moving their keys from client A to client B, this could lead to scenarios in which client B inadvertently signs a message that conflicts with an earlier message signed with client A. The interchange format described here provides a solution to this problem. +A standard format for transferring a key's signing history allows validators to easily switch between clients without the risk of signing conflicting messages. While a common keystore format provides part of the solution, it does not contain any information about a key's signing history. For a validator moving their keys from client A to client B, this could lead to scenarios in which client B inadvertently signs a message that conflicts with an earlier message signed with client A. The interchange format described here provides a solution to this problem. ## Motivation @@ -21,7 +21,7 @@ The proof of stake (PoS) protocol penalises validators for voting in ways that c For a validator following the protocol correctly, there is, in principle, no risk of being slashed. However, changing clients (from client A to client B, say) can result in a slashing risk if client B is unaware of the blocks and attestations that were signed with client A. -This can can occur if client A and client B do not agree on what the present time is. For example, say client A's time is accidentally set to a day in the future (225 epochs), and a validator switches from client A to client B without giving B a record of the blocks and attestations signed with A. The validator in question now runs the risk of attesting to two different blocks in the same epoch (a slashable offence) for the next 225 epochs (since they've already voted on these epochs with client A, and now stand to vote on them again with client B). Such time-skew bugs have been observed in the wild. +This can occur if client A and client B do not agree on what the present time is. For example, say client A's time is accidentally set to a day in the future (225 epochs), and a validator switches from client A to client B without giving B a record of the blocks and attestations signed with A. The validator in question now runs the risk of attesting to two different blocks in the same epoch (a slashable offence) for the next 225 epochs (since they've already voted on these epochs with client A, and now stand to vote on them again with client B). Such time-skew bugs have been observed in the wild. Another situation in which slashing protection is critical is in the case of re-orgs. During a re-org it is possible for a validator to be assigned new attestation duties for an epoch in which it has already signed an attestation. In this case it is essential that the record of the previous attestation is available, even if the validator just moved from one client to another in the space of a single epoch. @@ -168,12 +168,14 @@ A valid interchange file is one that adheres to the following JSON schema, and i After importing an interchange file with data field `data`, a signer must respect the following conditions: -1. Refuse to sign any block that is slashable with respect to the blocks contained in `data.signed_blocks`. For details of what constitutes a slashable block, see [process_proposer_slashing][pps]. If the `signing_root` is absent from a block, a signer must assume that any new block with the same `slot` is slashable with respect to the imported block. +1. Refuse to sign any block that is slashable with respect to the blocks contained in `data.signed_blocks`. For details of what constitutes a slashable block, see `process_proposer_slashing` (from `consensus-specs`). If the `signing_root` is absent from a block, a signer must assume that any new block with the same `slot` is slashable with respect to the imported block. 2. Refuse to sign any block with `slot <= min(b.slot for b in data.signed_blocks if b.pubkey == proposer_pubkey)`, except if it is a repeat signing as determined by the `signing_root`. -3. Refuse to sign any attestation that is slashable with respect to the attestations contained in `data.signed_attestations`. For details of what constitutes a slashable attestation, see [is_slashable_attestation_data][isad]. +3. Refuse to sign any attestation that is slashable with respect to the attestations contained in `data.signed_attestations`. For details of what constitutes a slashable attestation, see `is_slashable_attestation_data`. + 4. Refuse to sign any attestation with source epoch less than the minimum source epoch present in that signer's attestations (as seen in `data.signed_attestations`). In pseudocode: + ```python3 source.epoch < min(att.source_epoch @@ -181,7 +183,8 @@ source.epoch < if att.pubkey == attester_pubkey) ``` -5. Refuse to sign any attestation with target epoch less than or equal to the minimum target epoch present in that signer's attestations (as seen in `data.signed_attestations`). In pseudocode: +{:start="5"} +5. Refuse to sign any attestation with target epoch less than or equal to the minimum target epoch present in that signer's attestations (as seen in `data.signed_attestations`), except if it is a repeat signing as determined by the `signing_root`. In pseudocode: ```python3 target_epoch <= @@ -196,14 +199,9 @@ target_epoch <= - A signed block or attestation's `signing_root` refers to the message data (hash tree root) that gets signed with a BLS signature. It allows validators to re-sign and re-broadcast blocks or attestations if asked. -- The `signed_blocks` `signing_root`s are calculated using [`compute_signing_root(block, domain)`][csr]: where `block` is the block (of type `BeaconBlock` or `BeaconBlockHeader`) that was signed, and `domain` is equal to [`compute_domain(DOMAIN_BEACON_PROPOSER, fork, metadata.genesis_validators_root)`][cd]. - -- The `signed_attestations` `signing_root`s are calculated using [`compute_signing_root(attestation, domain)`][csr]: where `attestation` is the attestation (of type `AttestationData`) that was signed, and `domain` is equal to [`compute_domain(DOMAIN_BEACON_ATTESTER, fork, metadata.genesis_validators_root)`][cd]. +- The `signed_blocks` `signing_root`s are calculated using `compute_signing_root(block, domain)`: where `block` is the block (of type `BeaconBlock` or `BeaconBlockHeader`) that was signed, and `domain` is equal to `compute_domain(DOMAIN_BEACON_PROPOSER, fork, metadata.genesis_validators_root)`. -[pps]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#proposer-slashings -[isad]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#is_slashable_attestation_data -[csr]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#compute_signing_root -[cd]: https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/beacon-chain.md#compute_domain +- The `signed_attestations` `signing_root`s are calculated using `compute_signing_root(attestation, domain)`: where `attestation` is the attestation (of type `AttestationData`) that was signed, and `domain` is equal to `compute_domain(DOMAIN_BEACON_ATTESTER, fork, metadata.genesis_validators_root)`. ## Rationale @@ -243,20 +241,20 @@ In order to minimise risk and complexity, the format has been designed to map cl For implementers who use a complete record of signed messages to implement their slashing protection database, we make the following recommendations: -* You MUST ensure that, in addition to importing all of the messages from an interchange, all the [conditions](#conditions) are enforced. In particular, conditions (2), (4) and (5) may not have been enforced by your implementation before adopting the interchange format. Our recommendation is to enforce these rules at all times, to keep the implementation clean and minimise the attack surface. For example: your slashing protection mechanism should not sign a block with a slot number less than, or equal to, the minimum slot number of a previously signed block, _irrespective_ of whether that minimum-slot block was imported from an interchange file, or inserted as part of your database's regular operation. -* If your database records the signing roots of messages in addition to their slot/epochs, you should ensure that imported messages without signing roots are assigned a suitable dummy signing root internally. We suggest using a special "null" value which is distinct from all other signing roots, although a value like `0x0` may be used instead (as it is extremely unlikely to collide with any real signing root). -* Care must be taken to avoid signing messages within a gap in the database (an area of unknown signing activity). This could occur if two interchanges were imported with a large gap between the last entry of the first and the first entry of the second. Signing in this gap is not safe, and would violate conditions (2), (4) and (5). It can be avoided by storing an explicit low watermark in addition to the actual messages of the slashing protection database, or by pruning on import so that the oldest messages from the interchange become the oldest messages in the database. +- You MUST ensure that, in addition to importing all of the messages from an interchange, all the [conditions](#conditions) are enforced. In particular, conditions (2), (4) and (5) may not have been enforced by your implementation before adopting the interchange format. Our recommendation is to enforce these rules at all times, to keep the implementation clean and minimise the attack surface. For example: your slashing protection mechanism should not sign a block with a slot number less than, or equal to, the minimum slot number of a previously signed block, _irrespective_ of whether that minimum-slot block was imported from an interchange file, or inserted as part of your database's regular operation. +- If your database records the signing roots of messages in addition to their slot/epochs, you should ensure that imported messages without signing roots are assigned a suitable dummy signing root internally. We suggest using a special "null" value which is distinct from all other signing roots, although a value like `0x0` may be used instead (as it is extremely unlikely to collide with any real signing root). +- Care must be taken to avoid signing messages within a gap in the database (an area of unknown signing activity). This could occur if two interchanges were imported with a large gap between the last entry of the first and the first entry of the second. Signing in this gap is not safe, and would violate conditions (2), (4) and (5). It can be avoided by storing an explicit low watermark in addition to the actual messages of the slashing protection database, or by pruning on import so that the oldest messages from the interchange become the oldest messages in the database. ### Advice for Minimal Databases For implementers who wish to implement their slashing protection database by storing only the latest block and attestation for each validator, we make the following recommendations: -* During import, make sure you take the _maximum_ slot block and _maximum_ source and target attestations for each validator. Although the [conditions](#conditions) require the minimums to be enforced, taking the maximums from an interchange file and merging them with any existing values in the database is the recommended approach. For example, if the interchange file includes blocks for validator `V` at slots 4, 98 and 243, then the latest signed block for validator `V` should be updated to the one from slot 243. However, if the database has already included a block for this validator at a slot greater than 243, for example, slot 351, then the database's existing value should remain unchanged. +- During import, make sure you take the _maximum_ slot block and _maximum_ source and target attestations for each validator. Although the [conditions](#conditions) require the minimums to be enforced, taking the maximums from an interchange file and merging them with any existing values in the database is the recommended approach. For example, if the interchange file includes blocks for validator `V` at slots 4, 98 and 243, then the latest signed block for validator `V` should be updated to the one from slot 243. However, if the database has already included a block for this validator at a slot greater than 243, for example, slot 351, then the database's existing value should remain unchanged. ### General Recommendations -* To avoid exporting an outdated interchange file -- an action which creates a slashing risk -- your implementation should only allow the slashing protection database to be exported when the validator client or signer is _stopped_ -- in other words, when the client or signer is no longer adding new messages to the database. -* Similarly, your implementation should only allow an interchange file to be imported when the validator client is stopped. +- To avoid exporting an outdated interchange file -- an action which creates a slashing risk -- your implementation should only allow the slashing protection database to be exported when the validator client or signer is _stopped_ -- in other words, when the client or signer is no longer adding new messages to the database. +- Similarly, your implementation should only allow an interchange file to be imported when the validator client is stopped. ## Copyright diff --git a/EIPS/eip-3085.md b/EIPS/eip-3085.md index 1e081ddf3d50ac..22a576b13e2035 100644 --- a/EIPS/eip-3085.md +++ b/EIPS/eip-3085.md @@ -1,49 +1,33 @@ --- eip: 3085 -title: Wallet Add Ethereum Chain RPC Method (`wallet_addEthereumChain`) -author: Erik Marks (@rekmarks), Pedro Gomes (@pedrouid) +title: wallet_addEthereumChain RPC Method +description: Adds an RPC method to add EVM-compatible chains +author: Erik Marks (@rekmarks), Pedro Gomes (@pedrouid), Pandapip1 (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-3085-wallet-addethereumchain/5469 status: Stagnant type: Standards Track category: Interface created: 2020-11-01 -requires: 155, 695 +requires: 155 --- -## Simple Summary - -An RPC method for adding Ethereum chains to wallet applications. - ## Abstract -The `wallet_addEthereumChain` RPC method allows Ethereum applications ("dapps") to suggest chains to be added to the user's wallet application. -The caller must specify a chain ID and some chain metadata. -The wallet application may arbitrarily refuse or accept the request. -`null` is returned if the chain was added, and an error otherwise. - -## Motivation - -All dapps require the user to interact with one or more Ethereum chains in order to function. -Any given chain may or may not be supported by the user's wallet application. -`wallet_addEthereumChain` enables dapps to request chains to be added to the user's wallet. -This enables UX improvements for both dapps and wallets. +This EIP adds a wallet-namespaced RPC method: `wallet_addEtherereumChain`, providing a standard interface for adding chains to Ethereum wallets. ## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC-2119](https://www.ietf.org/rfc/rfc2119.txt). - -### `wallet_addEthereumChain` +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. -The method accepts a single object parameter, with a `chainId` and some chain metadata. -The method returns `null` if the chain was added to the wallet, and an error otherwise. +This proposal defines a new RPC method, `wallet_addEthereumChain`. -The wallet **MAY** reject the request for any reason. +### `wallet_addEthereumChain` -> Note that this method makes **no** statement about whether the wallet should change the user's currently selected chain, if the wallet has a concept thereof. +The `wallet_addEthereumChain` method is used to suggest to the wallet that a new chain be added to the wallet's list of chains. It takes a single parameter and returns `null` if the chain was added successfully, or an error if the chain was not added. -#### Parameters +#### `wallet_addEthereumChain` Parameters -`wallet_addEthereumChain` accepts a single object parameter, specified by the following TypeScript interface: +The `wallet_addEthereumChain` method takes a single parameter, an `EthereumChainAddRequest` object, which is defined as follows: ```typescript interface AddEthereumChainParameter { @@ -60,115 +44,33 @@ interface AddEthereumChainParameter { } ``` -Only the `chainId` is required per this specification, but a wallet **MAY** require any other fields listed, impose additional requirements on them, or ignore them outright. -If a field does not meet the requirements of this specification and the wallet does not ignore the field, the wallet **MUST** reject the request. - -- `chainId` - - **MUST** specify the integer ID of the chain as a hexadecimal string, per the [`eth_chainId`](./eip-695.md) Ethereum RPC method. - - The wallet **SHOULD** compare the specified `chainId` value with the `eth_chainId` return value from the endpoint. - If these values are not identical, the wallet **MUST** reject the request. -- `blockExplorerUrls` - - If provided, **MUST** specify one or more URLs pointing to block explorer web sites for the chain. -- `chainName` - - If provided, **MUST** specify a human-readable name for the chain. -- `iconUrls` - - If provided, **MUST** specify one or more URLs pointing to reasonably sized images that can be used to visually identify the chain. -- `nativeCurrency` - - If provided, **MUST** describe the native currency of the chain using the `name`, `symbol`, and `decimals` fields. - - `decimals` **MUST** be a non-negative integer. - - `name` and `symbol` **SHOULD** be human-readable strings. -- `rpcUrls` - - If provided, **MUST** specify one or more URLs pointing to RPC endpoints that can be used to communicate with the chain. - -All URL strings **MUST** include the protocol component of the URL. -HTTPS **SHOULD** always be used over HTTP. - -#### Returns - -The method **MUST** return `null` if the request was successful, and an error otherwise. - -A request to add a chain that was already added **SHOULD** be considered successful. - -The wallet **MUST NOT** allow the same `chainId` to be added multiple times. -See [Security Considerations](#security-considerations) for more information. - -### Examples - -These examples use JSON-RPC, but the method could be implemented using other RPC protocols. - -To add the Goerli test chain: - -```json -{ - "id": 1, - "jsonrpc": "2.0", - "method": "wallet_addEthereumChain", - "params": [ - { - "chainId": "0x5", - "chainName": "Goerli", - "rpcUrls": ["https://goerli.infura.io/v3/INSERT_API_KEY_HERE"], - "nativeCurrency": { - "name": "Goerli ETH", - "symbol": "gorETH", - "decimals": 18 - }, - "blockExplorerUrls": ["https://goerli.etherscan.io"] - } - ] -} -``` +Only the `chainId` is required per this specification, but a wallet MAY require any other fields listed, impose additional requirements on them, or ignore them outright. -To add POA Network's xDAI chain: - -```json -{ - "id": 1, - "jsonrpc": "2.0", - "method": "wallet_addEthereumChain", - "params": [ - { - "chainId": "0x64", - "chainName": "xDAI Chain", - "rpcUrls": ["https://dai.poa.network"], - "iconUrls": [ - "https://xdaichain.com/fake/example/url/xdai.svg", - "https://xdaichain.com/fake/example/url/xdai.png" - ], - "nativeCurrency": { - "name": "xDAI", - "symbol": "xDAI", - "decimals": 18 - } - } - ] -} -``` +If a field does not meet the requirements of this specification and the wallet does not ignore the field, the wallet MUST reject the request. -In the above example, notice that the `iconUrls` array contains URLs pointing to two different image formats. +The `chainId` is the integer ID of the chain as a hexadecimal string, as per [EIP-155](./eip-155.md). The `blockExplorerUrls`, `iconUrls`, and `rpcUrls` fields are arrays of strings, each of which MUST be a valid URL. The `nativeCurrency` field is an object with `name`, `symbol`, and `decimals` fields, where `decimals` is a non-negative integer, and is to be interpreted like in [EIP-20](./eip-20.md). The `chainName` field is a string that is the human-readable name of the chain. -A success response: +The wallet MUST reject the request if the `chainId` is not a valid hexadecimal string, or if the `chainId` is not a valid chain ID. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "result": null -} -``` +The wallet MUST reject the request if the `rpcUrls` field is not provided, or if the `rpcUrls` field is an empty array. The wallet MUST reject the request if the `rpcUrls` contains any strings that are not valid URLs. The wallet must reject the request if the `chainId` does not match the value of the `eth_chainId` method for any of the RPC urls. -A failure response: +The wallet MUST reject the request if the `nativeCurrency` field is provided, and any of the `name`, `symbol`, or `decimals` fields are missing. The wallet MUST reject the request if the `decimals` field is a negative integer. -```json -{ - "id": 1, - "jsonrpc": "2.0", - "error": { - "code": 4001, - "message": "The user rejected the request." - } -} -``` +The wallet MUST reject the request if the `blockExplorerUrls` field is provided, and any of the URLs are not valid URLs. + +The wallet MUST reject the request if the `iconUrls` field is provided, and any of the URLs are not valid URLs or do not point to a valid image. + +The wallet MUST reject any URLs that use the `file:` or `http:` schemes. + +#### `wallet_addEthereumChain` Returns + +The method MUST return `null` if the request was successful, and an error otherwise. The wallet MAY reject the request for any reason. + +The chain MUST NOT be assumed to be automatically selected by the wallet, even if the wallet does not reject the request. + +A request to add a chain that was already added SHOULD be successful, unless the user declines the request or the validation fails. + +The wallet MUST NOT allow the same `chainId` to be added multiple times. See [Security Considerations](#security-considerations) for more information. ## Rationale @@ -186,8 +88,6 @@ Therefore, all parameters except `chainId` are specified as optional, even thoug This specification does not mandate that the wallet "switches" its "active" or "currently selected" chain after a successful request, if the wallet has a concept thereof. Just like the meaning of "adding" a chain, "switching" between chains is a wallet implementation detail, and therefore out of scope. -For related work, see [EIP-2015](./eip-2015.md). - ## Security Considerations `wallet_addEthereumChain` is a powerful method that exposes the end user to serious risks if implemented incorrectly. @@ -204,7 +104,7 @@ The wallet should: - See the next section for how to handle multiple RPC endpoints. - Only use the submitted chain ID to sign transactions, **never** a chain ID received from an RPC endpoint. - A malicious or faulty endpoint could return arbitrary chain IDs, and potentially cause the user to sign transactions for unintended chains. -- Verify that the specified chain ID matches the return value of `eth_chainId` from the endpoint, as described [above](#parameters). +- Verify that the specified chain ID matches the return value of `eth_chainId` from the endpoint, as described above. ### RPC Endpoints and RPC URLs diff --git a/EIPS/eip-3091.md b/EIPS/eip-3091.md index 7393f572ea25cb..a2174d3c52d2da 100644 --- a/EIPS/eip-3091.md +++ b/EIPS/eip-3091.md @@ -1,7 +1,8 @@ --- eip: 3091 title: Block Explorer API Routes -author: Pedro Gomes (@pedrouid) +description: API Routes for Blockchain explorers +author: Pedro Gomes (@pedrouid), ligi (@ligi) discussions-to: https://ethereum-magicians.org/t/eip-3091-block-explorer-api-routes/4907 status: Stagnant type: Standards Track @@ -9,35 +10,46 @@ category: Interface created: 2020-11-02 --- -## Simple Summary -Standard API Routes for Blockchain explorers - ## Abstract + This proposal brings standardization between block explorers API routes when linking transactions, blocks, accounts and tokens. ## Motivation -Currently wallets will link transactions and accounts to block explorers web pages but as chain diversity and layer two solutions grow it becomes harder to maintain a consistent user experience. Adding new chains or layer two solutions becomes harder given these endpoints are inconsistent. Standardizing the API routes to these links improves interoperability between wallets and block explorers. This EIP makes RPC endpoints like [EIP-2015](./eip-2015.md) more feasible. + +Currently wallets and dapps link transactions and accounts to block explorer web pages but as chain diversity and layer two solutions grow it becomes harder to maintain a consistent user experience. Adding new chains or layer two solutions becomes harder given these endpoints are inconsistent. Standardizing the API routes to these links improves interoperability between wallets and block explorers. ## Specification + Block explorers will route their webpages accordingly for the following data: ### Blocks -`/block/` + +`/block/` ### Transactions -`/tx/` + +`/tx/` ### Accounts -`/address/` -### ERC-20 Tokens -`/token/` +`/address/` + +### Tokens -## Backward Compatibility -This EIP was designed with existing API routes in mind to reduce disruption. Incompatible block explorers should include either 301 redirects to their existing API routes to match this EIP. +`/token/` + +## Rationale + +The particular paths used in this proposal are chosen to be compatible with the majority of existing block explorers. + +## Backwards Compatibility + +Incompatible block explorers can use redirects to their existing API routes in order to conform to this EIP. ## Security Considerations -TBD + +None ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3102.md b/EIPS/eip-3102.md index 00c50d9b6b9043..376a91b14f8412 100644 --- a/EIPS/eip-3102.md +++ b/EIPS/eip-3102.md @@ -2,9 +2,8 @@ eip: 3102 title: Binary trie structure author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin) -status: Draft discussions-to: https://ethresear.ch/t/binary-trie-format/7621 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2020-09-01 diff --git a/EIPS/eip-3135.md b/EIPS/eip-3135.md index bc7133d5c15fea..357486d011dcbc 100644 --- a/EIPS/eip-3135.md +++ b/EIPS/eip-3135.md @@ -1,268 +1,7 @@ --- eip: 3135 -title: Exclusive Claimable Token -author: Zhenyu Sun (@Ungigdu) -discussions-to: https://github.com/ethereum/EIPs/issues/3132 -status: Stagnant -type: Standards Track category: ERC -created: 2020-08-10 -requires: 20 +status: Moved --- -## Simple Summary - -This standard defines a token which can be claimed only by token issuer with payer's signature. - -## Abstract - -This EIP defines a set of additions to the default token standard such as ERC-20, that allows online/offline service providers establish micropayment channels with any number of users by signing and verifying messages about the consumption of token off chain. Using this mechanism will reduce interactions with blockchain to minimal for both participants, thus saving gas and improve performance. - -## Motivation - -There are two main purposes of this EIP, one is to reduce interactions with blockchain, the second is to link Ethereum to real-world payment problems. - -Many small businesses want to build payment system based on blockchain but find it difficult. There are basically two ways: - -1. Directly pay with token. There are many wallet can receive and transfer token but transactions on Ethereum cost gas and take time to confirm. -2. User lock token on payment smart contract and service provider use payment messages signed by user to release token, establishing a micropayment channel. The advantage is interactions with blockchain is reduced and the signing/verifying process is off-chain. But interact with payment contract needs service provider to build a DApp, which require resources many small businesses do not have. Even if they managed to build DApps, they are all different, not standardized. Also, user should have a wallet with DApp browser and has to learn how to use it. - -This EIP helps to standardize the interactions of micropayment system, and make it possible for wallet build a universal UI in the future. - -## Specification - -```solidity - -/// @return Image url of this token or descriptive resources -function iconUrl() external view returns (string memory); - -/// @return Issuer of this token. Only issuer can execute claim function -function issuer() external view returns (address); - -/** - * @notice Remove consumption from payer's deposite - * @dev Check if msg.sender == issuer - * @param from Payer's address - * @param consumption How many token is consumed in this epoch, specified - * @param epoch Epoch increased by 1 after claim or withdraw, at the beginning of each epoch, consumption goes back to 0 - * @param signature Signature of payment message signed by payer -*/ -function claim(address from, uint256 consumption, uint256 epoch, bytes calldata signature) external; - -function transferIssuer(address newIssuer) external; - -/// @notice Move amount from payer's token balance to deposite balance to ensure payment is sufficient -function deposit(uint256 amount) external; - -/** - * @notice Give remaining deposite balance back to "to" account, act as "refund" function - * @dev In prepayment module, withdraw is executed from issuer account - * In lock-release module, withdraw is executed from user account - * @param to the account receiving remaining deposite - * @param amount how many token is returned -*/ -function withdraw(address to, uint256 amount) external; - -function depositBalanceOf(address user) external view returns(uint256 depositBalance, uint256 epoch); - -event Deposit( - address indexed from, - uint256 amount -); - -event Withdraw( - address indexed to, - uint256 amount -); - -event TransferIssuer( - address indexed oldIssuer, - address indexed newIssuer -); - -event Claim( - address indexed from, - address indexed to, - uint256 epoch, - uint256 consumption -); - -``` - -### signature - -the pseudo code generating an ECDSA signature: -``` -sign(keccak256(abi_encode( - "\x19Ethereum Signed Message:\n32", - keccak256(abi_encode( - token_address, - payer_address, - token_issuer, - token_consumption, //calculated by user client - epoch - )) - )) -,private_key) - -``` - -### verification process - -the verification contains check about both signature and token_consumption - -the pseudo code run by verification server is as follows: - -``` - -serving_loop: - - for { - /** - * unpaied_consumption is calculated by provider - * signed_consumption is claimable amount - * tolerance allows payer "owes" provider to a certain degree - */ - //getSignedConsumption returns amount that are already claimable - if(unpaied_consumption < signed_consumption + tolerance){ - informUser("user need charge", unpaied_consumption) - interruptService() - }else{ - isServing() || recoverService() - } - } - -verification_loop: - - for { - message = incomingMessage() - if(recover_signer(message, signature) != payer_address){ - informUser("check signature failed", hash(message)) - continue - } - - /** - * optional: when using echo server to sync messages between verification servers - * more info about this in Security Considerations section - */ - if(query(message) != message){ - informUser("message outdate", hash(message)) - continue - } - - if(epoch != message.epoch || message.consumption > getDepositBalance()){ - informUser("invalid message", epoch, unpaied_consumption) - continue - } - - signed_consumption = message.consumption - save(message) - } - -claim_process: - - if(claim()){ - unpaied_consumption -= signed_consumption - signed_consumption = 0 - epoch+=1 - } - -``` -### About withdraw - -The withdraw function is slightly different based on business models - -1. prepayment model - -In prepayment business model such as using token as recharge card of general store, the user pays (crypto)currency to store in advance for claimable token as recharge card (with bonus or discount). When checking out, the customer signs a message with updated consumption (old consumption + consumption this time) to store and store verifies this message off chain. The shopping process loops without any blockchain involved, until the customer wants to return the card and get money back. Because the store already holds all currency, the withdraw function should be executed by token issuer (store) to return remaining deposit balance after claim. The prepayment model can easily be built into a wallet with QR-code scanning function. - -2. lock-release model - -If we run a paid end-to-end encrypted e-mail service that accepts token as payment, we can use lock-release model. Unlike prepayment, we charge X * N token for an e-mail sent to N recipients. In this "pay for usage" scenario, the counting of services happens on both client and server side. The client should not trust charge amount given by server in case the it's malfunctioning or malicious. When client decide not to trust server, it stops signing messages, but some of token is taken hostage in deposit balance. To fix this problem, the withdraw function should be executed by payer account with limitation such as epoch didn't change in a month. - -## Rationale - -This EIP targets on ERC-20 tokens due to its widespread adoption. However, this extension is designed to be compatible with other token standard. - -The reason we chose to implement those functions in token contract rather than a separate record contract is as follows: -- Token can transfer is more convenient and more general than interact with DApp -- Token is more standardized and has better UI support -- Token is equal to service, make token economy more prosperous -- Remove the approve process - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [ERC-20](./eip-20.md). - -## Implementation - -```solidity - -mapping (address => StampBalance) private _depositBalance; - -struct StampBalance{ - uint256 balance; - uint256 epoch; -} - -function deposit(uint256 value) override external{ - require(value <= _balances[msg.sender]); - _balances[msg.sender] = _balances[msg.sender].sub(value); - _depositBalance[msg.sender].balance = _depositBalance[msg.sender].balance.add(value); - emit Deposit(msg.sender, value); -} - -function withdraw(address to, uint256 value) override onlyIssuer external{ - require(value <= _depositBalance[to].balance); - _depositBalance[to].balance = _depositBalance[to].balance.sub(value); - _depositBalance[to].epoch += 1; - _balances[to] = _balances[to].add(value); - emit Withdraw(to, value); -} - -function depositBalanceOf(address user) override public view returns(uint256 depositBalance, uint256 epoch){ - return (_depositBalance[user].balance, _depositBalance[user].epoch); -} - -// prepayment model -function claim(address from, uint credit, uint epoch, bytes memory signature) override onlyIssuer external{ - require(credit > 0); - require(_depositBalance[from].epoch + 1 == epoch); - require(_depositBalance[from].balance >= credit); - bytes32 message = keccak256(abi.encode(this, from, _issuer, credit, epoch)); - bytes32 msgHash = prefixed(message); - require(recoverSigner(msgHash, signature) == from); - _depositBalance[from].balance = _depositBalance[from].balance.sub(credit); - _balances[_issuer] = _balances[_issuer].add(credit); - _depositBalance[from].epoch += 1; - emit Claim(from, msg.sender, credit, epoch); -} - -function prefixed(bytes32 hash) internal pure returns (bytes32) { - return keccak256(abi.encode("\x19Ethereum Signed Message:\n32", hash)); -} - -function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { - (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig); - return ecrecover(message, v, r, s); -} - -function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) { - require(sig.length == 65); - assembly { - r := mload(add(sig, 32)) - s := mload(add(sig, 64)) - v := byte(0, mload(add(sig, 96))) - } - return (v, r, s); -} - -``` - -## Security Considerations - -By restricting claim function to issuer, there is no race condition on chain layer. However double spending problem may occur when the issuer use multiple verifiers and payer signs many payment messages simultaneously. Some of those messages may get chance to be checked valid though only the message with the largest consumption can be claimed. This problem can be fixed by introducing an echo server which accepts messages from verifiers, returns the message sequentially with largest consumption and biggest epoch number. If a verifier gets an answer different from the message he send, it updates the message from echo server as the last message it receives along with local storage of the status about this payer. Then the verifier asks the payer again for a new message. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3135.md diff --git a/EIPS/eip-3155.md b/EIPS/eip-3155.md index e235e1e157607d..8d55f3e2e2cbf1 100644 --- a/EIPS/eip-3155.md +++ b/EIPS/eip-3155.md @@ -153,7 +153,7 @@ This EIP is fully backward compatible with go-ethereum. OpenEthereum, Besu and N ## Implementation Implementation in [go-ethereum](https://github.com/ethereum/go-ethereum/tree/master/cmd/evm) -Implementation in [OpenEthereum](https://github.com/openethereum/openethereum/tree/master/evmbin) +Implementation in [OpenEthereum](https://github.com/openethereum/openethereum/tree/main/bin/evmbin) Implementation in [Besu](https://github.com/hyperledger/besu/tree/master/ethereum/evmtool) Implementation in [Nethermind](https://github.com/NethermindEth/nethermind/tree/master/src/Nethermind/Nethermind.State.Test.Runner) diff --git a/EIPS/eip-3156.md b/EIPS/eip-3156.md index 07c46fa3cc887e..b3f20e5d49f318 100644 --- a/EIPS/eip-3156.md +++ b/EIPS/eip-3156.md @@ -1,517 +1,7 @@ --- eip: 3156 -title: Flash Loans -author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction) -discussions-to: https://ethereum-magicians.org/t/erc-3156-flash-loans-review-discussion/5077 -status: Final -type: Standards Track category: ERC -created: 2020-11-15 +status: Moved --- -## Simple Summary - -This ERC provides standard interfaces and processes for single-asset flash loans. - -## Abstract - -A flash loan is a smart contract transaction in which a lender smart contract lends assets to a borrower smart contract with the condition that the assets are returned, plus an optional fee, before the end of the transaction. This ERC specifies interfaces for lenders to accept flash loan requests, and for borrowers to take temporary control of the transaction within the lender execution. The process for the safe execution of flash loans is also specified. - -## Motivation - -Flash loans allow smart contracts to lend an amount of tokens without a requirement for collateral, with the condition that they must be returned within the same transaction. - -Early adopters of the flash loan pattern have produced different interfaces and different use patterns. The diversification is expected to intensify, and with it the technical debt required to integrate with diverse flash lending patterns. - -Some of the high level differences in the approaches across the protocols include: -- Repayment approaches at the end of the transaction, where some pull the principal plus the fee from the loan receiver, and others where the loan receiver needs to manually return the principal and the fee to the lender. -- Some lenders offer the ability to repay the loan using a token that is different to what was originally borrowed, which can reduce the overall complexity of the flash transaction and gas fees. -- Some lenders offer a single entry point into the protocol regardless of whether you're buying, selling, depositing or chaining them together as a flash loan, whereas other protocols offer discrete entry points. -- Some lenders allow to flash mint any amount of their native token without charging a fee, effectively allowing flash loans bounded by computational constraints instead of asset ownership constraints. - -## Specification - -A flash lending feature integrates two smart contracts using a callback pattern. These are called the LENDER and the RECEIVER in this EIP. - -### Lender Specification - -A `lender` MUST implement the IERC3156FlashLender interface. -``` -pragma solidity ^0.7.0 || ^0.8.0; -import "./IERC3156FlashBorrower.sol"; - - -interface IERC3156FlashLender { - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view returns (uint256); - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view returns (uint256); - - /** - * @dev Initiate a flash loan. - * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external returns (bool); -} -``` - -The `maxFlashLoan` function MUST return the maximum loan possible for `token`. If a `token` is not currently supported `maxFlashLoan` MUST return 0, instead of reverting. - -The `flashFee` function MUST return the fee charged for a loan of `amount` `token`. If the token is not supported `flashFee` MUST revert. - -The `flashLoan` function MUST include a callback to the `onFlashLoan` function in a `IERC3156FlashBorrower` contract. - -``` -function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data -) external returns (bool) { - ... - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == keccak256("ERC3156FlashBorrower.onFlashLoan"), - "IERC3156: Callback failed" - ); - ... -} -``` - -The `flashLoan` function MUST transfer `amount` of `token` to `receiver` before the callback to the receiver. - -The `flashLoan` function MUST include `msg.sender` as the `initiator` to `onFlashLoan`. - -The `flashLoan` function MUST NOT modify the `token`, `amount` and `data` parameter received, and MUST pass them on to `onFlashLoan`. - -The `flashLoan` function MUST include a `fee` argument to `onFlashLoan` with the fee to pay for the loan on top of the principal, ensuring that `fee == flashFee(token, amount)`. - -The `lender` MUST verify that the `onFlashLoan` callback returns the keccak256 hash of "ERC3156FlashBorrower.onFlashLoan". - -After the callback, the `flashLoan` function MUST take the `amount + fee` `token` from the `receiver`, or revert if this is not successful. - -If successful, `flashLoan` MUST return `true`. - -### Receiver Specification - -A `receiver` of flash loans MUST implement the IERC3156FlashBorrower interface: - -``` -pragma solidity ^0.7.0 || ^0.8.0; - - -interface IERC3156FlashBorrower { - - /** - * @dev Receive a flash loan. - * @param initiator The initiator of the loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param fee The additional amount of tokens to repay. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" - */ - function onFlashLoan( - address initiator, - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) external returns (bytes32); -} -``` - -For the transaction to not revert, `receiver` MUST approve `amount + fee` of `token` to be taken by `msg.sender` before the end of `onFlashLoan`. - -If successful, `onFlashLoan` MUST return the keccak256 hash of "ERC3156FlashBorrower.onFlashLoan". - -## Rationale - -The interfaces described in this ERC have been chosen as to cover the known flash lending use cases, while allowing for safe and gas efficient implementations. - -`flashFee` reverts on unsupported tokens, because returning a numerical value would be incorrect. - -`flashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the lender, and including both the use cases in which the tokens lent are held or minted by the lender. - -`receiver` is taken as a parameter to allow flexibility on the implementation of separate loan initiators and receivers. - -Existing flash lenders all provide flash loans of several token types from the same contract. Providing a `token` parameter in both the `flashLoan` and `onFlashLoan` functions matches closely the observed functionality. - -A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `flashLoan` standard. - -`onFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the `receiver`, and following the `onAction` naming pattern used as well in EIP-667. - -A `initiator` will often be required in the `onFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `initiator` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `amount` will be required in the `onFlashLoan` function, which the lender took as a parameter. An alternative implementation which would embed the `amount` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -A `fee` will often be calculated in the `flashLoan` function, which the `receiver` must be aware of for repayment. Passing the `fee` as a parameter instead of appended to `data` is simple and effective. - -The `amount + fee` are pulled from the `receiver` to allow the `lender` to implement other features that depend on using `transferFrom`, without having to lock them for the duration of a flash loan. An alternative implementation where the repayment is transferred to the `lender` is also possible, but would need all other features in the lender to be also based in using `transfer` instead of `transferFrom`. Given the lower complexity and prevalence of a "pull" architecture over a "push" architecture, "pull" was chosen. - -## Backwards Compatibility - -No backwards compatibility issues identified. - -## Implementation - -### Flash Borrower Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "./interfaces/IERC20.sol"; -import "./interfaces/IERC3156FlashBorrower.sol"; -import "./interfaces/IERC3156FlashLender.sol"; - - -contract FlashBorrower is IERC3156FlashBorrower { - enum Action {NORMAL, OTHER} - - IERC3156FlashLender lender; - - constructor ( - IERC3156FlashLender lender_ - ) { - lender = lender_; - } - - /// @dev ERC-3156 Flash loan callback - function onFlashLoan( - address initiator, - address token, - uint256 amount, - uint256 fee, - bytes calldata data - ) external override returns(bytes32) { - require( - msg.sender == address(lender), - "FlashBorrower: Untrusted lender" - ); - require( - initiator == address(this), - "FlashBorrower: Untrusted loan initiator" - ); - (Action action) = abi.decode(data, (Action)); - if (action == Action.NORMAL) { - // do one thing - } else if (action == Action.OTHER) { - // do another - } - return keccak256("ERC3156FlashBorrower.onFlashLoan"); - } - - /// @dev Initiate a flash loan - function flashBorrow( - address token, - uint256 amount - ) public { - bytes memory data = abi.encode(Action.NORMAL); - uint256 _allowance = IERC20(token).allowance(address(this), address(lender)); - uint256 _fee = lender.flashFee(token, amount); - uint256 _repayment = amount + _fee; - IERC20(token).approve(address(lender), _allowance + _repayment); - lender.flashLoan(this, token, amount, data); - } -} -``` - -### Flash Mint Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "../ERC20.sol"; -import "../interfaces/IERC20.sol"; -import "../interfaces/IERC3156FlashBorrower.sol"; -import "../interfaces/IERC3156FlashLender.sol"; - - -/** - * @author Alberto Cuesta Cañada - * @dev Extension of {ERC20} that allows flash minting. - */ -contract FlashMinter is ERC20, IERC3156FlashLender { - - bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); - uint256 public fee; // 1 == 0.01 %. - - /** - * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`. - */ - constructor ( - string memory name, - string memory symbol, - uint256 fee_ - ) ERC20(name, symbol) { - fee = fee_; - } - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view override returns (uint256) { - return type(uint256).max - totalSupply(); - } - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. Must match the address of this contract. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view override returns (uint256) { - require( - token == address(this), - "FlashMinter: Unsupported currency" - ); - return _flashFee(token, amount); - } - - /** - * @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the ERC3156 callback. - * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. - * @param token The loan currency. Must match the address of this contract. - * @param amount The amount of tokens lent. - * @param data A data parameter to be passed on to the `receiver` for any custom use. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external override returns (bool){ - require( - token == address(this), - "FlashMinter: Unsupported currency" - ); - uint256 fee = _flashFee(token, amount); - _mint(address(receiver), amount); - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS, - "FlashMinter: Callback failed" - ); - uint256 _allowance = allowance(address(receiver), address(this)); - require( - _allowance >= (amount + fee), - "FlashMinter: Repay not approved" - ); - _approve(address(receiver), address(this), _allowance - (amount + fee)); - _burn(address(receiver), amount + fee); - return true; - } - - /** - * @dev The fee to be charged for a given loan. Internal function with no checks. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function _flashFee( - address token, - uint256 amount - ) internal view returns (uint256) { - return amount * fee / 10000; - } -} -``` - -### Flash Loan Reference Implementation - -``` -pragma solidity ^0.8.0; - -import "../interfaces/IERC20.sol"; -import "../interfaces/IERC3156FlashBorrower.sol"; -import "../interfaces/IERC3156FlashLender.sol"; - - -/** - * @author Alberto Cuesta Cañada - * @dev Extension of {ERC20} that allows flash lending. - */ -contract FlashLender is IERC3156FlashLender { - - bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); - mapping(address => bool) public supportedTokens; - uint256 public fee; // 1 == 0.01 %. - - - /** - * @param supportedTokens_ Token contracts supported for flash lending. - * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`. - */ - constructor( - address[] memory supportedTokens_, - uint256 fee_ - ) { - for (uint256 i = 0; i < supportedTokens_.length; i++) { - supportedTokens[supportedTokens_[i]] = true; - } - fee = fee_; - } - - /** - * @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the callback. - * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @param data A data parameter to be passed on to the `receiver` for any custom use. - */ - function flashLoan( - IERC3156FlashBorrower receiver, - address token, - uint256 amount, - bytes calldata data - ) external override returns(bool) { - require( - supportedTokens[token], - "FlashLender: Unsupported currency" - ); - uint256 fee = _flashFee(token, amount); - require( - IERC20(token).transfer(address(receiver), amount), - "FlashLender: Transfer failed" - ); - require( - receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS, - "FlashLender: Callback failed" - ); - require( - IERC20(token).transferFrom(address(receiver), address(this), amount + fee), - "FlashLender: Repay failed" - ); - return true; - } - - /** - * @dev The fee to be charged for a given loan. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function flashFee( - address token, - uint256 amount - ) external view override returns (uint256) { - require( - supportedTokens[token], - "FlashLender: Unsupported currency" - ); - return _flashFee(token, amount); - } - - /** - * @dev The fee to be charged for a given loan. Internal function with no checks. - * @param token The loan currency. - * @param amount The amount of tokens lent. - * @return The amount of `token` to be charged for the loan, on top of the returned principal. - */ - function _flashFee( - address token, - uint256 amount - ) internal view returns (uint256) { - return amount * fee / 10000; - } - - /** - * @dev The amount of currency available to be lent. - * @param token The loan currency. - * @return The amount of `token` that can be borrowed. - */ - function maxFlashLoan( - address token - ) external view override returns (uint256) { - return supportedTokens[token] ? IERC20(token).balanceOf(address(this)) : 0; - } -} - -``` - -## Security Considerations - - -### Verification of callback arguments - -The arguments of `onFlashLoan` are expected to reflect the conditions of the flash loan, but cannot be trusted unconditionally. They can be divided in two groups, that require different checks before they can be trusted to be genuine. - -0. No arguments can be assumed to be genuine without some kind of verification. `initiator`, `token` and `amount` refer to a past transaction that might not have happened if the caller of `onFlashLoan` decides to lie. `fee` might be false or calculated incorrectly. `data` might have been manipulated by the caller. -1. To trust that the value of `initiator`, `token`, `amount` and `fee` are genuine a reasonable pattern is to verify that the `onFlashLoan` caller is in a whitelist of verified flash lenders. Since often the caller of `flashLoan` will also be receiving the `onFlashLoan` callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in `onFlashLoan` are to be trusted. -2. To trust that the value of `data` is genuine, in addition to the check in point 1, it is recommended to verify that the `initiator` belongs to a group of trusted addresses. Trusting the `lender` and the `initiator` is enough to trust that the contents of `data` are genuine. - -### Flash lending security considerations - -#### Automatic approvals -The safest approach is to implement an approval for `amount+fee` before the `flashLoan` is executed. - -Any `receiver` that keeps an approval for a given `lender` needs to include in `onFlashLoan` a mechanism to verify that the initiator is trusted. - -Any `receiver` that includes in `onFlashLoan` the approval for the `lender` to take the `amount + fee` needs to be combined with a mechanism to verify that the initiator is trusted. - -If an unsuspecting contract with a non-reverting fallback function, or an EOA, would approve a `lender` implementing ERC3156, and not immediately use the approval, and if the `lender` would not verify the return value of `onFlashLoan`, then the unsuspecting contract or EOA could be drained of funds up to their allowance or balance limit. This would be executed by an `initiator` calling `flashLoan` on the victim. The flash loan would be executed and repaid, plus any fees, which would be accumulated by the `lender`. For this reason, it is important that the `lender` implements the specification in full and reverts if `onFlashLoan` doesn't return the keccak256 hash for "ERC3156FlashBorrower.onFlashLoan". - -### Flash minting external security considerations - -The typical quantum of tokens involved in flash mint transactions will give rise to new innovative attack vectors. - -#### Example 1 - interest rate attack -If there exists a lending protocol that offers stable interests rates, but it does not have floor/ceiling rate limits and it does not rebalance the fixed rate based on flash-induced liquidity changes, then it could be susceptible to the following scenario: - -FreeLoanAttack.sol -1. Flash mint 1 quintillion STAB -2. Deposit the 1 quintillion STAB + $1.5 million worth of ETH collateral -3. The quantum of your total deposit now pushes the stable interest rate down to 0.00001% stable interest rate -4. Borrow 1 million STAB on 0.00001% stable interest rate based on the 1.5M ETH collateral -5. Withdraw and burn the 1 quint STAB to close the original flash mint -6. You now have a 1 million STAB loan that is practically interest free for perpetuity ($0.10 / year in interest) - -The key takeaway being the obvious need to implement a flat floor/ceiling rate limit and to rebalance the rate based on short term liquidity changes. - -#### Example 2 - arithmetic overflow and underflow -If the flash mint provider does not place any limits on the amount of flash mintable tokens in a transaction, then anyone can flash mint 2^256-1 amount of tokens. - -The protocols on the receiving end of the flash mints will need to ensure their contracts can handle this, either by using a compiler that embeds overflow protection in the smart contract bytecode, or by setting explicit checks. - -### Flash minting internal security considerations - -The coupling of flash minting with business specific features in the same platform can easily lead to unintended consequences. - -#### Example - Treasury draining -Assume a smart contract that flash lends its native token. The same smart contract borrows from a third party when users burn the native token. This pattern would be used to aggregate in the smart contract the collateralized debt of several users into a single account in the third party. The flash mint could be used to cause the lender to borrow to its limit, and then pushing interest rates in the underlying lender, liquidate the flash lender: -1. Flash mint from `lender` a very large amount of FOO. -2. Redeem FOO for BAR, causing `lender` to borrow from `underwriter` all the way to its borrowing limit. -3. Trigger a debt rate increase in `underwriter`, making `lender` undercollateralized. -4. Liquidate the `lender` for profit. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3156.md diff --git a/EIPS/eip-3224.md b/EIPS/eip-3224.md index 0d3ab96f0c6c50..7d22ce6165ce0a 100644 --- a/EIPS/eip-3224.md +++ b/EIPS/eip-3224.md @@ -1,442 +1,7 @@ --- eip: 3224 -title: Described Data -description: Contract method to compute human-readable descriptions for signable data. -author: Richard Moore (@ricmoo), Nick Johnson (@arachnid) -discussions-to: https://github.com/ethereum/EIPs/issues/3225 -status: Stagnant -type: Standards Track category: ERC -created: 2021-01-23 -requires: 191 +status: Moved --- - -## Abstract - -Human-readable descriptions for machine executable operations, -described in higher level machine readable data, so that wallets -can provide meaningful feedback to the user describing the -action the user is about to perform. - - -## Motivation - -When using an Ethereum Wallet (e.g. MetaMask, Clef, Hardware -Wallets) users must accept and authorize signing messages or -sending transactions. - -Due to the complexity of Ethereum transactions, wallets are very -limitd in their ability to provide insight into the contents of -transactions user are approving; outside special-cased support -for common transactions such as ERC20 transfers, this often amounts -to asking the user to sign an opaque blob of binary data. - -This EIP presents a method for dapp developers to enable a more -comfortable user experience by providing wallets with a means -to generate a better description about what the contract claims -will happen. - -It does not address malicious contracts which wish to lie, it -only addresses honest contracts that want to make their user's -life better. We believe that this is a reasonable security model, -as transaction descriptions can be audited at the same time as -contract code, allowing auditors and code reviewers to check that -transaction descriptions are accurate as part of their review. - - -## Specification - -The **description string** and **described data** are generated -simultaneously by evaluating the contract -(i.e. the **describer**), passing the **describer inputs** to the -method: - -```solidity -function eipXXXDescribe(bytes describer_inputs) view returns (string description_string, bytes described_data); -``` - -The method must be executable in a static context, (i.e. any -side effects, such as logX, sstore, etc.), including through -indirect calls may be ignored. - -During evaluation, the `ADDRESS` (i.e. `to`), `CALLER` -(i.e. `from`), `VALUE`, and `GASPRICE` must be the same as the -values for the transaction being described, so that the -code generating the description can rely on them. For signing -**described messages**, `VALUE` should always be 0. - -When executing the bytecode, best efforts should be made to -ensure `BLOCKHASH`, `NUMBER`, `TIMESTAMP` and `DIFFICULTY` -match the `"latest"` block. The `COINBASE` should be the zero -address. - -The method may revert, in which case the signing must be aborted. - - -### New JSON-RPC Methods - -Clients which manage private keys should expose additional -methods for interacting with the related accounts. - -If an user interface is not present or expected for any other -account-based operations, the description strings should be -ignored and the described data used directly. - -These JSON-RPC methods will also be implemented in standard -Ethereum libraries, so the JSON-RPC description is meant more -of a canonical way to describe them. - - -### Signing Described Messages - -```solidity -eth_signDescribedMessage(address, describer, describerInput) -// Result: { -// description: "text/plain;Hello World", -// data: "0x...", // described data -// signature: "0x..." -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to **describer**, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. The `VALUE` during execution must -be 0. - -If the wallet contains a user interface for accepting or -denying signing a message, it should present the description -string to the user. Optionally, a wallet may wish to -additionally provide a way to examine the described data. - -If accepted, the computed **described data** is signed -according to [EIP-191](./eip-191.md), with the *version -byte* of `0x00` and the *version specific data* of describer -address. - -That is: - -``` -0x19 0x00 DESCRIBER_ADDRESS 0xDESCRIBED_DATA -``` - -The returned result includes the **described data**, allowing -dapps that use parameters computed in the contract to be -available. - -### Sending Described Transactions - -```solidity -eth_sendDescribedTransaction(address, { - to: "0x...", - value: 1234, - nonce: 42, - gas: 42000, - gasPrice: 9000000000, - describerInput: "0x1234...", -}) -// Result: { -// description: "text/plain;Hello World", -// transaction: "0x...", // serialized signed transaction -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to the **describer** `to`, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. - -If the wallet contains a user interface for accepting or -denying a transaction, it should present the description string -along with fee and value information. Optionally, a wallet may -wish to additionally provide a way to further examine the -transaction. - -If accepted, the transaction data is set to the computed -**described data**, the derived transaction is signed and sent, -and the **description string** and serialized signed -transaction is returned. - - -### Signing Described Transaction - -```solidity -eth_signDescribedTransaction(address, { - to: "0x...", - value: 1234, - nonce: 42, - gas: 42000, - gasPrice: 9000000000, - describerInput: "0x1234...", -}) -// Result: { -// description: "text/plain;Hello World", -// transaction: "0x...", // serialized signed transaction -// } -``` - -Compute the **description string** and **described data** by -evaluating the call to the **describer** `to`, with the -**describerInput** passed to the ABI encoded call to -`eipXXXDescription(bytes)`. - -If the wallet contains a user interface for accepting or -denying a transaction, it should present the description string -along with fee and value information. Optionally, a wallet may -wish to additionally provide a way to further examine the -transaction. - -If accepted, the transaction data is set to the computed -**described data**, the derived transaction is signed (and not -sent) and the **description string** and serialized signed -transaction is returned. - -### Description Strings - -A **description string** must begin with a mime-type followed -by a semi-colon (`;`). This EIP specifies only the `text/plain` -mime-type, but future EIPs may specify additional types to -enable more rich processing, such as `text/markdown` so that -addresses can be linkable within clients or to enable -multi-locale options, similar to multipart/form-data. - - -## Rationale - -### Meta Description - -There have been many attempts to solve this problem, many of -which attempt to examine the encoded transaction data or -message data directly. - -In many cases, the information that would be necessary for a -meaningful description is not present in the final encoded -transaction data or message data. - -Instead this EIP uses an indirect description of the data. - -For example, the `commit(bytes32)` method of ENS places a -commitement **hash** on-chain. The hash contains the -**blinded** name and address; since the name is blinded, the -encoded data (i.e. the hash) no longer contains the original -values and is insufficient to access the necessary values to -be included in a description. - -By instead describing the commitment indirectly (with the -original information intact: NAME, ADDRESS and SECRET) a -meaningful description can be computed (e.g. "commit to NAME for ADDRESS (with SECRET)") -and the matching data can be computed (i.e. `commit(hash(name, owner, secret))`). - -### Entangling the Contract Address - -To prevent data being signed from one contract being used -against another, the contract address is entanlged into -both the transaction (implicitly via the `to` field) and -in messages by the EIP-191 versions specific data. - -The use of the zero address is reserved. - -### Alternatives - -- NatSpec and company are a class of more complex languages that attempt to describe the encoded data directly. Because of the language complexity they often end up being quite large requiring entire runtime environments with ample processing power and memory, as well as additional sandboxing to reduce security concerns. One goal of this is to reduce the complexity to something that could execute on hardware wallets and other simple wallets. These also describe the data directly, which in many cases (such as blinded data), cannot adequately describe the data at all - -- Custom Languages; due to the complexity of Ethereum transactions, any language used would require a lot of expressiveness and re-inventing the wheel. The EVM already exists (it may not be ideal), but it is there and can handle everything necessary. - -- Format Strings (e.g. Trustless Signing UI Protocol; format strings can only operate on the class of regular languages, which in many cases is insufficient to describe an Ethereum transaction. This was an issue quite often during early attempts at solving this problem. - -- The signTypedData [EIP-712](./eip-712.md) has many parallels to what this EIP aims to solve - -- @TODO: More - - -## Backwards Compatibility - -All signatures for messages are generated using [EIP-191](./eip-191.md) -which had a previously compatible version byte of `0x00`, so -there should be no concerns with backwards compatibility. - - -## Test Cases - -All test cases operate against the published and verified contracts: - -- Formatter: Ropsten @ 0x7a89c0521604008c93c97aa76950198bca73d933 -- TestFormatter: Ropsten @ 0xab3045aa85cbcabb06ed3f3fe968fa5457727270 - -The private key used for signing messages and transactions is: - -``` -privateKey = "0x6283185307179586476925286766559005768394338798750211641949889184" -``` - - -### Messages - -**Example: login with signed message** - -- sends selector login() -- received data with selector doLogin(bytes32 timestamp) - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0xb34e97e800000000000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4" ], - [ SEL("login()") ] - ) - -Output: - Description: text/plain;Log into ethereum.org? - Data: 0x14629d78000000000000000000000000000000000000000000000000000000006010d607 - i.e. encodeWithSelector("doLogin(bytes32)", "0x000000000000000000000000000000000000000000000000000000006010d607" ] - -Signing: - Preimage: 0x1900ab3045aa85cbcabb06ed3f3fe968fa545772727014629d78000000000000000000000000000000000000000000000000000000006010d607 - Signature: 0x8b9def29343c85797a580c5cd3607c06e78a53351219f9ba706b9985c1a3c91e702bf678e07f5daf5ef48b3e3cc581202de233904b72cf2c4f7d714ce92075b21c -``` - -### Transactions - -All transaction test cases use the ropsten network (chainId: 3) -and for all unspecified properties use 0. - -**Example: ERC-20 transfer** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0xa9059cbb000000000000000000000000000000000000000000000000000000000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000002b992b75cbeb6000 - i.e. encode( - [ "bytes4", "address", "uint"], - [ SEL("transfer(address,uint256)"), "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18 ] - ) -Output: - Description: text/plain;Send 3.14159 TOKN to "ricmoose.eth" (0x8ba1f109551bD432803012645Ac136ddd64DBA72)? - Described Data: 0xa9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72 - i.e. encodeWithSelector("transfer(address,uint256)", "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18) - -Signing: - Signed Transaction: 0xf8a280808094ab3045aa85cbcabb06ed3f3fe968fa545772727080b844a9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba7229a0f33ea492d326ac32d9b7ae203c61bf7cf0ac576fb0cf8be8e4c63dc89c90de12a06c8efb28aaf3b70c032b3bd1edfc664578c49f040cf749bb19b000da56507fb2 -``` - -**Example: ERC-20 approve** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x095ea7b3000000000000000000000000000000000000000000000000000000000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000002b992b75cbeb6000 - i.e. encode( - [ "bytes4", "address", "uint"], - [ SEL("approve(address,uint256)"), "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18 ] - ) - -Output: - Description: text/plain;Approve "ricmoose.eth" (0x8ba1f109551bD432803012645Ac136ddd64DBA72) to manage 3.14159 TOKN tokens? - Described Data: 0xa9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72 - i.e. encodeWithSelector("approve(address,uint256)", "0x8ba1f109551bD432803012645Ac136ddd64DBA72", 3.14159e18) - -Signing: - Signed Transaction: 0xf8a280808094ab3045aa85cbcabb06ed3f3fe968fa545772727080b844a9059cbb0000000000000000000000000000000000000000000000002b992b75cbeb60000000000000000000000000008ba1f109551bd432803012645ac136ddd64dba7229a0f33ea492d326ac32d9b7ae203c61bf7cf0ac576fb0cf8be8e4c63dc89c90de12a06c8efb28aaf3b70c032b3bd1edfc664578c49f040cf749bb19b000da56507fb2 -``` - -**Example: ENS commit** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x0f0e373f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000e31f43c1d823afaa67a8c5fbb8348176d225a79e65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b00000000000000000000000000000000000000000000000000000000000000087269636d6f6f7365000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4", "string", "address", "bytes32"], - [ SEL("commit(string,address,bytes32)"), "ricmoose", "0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e", "0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b" ] - ) - -Output: - Description: text/plain;Commit to the ENS name "ricmoose.eth" for 0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e? - Described Data: 0xf14fcbc8e4a4f2bb818545497be34c7ab30e6e87e0001df4ba82e7c8b3f224fbaf255b91 - i.e. encodeWithSelector("commit(bytes32)", makeCommitment("ricmoose", "0xE31f43C1d823AfAA67A8C5fbB8348176d225A79e", "0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b")) - -Signing: - Signed Transaction: 0xf88180808094ab3045aa85cbcabb06ed3f3fe968fa545772727080a4f14fcbc8e4a4f2bb818545497be34c7ab30e6e87e0001df4ba82e7c8b3f224fbaf255b912aa0a62b41d1ebda584fe84cf8a05f61b429fe4ec361e13c17f30a23281106b38a8da00bcdd896fe758d8f0cfac46445a48f76f5e9fe27790d67c51412cb98a12a0844 -``` - -**Example: WETH mint()** - -``` -Input: - Address: 0xab3045AA85cBCaBb06eD3F3FE968fA5457727270 - Describer Input: 0x1249c58b00000000000000000000000000000000000000000000000000000000 - i.e. encode( - [ "bytes4" ], - [ SEL("mint()") ] - ) - Value: 1.23 ether - -Output: - Description: text/plain;Mint 1.23 WETH (spending 1.23 ether)? - Described Data: 0x1249c58b - i.e. encodeWithSelector("mint()") - -Signing: - Signed Transaction: 0xf86980808094ab3045aa85cbcabb06ed3f3fe968fa5457727270881111d67bb1bb0000841249c58b29a012df802e1394a97caab23c15c3a8c931668df4b2d6d604ca23f3f6b836d0aafca0071a2aebef6a9848616b4d618912f2003fb4babde3dba451b5246f866281a654 -``` - -## Reference Implementation - -@TODO (consider adding it as one or more files in `../assets/eip-####/`) - -I will add examples in Solidity and JavaScript. - - -## Security Considerations - -### Escaping Text - -Wallets must be careful when displaying text provided by -contracts and proper efforts must be taken to sanitize -it, for example, be sure to consider: - -- HTML could be embedded to attempt to trick web-based wallets into executing code using the script tag (possibly uploading any private keys to a server) -- In general, extreme care must be used when rendering HTML; consider the ENS names `not-ricmoo.eth` or ` ricmoo.eth`, which if rendered without care would appear as `ricmoo.eth`, which it is not -- Other marks which require escaping could be included, such as quotes (`"`), formatting (`\n` (new line), `\f` (form feed), `\t` (tab), any of many non-standard whitespaces), back-slassh (`\`) -- UTF-8 has had bugs in the past which could allow arbitrary code execution and crashing renderers; consider using the UTF-8 replacement character (or *something*) for code-points outside common planes or common sub-sets within planes -- Homoglyphs attacks -- Right-to-left marks may affect rendering -- Many other things, deplnding on your environment - -### Distinguished Signed Data - -Applications implementing this EIP to sign message data should -ensure there are no collisions within the data which could -result in ambiguously signed data. - -@TODO: Expand on this; compare packed data to ABI encoded data? - -### Enumeration - -If an abort occurs during signing, the response from this call -should match the response from a declined signing request; -otherwise this could be used for enumeration attacks, etc. A -random interactive-scale delay should also be added, otherwise -a < 10ms response could be interpreted as an error. - -### Replayablility - -Transactions contain an explicit nonce, but signed messages do -not. - -For many purposes, such as signing in, a nonce could be -injected (using block.timestamp) into the data. The log in -service can verify this is a recent timestamp. The timestamp -may or may not be omitted from the description string in this -case, as it it largely useful internally only. - -In general, when signing messages a nonce often makes sense to -include to prevent the same signed data from being used in the -future. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3224.md diff --git a/EIPS/eip-3234.md b/EIPS/eip-3234.md index df9e3864da9a96..72fccc38651821 100644 --- a/EIPS/eip-3234.md +++ b/EIPS/eip-3234.md @@ -1,226 +1,7 @@ --- eip: 3234 -title: Batch Flash Loans -author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction) -discussions-to: https://ethereum-magicians.org/t/erc-3234-batch-flash-loans/5271 -status: Stagnant -type: Standards Track category: ERC -created: 2021-01-31 +status: Moved --- -## Simple Summary - -This ERC provides standard interfaces and processes for multiple-asset flash loans. - -## Motivation - -Flash loans of multiple assets, or batch flash loans, are a common offering of flash lenders, and have a strong use case in the simultaneous refinance of several positions between platforms. At the same time, batch flash loans are more complicated to use than single asset flash loans (ER3156). This divergence of use cases and user profiles calls for independent, but consistent, standards for single asset flash loans and batch flash loans. - - -## Specification - -A batch flash lending feature integrates two smart contracts using a callback pattern. These are called the LENDER and the RECEIVER in this EIP. - -### Lender Specification - -A `lender` MUST implement the IERC3234BatchFlashLender interface. -``` -pragma solidity ^0.7.0 || ^0.8.0; -import "./IERC3234BatchFlashBorrower.sol"; - - -interface IERC3234BatchFlashLender { - - /** - * @dev The amount of currency available to be lended. - * @param tokens The currency for each loan in the batch. - * @return The maximum amount that can be borrowed for each loan in the batch. - */ - function maxFlashLoan( - address[] calldata tokens - ) external view returns (uint256[]); - - /** - * @dev The fees to be charged for a given batch loan. - * @param tokens The loan currencies. - * @param amounts The amounts of tokens lent. - * @return The amount of each `token` to be charged for each loan, on top of the returned principal. - */ - function flashFee( - address[] calldata tokens, - uint256[] calldata amounts - ) external view returns (uint256[]); - - /** - * @dev Initiate a batch flash loan. - * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. - * @param tokens The loan currencies. - * @param amounts The amount of tokens lent. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - */ - function batchFlashLoan( - IERC3234BatchFlashBorrower receiver, - address[] calldata tokens, - uint256[] calldata amounts, - bytes[] calldata data - ) external returns (bool); -} -``` - -The `maxFlashLoan` function MUST return the maximum loan possible for each `token`. If a `token` is not currently supported `maxFlashLoan` MUST return 0, instead of reverting. - -The `flashFee` function MUST return the fees charged for each loan of `amount` `token`. If a token is not supported `flashFee` MUST revert. - -The `batchFlashLoan` function MUST include a callback to the `onBatchFlashLoan` function in a `IERC3234BatchFlashBorrower` contract. - -``` -function batchFlashLoan( - IERC3234BatchFlashBorrower receiver, - address[] calldata tokens, - uint256[] calldata amounts, - bytes calldata data -) external returns (bool) { - ... - require( - receiver.onBatchFlashLoan( - msg.sender, - tokens, - amounts, - fees, - data - ) == keccak256("ERC3234BatchFlashBorrower.onBatchFlashLoan"), - "IERC3234: Callback failed" - ); - ... -} -``` - -The `batchFlashLoan` function MUST transfer `amounts[i]` of each `tokens[i]` to `receiver` before the callback to the borrower. - -The `batchFlashLoan` function MUST include `msg.sender` as the `initiator` to `onBatchFlashLoan`. - -The `batchFlashLoan` function MUST NOT modify the `tokens`, `amounts` and `data` parameters received, and MUST pass them on to `onBatchFlashLoan`. - -The `lender` MUST verify that the `onBatchFlashLoan` callback returns the keccak256 hash of "ERC3234BatchFlashBorrower.onBatchFlashLoan". - -The `batchFlashLoan` function MUST include a `fees` argument to `onBatchFlashLoan` with the fee to pay for each individual `token` and `amount` lent, ensuring that `fees[i] == flashFee(tokens[i], amounts[i])`. - -After the callback, for each `token` in `tokens`, the `batchFlashLoan` function MUST take the `amounts[i] + fees[i]` of `tokens[i]` from the `receiver`, or revert if this is not successful. - -If successful, `batchFlashLoan` MUST return `true`. - -### Receiver Specification - -A `receiver` of flash loans MUST implement the IERC3234BatchFlashBorrower interface: - -``` -pragma solidity ^0.7.0 || ^0.8.0; - - -interface IERC3234BatchFlashBorrower { - - /** - * @dev Receive a flash loan. - * @param initiator The initiator of the loan. - * @param tokens The loan currency. - * @param amounts The amount of tokens lent. - * @param fees The additional amount of tokens to repay. - * @param data Arbitrary data structure, intended to contain user-defined parameters. - * @return The keccak256 hash of "ERC3234BatchFlashBorrower.onBatchFlashLoan" - */ - function onBatchFlashLoan( - address initiator, - address[] calldata tokens, - uint256[] calldata amounts, - uint256[] calldata fees, - bytes calldata data - ) external returns (bytes32); -} -``` - -For the transaction to not revert, for each `token` in `tokens`, `receiver` MUST approve `amounts[i] + fees[i]` of `tokens[i]` to be taken by `msg.sender` before the end of `onBatchFlashLoan`. - -If successful, `onBatchFlashLoan` MUST return the keccak256 hash of "ERC3156BatchFlashBorrower.onBatchFlashLoan". - -## Rationale - -The interfaces described in this ERC have been chosen as to cover the known flash lending use cases, while allowing for safe and gas efficient implementations. - -`flashFee` reverts on unsupported tokens, because returning a numerical value would be incorrect. - -`batchFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the lender, and including both the use cases in which the tokens lended are held or minted by the lender. - -`receiver` is taken as a parameter to allow flexibility on the implementation of separate loan initiators and receivers. - -Existing flash lenders (Aave, dYdX and Uniswap) all provide flash loans of several token types from the same contract (LendingPool, SoloMargin and UniswapV2Pair). Providing a `token` parameter in both the `batchFlashLoan` and `onBatchFlashLoan` functions matches closely the observed functionality. - -A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `batchFlashLoan` standard. - -`onBatchFlashLoan` has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the `receiver`, and following the `onAction` naming pattern used as well in EIP-667. - -An `initiator` will often be required in the `onBatchFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `initiator` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `amounts` will be required in the `onBatchFlashLoan` function, which the lender took as a parameter. An alternative implementation which would embed the `amounts` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable. - -The `fees` will often be calculated in the `batchFlashLoan` function, which the `receiver` must be aware of for repayment. Passing the `fees` as a parameter instead of appended to `data` is simple and effective. - -The `amount + fee` are pulled from the `receiver` to allow the `lender` to implement other features that depend on using `transferFrom`, without having to lock them for the duration of a flash loan. An alternative implementation where the repayment is transferred to the `lender` is also possible, but would need all other features in the lender to be also based in using `transfer` instead of `transferFrom`. Given the lower complexity and prevalence of a "pull" architecture over a "push" architecture, "pull" was chosen. - -## Security Considerations - -### Verification of callback arguments - -The arguments of `onBatchFlashLoan` are expected to reflect the conditions of the flash loan, but cannot be trusted unconditionally. They can be divided in two groups, that require different checks before they can be trusted to be genuine. - -0. No arguments can be assumed to be genuine without some kind of verification. `initiator`, `tokens` and `amounts` refer to a past transaction that might not have happened if the caller of `onBatchFlashLoan` decides to lie. `fees` might be false or calculated incorrectly. `data` might have been manipulated by the caller. -1. To trust that the value of `initiator`, `tokens`, `amounts` and `fees` are genuine a reasonable pattern is to verify that the `onBatchFlashLoan` caller is in a whitelist of verified flash lenders. Since often the caller of `batchFlashLoan` will also be receiving the `onBatchFlashLoan` callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in `onBatchFlashLoan` are to be trusted. -2. To trust that the value of `data` is genuine, in addition to the check in point 1, it is recommended that the `receiver` verifies that the `initiator` is in some list of trusted addresses. Trusting the `lender` and the `initiator` is enough to trust that the contents of `data` are genuine. - -### Flash lending security considerations - -#### Automatic approvals for untrusted borrowers -The safest approach is to implement an approval for `amount+fee` before the `batchFlashLoan` is executed. - -Including in `onBatchFlashLoan` the approval for the `lender` to take the `amount + fee` needs to be combined with a mechanism to verify that the borrower is trusted, such as those described above. - -If an unsuspecting contract with a non-reverting fallback function, or an EOA, would approve a `lender` implementing ERC3156, and not immediately use the approval, and if the `lender` would not verify the return value of `onBatchFlashLoan`, then the unsuspecting contract or EOA could be drained of funds up to their allowance or balance limit. This would be executed by a `borrower` calling `batchFlashLoan` on the victim. The flash loan would be executed and repaid, plus any fees, which would be accumulated by the `lender`. For this reason, it is important that the `lender` implements the specification in full and reverts if `onBatchFlashLoan` doesn't return the keccak256 hash for "ERC3156FlashBorrower.onBatchFlashLoan". - -### Flash minting external security considerations - -The typical quantum of tokens involved in flash mint transactions will give rise to new innovative attack vectors. - -#### Example 1 - interest rate attack -If there exists a lending protocol that offers stable interests rates, but it does not have floor/ceiling rate limits and it does not rebalance the fixed rate based on flash-induced liquidity changes, then it could be susceptible to the following scenario: - -FreeLoanAttack.sol -1. Flash mint 1 quintillion DAI -2. Deposit the 1 quintillion DAI + $1.5 million worth of ETH collateral -3. The quantum of your total deposit now pushes the stable interest rate down to 0.00001% stable interest rate -4. Borrow 1 million DAI on 0.00001% stable interest rate based on the 1.5M ETH collateral -5. Withdraw and burn the 1 quint DAI to close the original flash mint -6. You now have a 1 million DAI loan that is practically interest free for perpetuity ($0.10 / year in interest) - -The key takeaway being the obvious need to implement a flat floor/ceiling rate limit and to rebalance the rate based on short term liquidity changes. - -#### Example 2 - arithmetic overflow and underflow -If the flash mint provider does not place any limits on the amount of flash mintable tokens in a transaction, then anyone can flash mint 2^256-1 amount of tokens. - -The protocols on the receiving end of the flash mints will need to ensure their contracts can handle this. One obvious way is to leverage OpenZeppelin's SafeMath libraries as a catch-all safety net, however consideration should be given to when it is or isn't used given the gas tradeoffs. - -If you recall there was a series of incidents in 2018 where exchanges such as OKEx, Poloniex, HitBTC and Huobi had to shutdown deposits and withdrawls of ERC20 tokens due to integer overflows within the ERC20 token contracts. - - -### Flash minting internal security considerations - -The coupling of flash minting with business specific features in the same platform can easily lead to unintended consequences. - -#### Example - Treasury draining -In early implementations of the Yield Protocol flash loaned fyDai could be redeemed for Dai, which could be used to liquidate the Yield Protocol CDP vault in MakerDAO: -1. Flash mint a very large amount of fyDai. -2. Redeem for Dai as much fyDai as the Yield Protocol collateral would allow. -3. Trigger a stability rate increase with a call to `jug.drip` which would make the Yield Protocol uncollateralized. -4. Liquidate the Yield Protocol CDP vault in MakerDAO. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3234.md diff --git a/EIPS/eip-3386.md b/EIPS/eip-3386.md index 81558c2b38439f..45c38d76ceed16 100644 --- a/EIPS/eip-3386.md +++ b/EIPS/eip-3386.md @@ -1,274 +1,7 @@ --- eip: 3386 -title: ERC-721 and ERC-1155 to ERC-20 Wrapper -author: Calvin Koder (@ashrowz) -discussions-to: https://github.com/ethereum/EIPs/issues/3384 -status: Stagnant -type: Standards Track category: ERC -created: 2021-03-12 -requires: 165 +status: Moved --- -## Simple Summary -A standard interface for contracts that create generic ERC-20 tokens which derive from a pool of unique ERC-721/ERC-1155 tokens. - -## Abstract - -This standard outlines a smart contract interface to wrap identifiable tokens with fungible tokens. This allows for derivative [ERC-20](./eip-20.md) tokens to be minted by locking the base [ERC-721](./eip-721.md) non-fungible tokens and [ERC-1155](./eip-1155.md) multi tokens into a pool. The derivative tokens can be burned to redeem base tokens out of the pool. These derivatives have no reference to the unique id of these base tokens, and should have a proportional rate of exchange with the base tokens. As representatives of the base tokens, these generic derivative tokens can be traded and otherwise utilized according to ERC-20, such that the unique identifier of each base token is irrelevant. - -ERC-721 and ERC-1155 tokens are considered valid base, tokens because they have unique identifiers and are transferred according to similar rules. This allows for both ERC-721 NFTs and ERC-1155 Multi-Tokens to be wrapped under a single common interface. - -## Motivation - -The ERC-20 token standard is the most widespread and liquid token standard on Ethereum. ERC-721 and ERC-1155 tokens on the other hand can only be transferred by their individual ids, in whole amounts. Derivative tokens allow for exposure to the base asset while benefiting from contracts which utilize ERC-20 tokens. This allows for the base tokens to be fractionalized, traded and pooled generically on AMMs, collateralized, and be used for any other ERC-20 type contract. Several implementations of this proposal already exist without a common standard. - -Given a fixed exchange rate between base and derivative tokens, the value of the derivative token is proportional to the floor price of the pooled tokens. With the derivative tokens being used in AMMs, there is opportunity for arbitrage between derived token markets and the base NFT markets. By specifying a subset of base tokens which may be pooled, the difference between the lowest and highest value token in the pool may be minimized. This allows for higher value tokens within a larger set to be poolable. Additionally, price calculations using methods such as Dutch auctions, as implemented by NFT20, allow for price discovery of subclasses of base tokens. This allows the provider of a higher value base token to receive a proportionally larger number of derivative tokens than a token worth the floor price would receive. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt). - -**Every IWrapper compliant contract must implement the `IWrapper` and `ERC165` interfaces** : - - -```solidity -pragma solidity ^0.8.0; - -/** - @title IWrapper Identifiable Token Wrapper Standard - @dev {Wrapper} refers to any contract implementing this interface. - @dev {Base} refers to any ERC-721 or ERC-1155 contract. It MAY be the {Wrapper}. - @dev {Pool} refers to the contract which holds the {Base} tokens. It MAY be the {Wrapper}. - @dev {Derivative} refers to the ERC-20 contract which is minted/burned by the {Wrapper}. It MAY be the {Wrapper}. - @dev All uses of "single", "batch" refer to the number of token ids. This includes individual ERC-721 tokens by id, and multiple ERC-1155 by id. An ERC-1155 `TransferSingle` event may emit with a `value` greater than `1`, but it is still considered a single token. - @dev All parameters named `_amount`, `_amounts` refer to the `value` parameters in ERC-1155. When using this interface with ERC-721, `_amount` MUST be 1, and `_amounts` MUST be either an empty list or a list of 1 with the same length as `_ids`. -*/ -interface IWrapper /* is ERC165 */ { - /** - * @dev MUST emit when a mint occurs where a single {Base} token is received by the {Pool}. - * The `_from` argument MUST be the address of the account that sent the {Base} token. - * The `_to` argument MUST be the address of the account that received the {Derivative} token(s). - * The `_id` argument MUST be the id of the {Base} token transferred. - * The `_amount` argument MUST be the number of {Base} tokens transferred. - * The `_value` argument MUST be the number of {Derivative} tokens minted. - */ - event MintSingle (address indexed _from, address indexed _to, uint256 _id, uint256 _amount, uint256 _value); - - /** - * @dev MUST emit when a mint occurs where multiple {Base} tokens are received by the {Wrapper}. - * The `_from` argument MUST be the address of the account that sent the {Base} tokens. - * The `_to` argument MUST be the address of the account that received the {Derivative} token(s). - * The `_ids` argument MUST be the list ids of the {Base} tokens transferred. - * The `_amounts` argument MUST be the list of the numbers of {Base} tokens transferred. - * The `_value` argument MUST be the number of {Derivative} tokens minted. - */ - event MintBatch (address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts, uint256 _value); - - /** - * @dev MUST emit when a burn occurs where a single {Base} token is sent by the {Wrapper}. - * The `_from` argument MUST be the address of the account that sent the {Derivative} token(s). - * The `_to` argument MUST be the address of the account that received the {Base} token. - * The `_id` argument MUST be the id of the {Base} token transferred. - * The `_amount` argument MUST be the number of {Base} tokens transferred. - * The `_value` argument MUST be the number of {Derivative} tokens burned. - */ - event BurnSingle (address indexed _from, address indexed _to, uint256 _id, uint256 _amount, uint256 _value); - - /** - * @dev MUST emit when a mint occurs where multiple {Base} tokens are sent by the {Wrapper}. - * The `_from` argument MUST be the address of the account that sent the {Derivative} token(s). - * The `_to` argument MUST be the address of the account that received the {Base} tokens. - * The `_ids` argument MUST be the list of ids of the {Base} tokens transferred. - * The `_amounts` argument MUST be the list of the numbers of {Base} tokens transferred. - * The `_value` argument MUST be the number of {Derivative} tokens burned. - */ - event BurnBatch (address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts, uint256 _value); - - /** - * @notice Transfers the {Base} token with `_id` from `msg.sender` to the {Pool} and mints {Derivative} token(s) to `_to`. - * @param _to Target address. - * @param _id Id of the {Base} token. - * @param _amount Amount of the {Base} token. - * - * Emits a {MintSingle} event. - */ - function mint( - address _to, - uint256 _id, - uint256 _amount - ) external; - - /** - * @notice Transfers `_amounts[i]` of the {Base} tokens with `_ids[i]` from `msg.sender` to the {Pool} and mints {Derivative} token(s) to `_to`. - * @param _to Target address. - * @param _ids Ids of the {Base} tokens. - * @param _amounts Amounts of the {Base} tokens. - * - * Emits a {MintBatch} event. - */ - function batchMint( - address _to, - uint256[] calldata _ids, - uint256[] calldata _amounts - ) external; - - /** - * @notice Burns {Derivative} token(s) from `_from` and transfers `_amounts` of some {Base} token from the {Pool} to `_to`. No guarantees are made as to what token is withdrawn. - * @param _from Source address. - * @param _to Target address. - * @param _amount Amount of the {Base} tokens. - * - * Emits either a {BurnSingle} or {BurnBatch} event. - */ - function burn( - address _from, - address _to, - uint256 _amount - ) external; - - /** - * @notice Burns {Derivative} token(s) from `_from` and transfers `_amounts` of some {Base} tokens from the {Pool} to `_to`. No guarantees are made as to what tokens are withdrawn. - * @param _from Source address. - * @param _to Target address. - * @param _amounts Amounts of the {Base} tokens. - * - * Emits either a {BurnSingle} or {BurnBatch} event. - */ - function batchBurn( - address _from, - address _to, - uint256[] calldata _amounts - ) external; - - /** - * @notice Burns {Derivative} token(s) from `_from` and transfers `_amounts[i]` of the {Base} tokens with `_ids[i]` from the {Pool} to `_to`. - * @param _from Source address. - * @param _to Target address. - * @param _id Id of the {Base} token. - * @param _amount Amount of the {Base} token. - * - * Emits either a {BurnSingle} or {BurnBatch} event. - */ - function idBurn( - address _from, - address _to, - uint256 _id, - uint256 _amount - ) external; - - /** - * @notice Burns {Derivative} tokens from `_from` and transfers `_amounts[i]` of the {Base} tokens with `_ids[i]` from the {Pool} to `_to`. - * @param _from Source address. - * @param _to Target address. - * @param _ids Ids of the {Base} tokens. - * @param _amounts Amounts of the {Base} tokens. - * - * Emits either a {BurnSingle} or {BurnBatch} event. - */ - function batchIdBurn( - address _from, - address _to, - uint256[] calldata _ids, - uint256[] calldata _amounts - ) external; -} -``` - -## Rationale - -### Naming - -The ERC-721/ERC-1155 tokens which are pooled are called {Base} tokens. Alternative names include: -- Underlying. -- NFT. However, ERC-1155 tokens may be considered "semi-fungible". - -The ERC-20 tokens which are minted/burned are called {Derivative} tokens. Alternative names include: -- Wrapped. -- Generic. - -The function names `mint` and `burn` are borrowed from the minting and burning extensions to ERC-20. Alternative names include: -- `mint`/`redeem` ([NFTX](https://nftx.org)) -- `deposit`/`withdraw` ([WrappedKitties](https://wrappedkitties.com/)) -- `wrap`/`unwrap` ([MoonCatsWrapped](https://etherscan.io/address/0x7c40c393dc0f283f318791d746d894ddd3693572)) - -The function names `*idBurn` are chosen to reduce confusion on what is being burned. That is, the {Derivative} tokens are burned in order to redeem the id(s). - -The wrapper/pool itself can be called an "Index fund" according to NFTX, or a "DEX" according to [NFT20](https://nft20.io). However, the {NFT20Pair} contract allows for direct NFT-NFT swaps which are out of the scope of this standard. - -### Minting -Minting requires the transfer of the {Base} tokens into the {Pool} in exchange for {Derivative} tokens. The {Base} tokens deposited in this way MUST NOT be transferred again except through the burning functions. This ensures the value of the {Derivative} tokens is representative of the value of the {Base} tokens. - -Alternatively to transferring the {Base} tokens into the {Pool}, the tokens may be locked as collateral in exchange for {Derivative} loans, as proposed in NFTX litepaper, similarly to Maker vaults. This still follows the general minting pattern of removing transferability of the {Base} tokens in exchange for {Derivative} tokens. - -### Burning -Burning requires the transfer of {Base} tokens out of the {Pool} in exchange for burning {Derivative} tokens. The burn functions are distinguished by the quantity and quality of {Base} tokens redeemed. -- For burning without specifying the `id`: `burn`, `batchBurn`. -- For burning with specifying the `id`(s): `idBurn`, `batchIdBurn`. - -By allowing for specific ids to be targeted, higher value {Base} tokens may be selected out of the pool. NFTX proposes an additional fee to be applied for such targeted withdrawals, to offset the desire to drain the {Pool} of {Base} tokens worth more than the floor price. - -### Pricing -Prices should not be necessarily fixed. therefore, Mint/Burn events MUST include the ERC-20 `_value` minted/burned. - -Existing pricing implementations are as follows (measured in base:derivative): -- Equal: Every {Base} costs 1 {Derivative} - - NFTX - - Wrapped Kitties -- Proportional - - NFT20 sets a fixed rate of 100 {Base} tokens per {Derivative} token. -- Variable - - NFT20 also allows for Dutch auctions when minting. - - NFTX proposes an additional fee to be paid when targeting the id of the {Base} token. - -Due to the variety of pricing implementations, the Mint\* and Burn\* events MUST include the number {Derivative} tokens minted/burned. - -### Inheritance -#### ERC-20 -The {Wrapper} MAY inherit from {ERC20}, in order to directly call `super.mint` and `super.burn`. -If the {Wrapper} does not inherit from {ERC20}, the {Derivative} contract MUST be limited such that the {Wrapper} has the sole power to `mint`, `burn`, and otherwise change the supply of tokens. - -#### ERC721Receiver, ERC1155Receiver -If not inheriting from {ERC721Receiver} and/or {ERC1155Receiver}, the pool MUST be limited such that the base tokens can only be transferred via the Wrapper's `mint`, `burn`. - -There exists only one of each ERC-721 token of with a given (address, id) pair. However, ERC-1155 tokens of a given (address, id) may have quantities greater than 1. Accordingly, the meaning of "Single" and "Batch" in each standard varies. In both standards, "single" refers to a single id, and "batch" refers to multiple ids. In ERC-1155, a single id event/function may involve multiple tokens, according to the `value` field. - -In building a common set of events and functions, we must be aware of these differences in implementation. The current implementation treats ERC-721 tokens as a special case where, in reference to the quantity of each {Base} token: -- All parameters named `_amount`, MUST be `1`. -- All parameters named `_amounts` MUST be either an empty list or a list of `1` with the same length as `_ids`. - -This keeps a consistent enumeration of tokens along with ERC-1155. Alternative implementations include: -- A common interface with specialized functions. EX: `mintFromERC721`. -- Separate interfaces for each type. EX: `ERC721Wrapper`, `ERC1155Wrapper`. - -#### ERC721, ERC1155 -The {Wrapper} MAY inherit from {ERC721} and/or {ERC1155} in order to call `super.mint`, directly. This is optional as minting {Base} tokens is not required in this standard. An "Initial NFT Offering" could use this to create a set of {Base} tokens within the contract, and directly distribute {Derivative} tokens. - -If the {Wrapper} does not inherit from {ERC721} or {ERC1155}, it MUST include calls to {IERC721} and {IERC1155} in order to transfer {Base} tokens. - -### Approval -All of the underlying transfer methods are not tied to the {Wrapper}, but rather call the ERC-20/721/1155 transfer methods. Implementations of this standard MUST: -- Either implement {Derivative} transfer approval for burning, and {Base} transfer approval for minting. -- Or check for Approval outside of the {Wrapper} through {IERC721} / {IERC1155} before attempting to execute. - -## Backwards Compatibility -Most existing implementations inherit from ERC-20, using functions `mint` and `burn`. -Events: -- Mint - - WK: DepositKittyAndMintToken - - NFTX: Mint - -- Burn - - WK: BurnTokenAndWithdrawKity - - NFTX: Redeem - -## Reference Implementation -[ERC-3386 Reference Implementation](https://github.com/ashrowz/erc-3386) - -## Security Considerations -Wrapper contracts are RECOMMENDED to inherit from burnable ERC-20 tokens. If they are not, the supply of the {Derivative} tokens MUST be controlled by the Wrapper. Similarly, price implementations MUST ensure that the supply of {Base} tokens is reflected by the {Derivative} tokens. - -With the functions `idBurn`, `idBurns`, users may target the most valuable NFT within the generic lot. If there is a significant difference between tokens values of different ids, the contract SHOULD consider creating specialized pools (NFTX) or pricing (NFT20) to account for this. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3386.md diff --git a/EIPS/eip-3440.md b/EIPS/eip-3440.md index a343038554a60f..f5bffc59f651b3 100644 --- a/EIPS/eip-3440.md +++ b/EIPS/eip-3440.md @@ -1,300 +1,7 @@ --- eip: 3440 -title: ERC-721 Editions Standard -author: Nathan Ginnever (@nginnever) -discussions-to: https://ethereum-magicians.org/t/eip-3340-nft-editions-standard-extension/6044 -status: Stagnant -type: Standards Track category: ERC -created: 2021-04-20 -requires: 712, 721 +status: Moved --- -## Simple Summary - -This standard addresses an extension to the [ERC-721 specification](./eip-721.md) by allowing signatures on NFTs representing works of art. This provides improved provenance by creating functionality for an artist to designate an original and signed limited-edition prints of their work. - -## Abstract - -ERC-3440 is an ERC-721 extension specifically designed to make NFTs more robust for works of art. This extends the original ERC-721 spec by providing the ability to designate the original and limited-edition prints with a specialized enumeration extension similar to the [original 721 extension](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/ERC721Enumerable.sol) built-in. The key improvement of this extension is allowing artists to designate the limited nature of their prints and provide a signed piece of data that represents their unique signature to a given token Id, much like an artist would sign a print of their work. - -## Motivation -Currently the link between a NFT and the digital work of art is only enforced in the token metadata stored in the shared `tokenURI` state of a NFT. While the blockchain provides an immutable record of history back to the origin of an NFT, often the origin is not a key that an artist maintains as closely as they would a hand written signature. - -An edition is a printed replica of an original piece of art. ERC-721 is not specifically designed to be used for works of art, such as digital art and music. ERC-721 (NFT) was originally created to handle deeds and other contracts. Eventually ERC-721 evolved into gaming tokens, where metadata hosted by servers may be sufficient. This proposal takes the position that we can create a more tangible link between the NFT, digital art, owner, and artist. By making a concise standard for art, it will be easier for an artist to maintain a connection with the Ethereum blockchain as well as their fans that purchase their tokens. - -The use cases for NFTs have evolved into works of digital art, and there is a need to designate an original NFT and printed editions with signatures in a trustless manner. ERC-721 contracts may or may not be deployed by artists, and currently, the only way to understand that something is uniquely touched by an artist is to display it on 3rd party applications that assume a connection via metadata that exists on servers, external to the blockchain. This proposal helps remove that distance with readily available functionality for artists to sign their work and provides a standard for 3rd party applications to display the uniqueness of a NFT for those that purchase them. The designation of limited-editions combined with immutable signatures, creates a trustlessly enforced link. This signature is accompanied by view functions that allow applications to easily display these signatures and limited-edition prints as evidence of uniqueness by showing that artists specifically used their key to designate the total supply and sign each NFT. - -## Specification -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -ERC-721 compliant contracts MAY implement this ERC for editions to provide a standard method for designating the original and limited-edition prints with signatures from the artist. - -Implementations of ERC-3440 MUST designate which token Id is the original NFT (defaulted to Id 0), and which token Id is a unique replica. The original print SHOULD be token Id number 0 but MAY be assigned to a different Id. The original print MUST only be designated once. The implementation MUST designate a maximum number of minted editions, after which new Ids MUST NOT be printed / minted. - -Artists MAY use the signing feature to sign the original or limited edition prints but this is OPTIONAL. A standard message to sign is RECOMMENDED to be simply a hash of the integer of the token Id. - -Signature messages MUST use the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard. - -A contract that is compliant with ERC-3440 shall implement the following abstract contract (referred to as ERC3440.sol): - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; -import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; - -/** - * @dev ERC721 token with editions extension. - */ -abstract contract ERC3440 is ERC721URIStorage { - - // eip-712 - struct EIP712Domain { - string name; - string version; - uint256 chainId; - address verifyingContract; - } - - // Contents of message to be signed - struct Signature { - address verificationAddress; // ensure the artists signs only address(this) for each piece - string artist; - address wallet; - string contents; - } - - // type hashes - bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( - "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" - ); - - bytes32 constant SIGNATURE_TYPEHASH = keccak256( - "Signature(address verifyAddress,string artist,address wallet, string contents)" - ); - - bytes32 public DOMAIN_SEPARATOR; - - // Optional mapping for signatures - mapping (uint256 => bytes) private _signatures; - - // A view to display the artist's address - address public artist; - - // A view to display the total number of prints created - uint public editionSupply = 0; - - // A view to display which ID is the original copy - uint public originalId = 0; - - // A signed token event - event Signed(address indexed from, uint256 indexed tokenId); - - /** - * @dev Sets `artist` as the original artist. - * @param `address _artist` the wallet of the signing artist (TODO consider multiple - * signers and contract signers (non-EOA) - */ - function _designateArtist(address _artist) internal virtual { - require(artist == address(0), "ERC721Extensions: the artist has already been set"); - - // If there is no special designation for the artist, set it. - artist = _artist; - } - - /** - * @dev Sets `tokenId as the original print` as the tokenURI of `tokenId`. - * @param `uint256 tokenId` the nft id of the original print - */ - function _designateOriginal(uint256 _tokenId) internal virtual { - require(msg.sender == artist, "ERC721Extensions: only the artist may designate originals"); - require(_exists(_tokenId), "ERC721Extensions: Original query for nonexistent token"); - require(originalId == 0, "ERC721Extensions: Original print has already been designated as a different Id"); - - // If there is no special designation for the original, set it. - originalId = _tokenId; - } - - - /** - * @dev Sets total number printed editions of the original as the tokenURI of `tokenId`. - * @param `uint256 _maxEditionSupply` max supply - */ - function _setLimitedEditions(uint256 _maxEditionSupply) internal virtual { - require(msg.sender == artist, "ERC721Extensions: only the artist may designate max supply"); - require(editionSupply == 0, "ERC721Extensions: Max number of prints has already been created"); - - // If there is no max supply of prints, set it. Leaving supply at 0 indicates there are no prints of the original - editionSupply = _maxEditionSupply; - } - - /** - * @dev Creates `tokenIds` representing the printed editions. - * @param `string memory _tokenURI` the metadata attached to each nft - */ - function _createEditions(string memory _tokenURI) internal virtual { - require(msg.sender == artist, "ERC721Extensions: only the artist may create prints"); - require(editionSupply > 0, "ERC721Extensions: the edition supply is not set to more than 0"); - for(uint i=0; i < editionSupply; i++) { - _mint(msg.sender, i); - _setTokenURI(i, _tokenURI); - } - } - - /** - * @dev internal hashing utility - * @param `Signature memory _message` the signature message struct to be signed - * the address of this contract is enforced in the hashing - */ - function _hash(Signature memory _message) internal view returns (bytes32) { - return keccak256(abi.encodePacked( - "\x19\x01", - DOMAIN_SEPARATOR, - keccak256(abi.encode( - SIGNATURE_TYPEHASH, - address(this), - _message.artist, - _message.wallet, - _message.contents - )) - )); - } - - /** - * @dev Signs a `tokenId` representing a print. - * @param `uint256 _tokenId` id of the NFT being signed - * @param `Signature memory _message` the signed message - * @param `bytes memory _signature` signature bytes created off-chain - * - * Requirements: - * - * - `tokenId` must exist. - * - * Emits a {Signed} event. - */ - function _signEdition(uint256 _tokenId, Signature memory _message, bytes memory _signature) internal virtual { - require(msg.sender == artist, "ERC721Extensions: only the artist may sign their work"); - require(_signatures[_tokenId].length == 0, "ERC721Extensions: this token is already signed"); - bytes32 digest = hash(_message); - address recovered = ECDSA.recover(digest, _signature); - require(recovered == artist, "ERC721Extensions: artist signature mismatch"); - _signatures[_tokenId] = _signature; - emit Signed(artist, _tokenId); - } - - - /** - * @dev displays a signature from the artist. - * @param `uint256 _tokenId` NFT id to verify isSigned - * @returns `bytes` gets the signature stored on the token - */ - function getSignature(uint256 _tokenId) external view virtual returns (bytes memory) { - require(_signatures[_tokenId].length != 0, "ERC721Extensions: no signature exists for this Id"); - return _signatures[_tokenId]; - } - - /** - * @dev returns `true` if the message is signed by the artist. - * @param `Signature memory _message` the message signed by an artist and published elsewhere - * @param `bytes memory _signature` the signature on the message - * @param `uint _tokenId` id of the token to be verified as being signed - * @returns `bool` true if signed by artist - * The artist may broadcast signature out of band that will verify on the nft - */ - function isSigned(Signature memory _message, bytes memory _signature, uint _tokenId) external view virtual returns (bool) { - bytes32 messageHash = hash(_message); - address _artist = ECDSA.recover(messageHash, _signature); - return (_artist == artist && _equals(_signatures[_tokenId], _signature)); - } - - /** - * @dev Utility function that checks if two `bytes memory` variables are equal. This is done using hashing, - * which is much more gas efficient then comparing each byte individually. - * Equality means that: - * - 'self.length == other.length' - * - For 'n' in '[0, self.length)', 'self[n] == other[n]' - */ - function _equals(bytes memory _self, bytes memory _other) internal pure returns (bool equal) { - if (_self.length != _other.length) { - return false; - } - uint addr; - uint addr2; - uint len = _self.length; - assembly { - addr := add(_self, /*BYTES_HEADER_SIZE*/32) - addr2 := add(_other, /*BYTES_HEADER_SIZE*/32) - } - assembly { - equal := eq(keccak256(addr, len), keccak256(addr2, len)) - } - } -} -``` - -## Rationale - -A major role of NFTs is to display uniqueness in digital art. Provenance is a desired feature of works of art, and this standard will help improve a NFT by providing a better way to verify uniqueness. Taking this extra step by an artist to explicitly sign tokens provides a better connection between the artists and their work on the blockchain. Artists can now retain their private key and sign messages in the future showing that the same signature is present on a unique NFT. - -## Backwards Compatibility - -This proposal combines already available 721 extensions and is backwards compatible with the ERC-721 standard. - -## Test Cases -An example implementation including tests can be found [here](https://github.com/nginnever/NFT-editions). - -## Reference Implementation -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC3440.sol"; - -/** - * @dev ERC721 token with editions extension. - */ -contract ArtToken is ERC3440 { - - /** - * @dev Sets `address artist` as the original artist to the account deploying the NFT. - */ - constructor ( - string memory _name, - string memory _symbol, - uint _numberOfEditions, - string memory tokenURI, - uint _originalId - ) ERC721(_name, _symbol) { - _designateArtist(msg.sender); - _setLimitedEditions(_numberOfEditions); - _createEditions(tokenURI); - _designateOriginal(_originalId); - - DOMAIN_SEPARATOR = keccak256(abi.encode( - EIP712DOMAIN_TYPEHASH, - keccak256(bytes("Artist's Editions")), - keccak256(bytes("1")), - 1, - address(this) - )); - } - - /** - * @dev Signs a `tokenId` representing a print. - */ - function sign(uint256 _tokenId, Signature memory _message, bytes memory _signature) public { - _signEdition(_tokenId, _message, _signature); - } -} - -``` - -## Security Considerations -This extension gives an artist the ability to designate an original edition, set the maximum supply of editions as well as print the editions and uses the `tokenURI` extension to supply a link to the art work. To minimize the risk of an artist changing this value after selling an original piece this function can only happen once. Ensuring that these functions can only happen once provides consistency with uniqueness and verifiability. Due to this, the reference implementation handles these features in the constructor function. An edition may only be signed once, and care should be taken that the edition is signed correctly before release of the token/s. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3440.md diff --git a/EIPS/eip-3448.md b/EIPS/eip-3448.md index e28d15f1ff013b..ddc7e16c821104 100644 --- a/EIPS/eip-3448.md +++ b/EIPS/eip-3448.md @@ -1,208 +1,7 @@ --- eip: 3448 -title: MetaProxy Standard -description: A minimal bytecode implementation for creating proxy contracts with immutable metadata attached to the bytecode -author: pinkiebell (@pinkiebell) -discussions-to: https://ethereum-magicians.org/t/erc-3448-metaproxy-factory/5834 -status: Final -type: Standards Track category: ERC -created: 2021-03-29 +status: Moved --- -## Abstract -By standardizing on a known minimal bytecode proxy implementation with support for immutable metadata, this standard allows users and third party tools (e.g. Etherscan) to: -(a) simply discover that a contract will always redirect in a known manner and -(b) depend on the behavior of the code at the destination contract as the behavior of the redirecting contract and -(c) verify/view the attached metadata. - -Tooling can interrogate the bytecode at a redirecting address to determine the location of the code that will run along with the associated metadata - and can depend on representations about that code (verified source, third-party audits, etc). -This implementation forwards all calls via `DELEGATECALL` and any (calldata) input plus the metadata at the end of the bytecode to the implementation contract and then relays the return value back to the caller. -In the case where the implementation reverts, the revert is passed back along with the payload data. - -## Motivation -This standard supports use-cases wherein it is desirable to clone exact contract functionality with different parameters at another address. - -## Specification -The exact bytecode of the MetaProxy contract is: -``` - 20 bytes target contract address - ---------------------------------------- -363d3d373d3d3d3d60368038038091363936013d7300000000000000000000000000000000000000005af43d3d93803e603457fd5bf3 -``` -wherein the bytes at indices 21 - 41 (inclusive) are replaced with the 20 byte address of the master functionality contract. -Additionally, everything after the MetaProxy bytecode can be arbitrary metadata and the last 32 bytes (one word) of the bytecode must indicate the length of the metadata in bytes. - -``` -<54 bytes metaproxy> -``` - -## Rationale -The goals of this effort have been the following: -- a cheap way of storing immutable metadata for each child instead of using storage slots -- inexpensive deployment of clones -- handles error return bubbling for revert messages - -## Backwards Compatibility -There are no backwards compatibility issues. - -## Test Cases -Tested with: -- invocation with no arguments -- invocation with arguments -- invocation with return values -- invocation with revert (confirming reverted payload is transferred) - -A solidity contract with the above test cases can be found [in the EIP asset directory](../assets/eip-3448/MetaProxyTest.sol). - -## Reference Implementation -A reference implementation can be found [in the EIP asset directory](../assets/eip-3448/MetaProxyFactory.sol). - -### Deployment bytecode -A annotated version of the deploy bytecode: -``` -// PUSH1 11; -// CODESIZE; -// SUB; -// DUP1; -// PUSH1 11; -// RETURNDATASIZE; -// CODECOPY; -// RETURNDATASIZE; -// RETURN; -``` - -### MetaProxy -A annotated version of the MetaProxy bytecode: -``` -// copy args -// CALLDATASIZE; calldatasize -// RETURNDATASIZE; 0, calldatasize -// RETURNDATASIZE; 0, 0, calldatasize -// CALLDATACOPY; - -// RETURNDATASIZE; 0 -// RETURNDATASIZE; 0, 0 -// RETURNDATASIZE; 0, 0, 0 -// RETURNDATASIZE; 0, 0, 0, 0 - -// PUSH1 54; 54, 0, 0, 0, 0 -// DUP1; 54, 54, 0, 0, 0, 0 -// CODESIZE; codesize, 54, 54, 0, 0, 0, 0 -// SUB; codesize-54, 54, 0, 0, 0, 0 -// DUP1; codesize-54, codesize-54, 54, 0, 0, 0, 0 -// SWAP2; 54, codesize-54, codesize-54, 0, 0, 0, 0 -// CALLDATASIZE; calldatasize, 54, codesize-54, codesize-54, 0, 0, 0, 0 -// CODECOPY; codesize-54, 0, 0, 0, 0 - -// CALLDATASIZE; calldatasize, codesize-54, 0, 0, 0, 0 -// ADD; calldatasize+codesize-54, 0, 0, 0, 0 -// RETURNDATASIZE; 0, calldatasize+codesize-54, 0, 0, 0, 0 -// PUSH20 0; addr, 0, calldatasize+codesize-54, 0, 0, 0, 0 - zero is replaced with shl(96, address()) -// GAS; gas, addr, 0, calldatasize+codesize-54, 0, 0, 0, 0 -// DELEGATECALL; (gas, addr, 0, calldatasize() + metadata, 0, 0) delegatecall to the target contract; -// -// RETURNDATASIZE; returndatasize, retcode, 0, 0 -// RETURNDATASIZE; returndatasize, returndatasize, retcode, 0, 0 -// SWAP4; 0, returndatasize, retcode, 0, returndatasize -// DUP1; 0, 0, returndatasize, retcode, 0, returndatasize -// RETURNDATACOPY; (0, 0, returndatasize) - Copy everything into memory that the call returned - -// stack = retcode, 0, returndatasize # this is for either revert(0, returndatasize()) or return (0, returndatasize()) - -// PUSH1 _SUCCESS_; push jumpdest of _SUCCESS_ -// JUMPI; jump if delegatecall returned `1` -// REVERT; (0, returndatasize()) if delegatecall returned `0` -// JUMPDEST _SUCCESS_; -// RETURN; (0, returndatasize()) if delegatecall returned non-zero (1) -``` - -### Examples -The following code snippets serve only as suggestions and are not a discrete part of this standard. - -#### Proxy construction with bytes from abi.encode -```solidity -/// @notice MetaProxy construction via abi encoded bytes. -function createFromBytes ( - address a, - uint256 b, - uint256[] calldata c -) external payable returns (address proxy) { - // creates a new proxy where the metadata is the result of abi.encode() - proxy = MetaProxyFactory._metaProxyFromBytes(address(this), abi.encode(a, b, c)); - require(proxy != address(0)); - // optional one-time setup, a constructor() substitute - MyContract(proxy).init{ value: msg.value }(); -} -``` - -#### Proxy construction with bytes from calldata -```solidity -/// @notice MetaProxy construction via calldata. -function createFromCalldata ( - address a, - uint256 b, - uint256[] calldata c -) external payable returns (address proxy) { - // creates a new proxy where the metadata is everything after the 4th byte from calldata. - proxy = MetaProxyFactory._metaProxyFromCalldata(address(this)); - require(proxy != address(0)); - // optional one-time setup, a constructor() substitute - MyContract(proxy).init{ value: msg.value }(); -} -``` - -#### Retrieving the metadata from calldata and abi.decode -```solidity -/// @notice Returns the metadata of this (MetaProxy) contract. -/// Only relevant with contracts created via the MetaProxy standard. -/// @dev This function is aimed to be invoked with- & without a call. -function getMetadataWithoutCall () public pure returns ( - address a, - uint256 b, - uint256[] memory c -) { - bytes memory data; - assembly { - let posOfMetadataSize := sub(calldatasize(), 32) - let size := calldataload(posOfMetadataSize) - let dataPtr := sub(posOfMetadataSize, size) - data := mload(64) - // increment free memory pointer by metadata size + 32 bytes (length) - mstore(64, add(data, add(size, 32))) - mstore(data, size) - let memPtr := add(data, 32) - calldatacopy(memPtr, dataPtr, size) - } - return abi.decode(data, (address, uint256, uint256[])); -} -``` - -#### Retrieving the metadata via a call to self -```solidity -/// @notice Returns the metadata of this (MetaProxy) contract. -/// Only relevant with contracts created via the MetaProxy standard. -/// @dev This function is aimed to to be invoked via a call. -function getMetadataViaCall () public pure returns ( - address a, - uint256 b, - uint256[] memory c -) { - assembly { - let posOfMetadataSize := sub(calldatasize(), 32) - let size := calldataload(posOfMetadataSize) - let dataPtr := sub(posOfMetadataSize, size) - calldatacopy(0, dataPtr, size) - return(0, size) - } -} -``` - -Apart from the examples above, it is also possible to use Solidity Structures or any custom data encoding. - -## Security Considerations -This standard only covers the bytecode implementation and does not include any serious side effects of itself. -The reference implementation only serves as a example. It is highly recommended to research side effects depending on how the functionality is used and implemented in any project. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3448.md diff --git a/EIPS/eip-3450.md b/EIPS/eip-3450.md index 7030877a628f5c..ca9c83ea69128e 100644 --- a/EIPS/eip-3450.md +++ b/EIPS/eip-3450.md @@ -1,190 +1,7 @@ --- eip: 3450 -title: Standardized Shamir Secret Sharing Scheme for BIP-39 Mnemonics -author: Daniel Streit (@danielstreit) -discussions-to: https://ethereum-magicians.org/t/erc-3450-standard-for-applying-shamirs-to-bip-39-mnemonics/5844 -status: Stagnant -type: Standards Track category: ERC -created: 2021-03-29 +status: Moved --- -## Simple Summary - -A standardized algorithm for applying Shamir's Secret Sharing Scheme to BIP-39 mnemonics. - -## Abstract - -A standardized approach to splitting a BIP-39 mnemonic into _N_ BIP-39 mnemonics, called shares, so that _T_ shares are required to recover the original mnemonic and no information about the original mnemonic, other than its size, is leaked with less than _T_ shares. - -## Motivation - -We'd like to make it easier for less-technical users to store keys securely. - -Currently, many users use BIP-39 mnemonics to store entropy values underlying their keys. These mnemonics are a single point of failure. If lost, the user may never regain access to the assets locked by the keys. If stolen, a malicious actor can steal the assets. - -Shamir's Secret Sharing Scheme addresses this concern directly. It creates "shares" of the secret, such that a subset can be used to recover the secret, but only if a minimum threshold of shares is reached. Without the minimum, no information about the original secret is leaked. - -One concern with Shamir's Secret Sharing Scheme is there is no canonical, standard implementation. This puts recovery at risk, as tooling may change over time. - -Here, we propose a standardized implementation of Shamir's Secret Sharing Scheme applied specifically to BIP-39 mnemonics, so users can easily create shares of their mnemonic, destroy the original, store the shares appropriately, and confidently recover the original mnemonic at a later date. - -## Specification - -### Shamir's Secret Sharing Scheme - -Shamir's Secret Sharing Scheme is a cryptographic method to split a secret into _N_ unique parts, where any _T_ of them are required to reconstruct the secret. - -First, a polynomial _f_ of degree _T_ − 1 is constructed. Then, each share is a point on the polynomial's curve: an integer _x_, and its corresponding _y_ point _f_(_x_). - -With any set of _T_ shares (or points), the initial polynomial can be recovered using polynomial interpolation. - -When constructing the initial polynomial, the secret is stored as the coefficient of x0 and the rest of the coefficients are randomly generated. - -### BIP-39 Mnemonics - -BIP-39 is a common standard for storing entropy as a list of words. It is easier to work with for human interactions than raw binary or hexadecimal representations of entropy. - -BIP-39 mnemonics encode two pieces of data: the original entropy and a checksum of that entropy. The checksum allows the mnemonic to be validated, ensuring that the user entered it correctly. - -#### Generating the Mnemonic - -The mnemonic must encode entropy in a multiple of 32 bits. With more entropy security is improved but the sentence length increases. We refer to the initial entropy length as ENT. The allowed size of ENT is 128-256 bits. - -First, an initial entropy of ENT bits is generated. A checksum is generated by taking the first `ENT / 32` bits of its SHA256 hash. This checksum is appended to the end of the initial entropy. Next, these concatenated bits are split into groups of 11 bits, each encoding a number from 0-2047, serving as an index into a word list. Finally, we convert these numbers into words and use the joined words as a mnemonic sentence. - -The following table describes the relation between the initial entropy length (ENT), the checksum length (CS), and the length of the generated mnemonic sentence (MS) in words. - -``` -CS = ENT / 32 -MS = (ENT + CS) / 11 - -| ENT | CS | ENT+CS | MS | -+-------+----+--------+------+ -| 128 | 4 | 132 | 12 | -| 160 | 5 | 165 | 15 | -| 192 | 6 | 198 | 18 | -| 224 | 7 | 231 | 21 | -| 256 | 8 | 264 | 24 | -``` - -#### Recovering the Entropy - -The initial entropy can be recovered by reversing the process above. The mnemonic is converted to bits, where each word is converted to 11 bits representing its index in the word list. The entropy portion is defined in the table above, based on the size of the mnemonic. - -#### Word List - -This specification only supports the BIP-39 English word list, but this may be expanded in the future. - -See [word list](../assets/eip-3450/wordlist.txt). - -### Applying Shamir's Scheme to BIP-39 Mnemonics - -To ensure that the shares are valid BIP-39 mnemonics, we: - -1. Convert the target BIP-39 mnemonic to its underlying entropy -2. Apply Shamir's Scheme to the entropy -3. Convert each resulting share's _y_ value to a BIP-39 mnemonic - -By converting to entropy before applying Shamir's Scheme, we omit the checksum from the initial secret, allowing us to calculate a new checksum for each share when converting the share _y_ values to mnemonics, ensuring that they are valid according to BIP-39. - -When applying Shamir's Scheme to the entropy, we apply it separately to each byte of the entropy and GF(256) is used as the underlying finite field. Bytes are interpreted as elements of GF(256) using polynomial representation with operations modulo the Rijndael irreducible polynomial _x_8 + _x_4 + _x_3 + _x_ + 1, following AES. - -### Share Format - -A share represents a point on the curve described by the underlying polynomial used to split the secret. It includes two pieces of data: - -- An ID: the _x_ value of the share -- A BIP-39 mnemonic: the _y_ value of the share represented by a mnemonic - -### Creating Shares - -Inputs: BIP-39 mnemonic, number of shares (_N_), threshold (_T_) - -Output: N Shares, each share including an ID, { _x_ | 0 < _x_ < 256 }, and a BIP-39 mnemonic of the same length as the input one - -1. Check the following conditions: - - 1 < T <= N < 256 - - The mnemonic is valid according to [BIP-39](#generating-the-mnemonic) -2. [Recover the underlying entropy of the mnemonic](#recovering-the-entropy) as a vector of bytes -3. Define values: - - Let _E_ be the byte-vector representation of the mnemonic's entropy - - Let _n_ be the length of _E_ - - Let _coeff1_, ... , _coeffT - 1_ be byte-vectors belonging to GF(256)_n_ generated randomly, independently with uniform distribution from a source suitable for generating cryptographic keys -4. Evaluate the polynomial for each share - - For each _x_ from 1 to _N_, evaluate the polynomial _f(x)_ = _E_ + _coeff1x1_ + ... + _coeffT - 1xT - 1_, where _x_ is the share ID and _f(x)_ is the share value (as a vector of bytes) -5. Using _f(x)_ as the underlying entropy, [generate a mnemonic](#generating-the-mnemonic) for each share -6. Return the ID and mnemonic for each share - -### Recovering the Mnemonic - -To recover the original mnemonic, we interpolate a polynomial _f_ from the given set of shares (or points on the polynomial) and evaluate _f(0)_. - -#### Polynomial Interpolation - -Given a set of _m_ points (_xi_, _yi_), 1 ≤ _i_ ≤ _m_, such that no two _xi_ values equal, there exists a polynomial that assumes the value _yi_ at each point _xi_. The polynomial of lowest degree that satisfies these conditions is uniquely determined and can be obtained using the Lagrange interpolation formula given below. - -Since Shamir's Secret Sharing Scheme is applied separately to each of the _n_ bytes of the shared mnemonic's entropy, we work with _yi_ as a vector of _n_ values, where _yi_[_k_] = _fk_(_xi_), 1 ≤ _k_ ≤ _n_, and _fk_ is the polynomial in the _k_-th instance of the scheme. - -#### Interpolate(_x_, {(_xi_, _yi_), 1 ≤ _i_ ≤ _m_}) - -Input: the desired index _x_, a set of index/value-vector pairs {(_xi_, _y__i_), 1 ≤ _i_ ≤ _m_} ⊆ GF(256) × GF(256)_n_ - -Output: the value-vector (_f_1(_x_), ... , _fn_(_x_)) - -![f_k(x) = \sum_{i=1}^m y_i[k] \prod_{\underset{j \neq i}{j=1}}^m \frac{x - x_j}{x_i - x_j}](../assets/eip-3450/lagrange.gif) - -#### Recover the Mnemonic - -Input: A set of _m_ Shares - -Output: The original mnemonic - -1. [Recover the underlying entropy of each share's mnemonic](#recovering-the-entropy) as a vector of bytes -2. Calculate _E_ = Interpolate(0, [(_x1_, _y1_),...,(_xm_, _ym_)]), where _x_ is the share ID and _y_ is the byte-vector of the share's mnemonic's entropy -3. Using _E_ as the underlying entropy, [generate a mnemonic](#generating-the-mnemonic) and return it - -## Rationale - -### Choice of Field - -The field GF(256) was chosen, because the field arithmetic is easy to implement in any programming language and many implementations are already available since it is used in the AES cipher. Although using GF(256) requires that we convert the mnemonic to its underlying entropy as a byte-vector, this is also easy to implement and many implementations of it exist in a variety of programming languages. - -GF(2048) was also considered. Using GF(2048), we could have applied Shamir's Scheme directly to the mnemonic, using the word indexes as the values. This would have allowed us to avoid converting the mnemonic to its underlying entropy. But, the resulting shares would not have been valid BIP-39 mnemonics - the checksum portion would not be a valid checksum of the entropy. And, working around this would add considerable complexity. - -Another option was GF(2_n_) where _n_ is the size of the entropy in bits. We'd still convert the mnemonic to entropy, but then apply Shamir's Scheme over the entire entropy rather than on a vector of values. The downside of this approach is we'd need a different field for each mnemonic strength along with an associated irreducible polynomial. Additionally, this would require working with very large numbers that can be cumbersome to work with in some languages. - -### Valid Share Mnemonics and Share IDs - -The shares produced by the specification include an ID, in addition to the BIP-39 mnemonic. - -Other options could have encoded the share ID into the mnemonic, simplifying storage - only the mnemonic would need to be stored. - -One possibility would be to store the ID instead of the checksum in the mnemonic. The downside of this approach is that the shares would not be _valid_ BIP-39 mnemonics because the "checksum" section of the mnemonic would not match the "entropy" section. Shares with valid BIP-39 mnemonics are useful because they are indistinguishable from any other. And users could store the ID in a variety of ways that obscure it. - -### Validation on Recovery - -We decided _not_ to include a validation mechanism on recovering the original mnemonic. This leaks less information to a potential attacker. There is no indication they've gotten the requisite number of shares until they've obtained _T_ + 1 shares. - -We could provide recovery validation by replacing one of the random coefficients with a checksum of the original mnemonic. Then, when recovering the original mnemonic and the polynomial, we could validate that the checksum coefficient is the valid checksum of recovered mnemonic. - -## Test Cases - -Coming soon. - -All implementations must be able to: - -- Split and recover each `mnemonic` with the given `numShares` and `threshold`. -- Recover the `mnemonic` from the given `knownShares`. - -## Security Considerations - -The shares produced by the specification include an ID in addition to the BIP-39 mnemonic. This raises two security concerns: - -Users **must** keep this ID in order to recover the original mnemonic. If the ID is lost, or separated from the share mnemonic, it may not be possible to recover the original. (Brute force recovery may or may not be possible depending on how much is known about the number of shares and threshold) - -The additional data may hint to an attacker of the existence of other keys and the scheme under which they are stored. Therefore, the ID should be stored in a way that obscures its use. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3450.md diff --git a/EIPS/eip-3455.md b/EIPS/eip-3455.md new file mode 100644 index 00000000000000..b9083d4a5cd2b1 --- /dev/null +++ b/EIPS/eip-3455.md @@ -0,0 +1,71 @@ +--- +eip: 3455 +title: SUDO Opcode +description: A new opcode is introduced to allow calling from an arbitrary sender address. +author: William Morriss (@wjmelements), Baptiste Vauthey (@thabaptiser) +discussions-to: https://ethereum-magicians.org/t/eip-3455-sudo-opcode/5860 +status: Stagnant +type: Standards Track +category: Core +created: 2021-04-01 +--- + +## Abstract +A new opcode, `SUDO`, is introduced with the same parameters as `CALL`, plus another parameter to specify the sender address. + +## Motivation +There are many use cases for being able to set the sender. + +Many tokens are stuck irretrievably because nobody has the key for the owner address. +In particular, at address zero there is approximately 17 billion USD in tokens and ether, according to etherscan. +With `SUDO`, anyone could free that value, leading to an economic boom that would end poverty and world hunger. +Instead it is sitting there idle like the gold in Fort Knox. +`SUDO` fixes this. + +It is a common mistake to send [ERC-20](./eip-20.md) tokens to the token address instead of the intended recipient. +This happens because users paste the token address into the recipient fields. +Currently there is no way to recover these tokens. +`SUDO` fixes this. + +Many scammers have fraudulently received tokens and ETH via trust-trading. +Their victims currently have no way to recover their funds. +`SUDO` fixes this. + +Large amounts of users have accidentally locked up tokens and ether by losing their private keys. +This is inefficient and provides a bad user experience. +To accommodate new and inexperienced users, there needs to be a way to recover funds after the private key has been lost. +`SUDO` fixes this. + +Finally, there are many tokens and ether sitting in smart contracts locked due to a bug. +We could finally close EIP issue #156. +We cannot currently reclaim ether from stuck accounts. +`SUDO` fixes this. + +## Specification +Adds a new opcode (`SUDO`) at `0xf8`. +`SUDO` pops 8 parameters from the stack. +Besides the sender parameter, the parameters shall match `CALL`. + +1. Gas: Integer; Maximum gas allowance for message call, safely using current gas counter if the counter is lower +2. Sender: Address, truncated to lower 40 bytes; Sets `CALLER` inside the call frame +3. To: Address, truncated to lower 40 bytes; sets `ADDRESS` +4. Value: Integer, raises exception amount specified is less than the value in Sender account; transferred with call to recipient balance, sets `CALLVALUE` +5. InStart: Integer; beginning of memory to use for `CALLDATA` +6. InSize: Integer; length of memory to use for `CALLDATA` +7. OutStart: Integer; beginning of memory to replace with `RETURNDATA` +8. OutSize: Integer; maximum `RETURNDATA` to place in memory + +Following execution, `SUDO` pushes a result value to the stack, indicating success or failure. +If the call ended with `STOP`, `RETURN`, or `SELFDESTRUCT`, `1` is pushed. +If the call ended with `REVERT`, `INVALID`, or an EVM assertion, `0` is pushed. + +## Rationale +The `GAS` parameter is first so that callers can tediously compute how much of their remaining gas to send at the last possible moment. +The remaining parameters inherited from `CALL` are in the same order, with sender inserted between. + + +## Security Considerations +It will be fine. + +## Copyright +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-3475.md b/EIPS/eip-3475.md index f55b6dc3e3334d..cc27918838a153 100644 --- a/EIPS/eip-3475.md +++ b/EIPS/eip-3475.md @@ -1,445 +1,7 @@ --- eip: 3475 -title: Abstract Storage Bonds -description: Interface for creating tokenized obligations with abstract on-chain metadata storage -author: Yu Liu (@yuliu-debond), Varun Deshpande (@dr-chain), Cedric Ngakam (@drikssy), Dhruv Malik (@dhruvmalik007), Samuel Gwlanold Edoumou (@Edoumou), Toufic Batrice (@toufic0710) -discussions-to: https://ethereum-magicians.org/t/eip-3475-multiple-callable-bonds-standard/8691 -status: Final -type: Standards Track category: ERC -created: 2021-04-05 -requires: 20, 721, 1155 +status: Moved --- -## Abstract - -- This EIP allows the creation of tokenized obligations with abstract on-chain metadata storage. Issuing bonds with multiple redemption data cannot be achieved with existing token standards. - -- This EIP enables each bond class ID to represent a new configurable token type and corresponding to each class, corresponding bond nonces to represent an issuing condition or any other form of data in uint256. Every single nonce of a bond class can have its metadata, supply, and other redemption conditions. - -- Bonds created by this EIP can also be batched for issuance/redemption conditions for efficiency on gas costs and UX side. And finally, bonds created from this standard can be divided and exchanged in a secondary market. - -## Motivation - -Current LP (Liquidity Provider) tokens are simple [EIP-20](./eip-20.md) tokens with no complex data structure. To allow more complex reward and redemption logic to be stored on-chain, we need a new token standard that: - -- Supports multiple token IDs -- Can store on-chain metadata -- Doesn't require a fixed storage pattern -- Is gas-efficient. - -Also Some benefits: - -- This EIP allows the creation of any obligation with the same interface. -- It will enable any 3rd party wallet applications or exchanges to read these tokens' balance and redemption conditions. -- These bonds can also be batched as tradeable instruments. Those instruments can then be divided and exchanged in secondary markets. - -## Specification - -**Definition** - -Bank: an entity that issues, redeems, or burns bonds after getting the necessary amount of liquidity. Generally, a single entity with admin access to the pool. - -**Functions** - -```solidity -pragma solidity ^0.8.0; - -/** -* transferFrom -* @param _from argument is the address of the bond holder whose balance is about to decrease. -* @param _to argument is the address of the bond recipient whose balance is about to increase. -* @param _transactions is the `Transaction[] calldata` (of type ['classId', 'nonceId', '_amountBonds']) structure defined in the rationale section below. -* @dev transferFrom MUST have the `isApprovedFor(_from, _to, _transactions[i].classId)` approval to transfer `_from` address to `_to` address for given classId (i.e for Transaction tuple corresponding to all nonces). -e.g: -* function transferFrom(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, 0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B, [IERC3475.Transaction(1,14,500)]); -* transfer from `_from` address, to `_to` address, `500000000` bonds of type class`1` and nonce `42`. -*/ - -function transferFrom(address _from, address _to, Transaction[] calldata _transactions) external; - -/** -* transferAllowanceFrom -* @dev allows the transfer of only those bond types and nonces being allotted to the _to address using allowance(). -* @param _from is the address of the holder whose balance is about to decrease. -* @param _to is the address of the recipient whose balance is about to increase. -* @param _transactions is the `Transaction[] calldata` structure defined in the section `rationale` below. -* @dev transferAllowanceFrom MUST have the `allowance(_from, msg.sender, _transactions[i].classId, _transactions[i].nonceId)` (where `i` looping for [ 0 ...Transaction.length - 1] ) -e.g: -* function transferAllowanceFrom(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, 0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B, [IERC3475.Transaction(1,14,500)]); -* transfer from `_from` address, to `_to` address, `500000000` bonds of type class`1` and nonce `42`. -*/ - -function transferAllowanceFrom(address _from,address _to, Transaction[] calldata _transactions) public ; - -/** -* issue -* @dev allows issuing any number of bond types (defined by values in Transaction tuple as param) to an address. -* @dev it MUST be issued by a single entity (for instance, a role-based ownable contract that has integration with the liquidity pool of the deposited collateral by `_to` address). -* @param `_to` argument is the address to which the bond will be issued. -* @param `_transactions` is the `Transaction[] calldata` (ie array of issued bond class, bond nonce and amount of bonds to be issued). -* @dev transferAllowanceFrom MUST have the `allowance(_from, msg.sender, _transactions[i].classId, _transactions[i].nonceId)` (where `i` looping for [ 0 ...Transaction.length - 1] ) -e.g: -example: issue(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,[IERC3475.Transaction(1,14,500)]); -issues `1000` bonds with a class of `0` to address `0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef` with a nonce of `5`. -*/ -function issue(address _to, Transaction[] calldata _transaction) external; - -/** -* redeem -* @dev permits redemption of bond from an address. -* @dev the calling of this function needs to be restricted to the bond issuer contract. -* @param `_from` is the address from which the bond will be redeemed. -* @param `_transactions` is the `Transaction[] calldata` structure (i.e., array of tuples with the pairs of (class, nonce and amount) of the bonds that are to be redeemed). Further defined in the rationale section. -* @dev redeem function for a given class, and nonce category MUST BE done after certain conditions for maturity (can be end time, total active liquidity, etc.) are met. -* @dev furthermore, it SHOULD ONLY be called by the bank or secondary market maker contract. -e.g: -* redeem(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, [IERC3475.Transaction(1,14,500)]); -means “redeem from wallet address(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef), 500000000 of bond class1 and nonce 42. -*/ - -function redeem(address _from, Transaction[] calldata _transactions) external; - -/** -* burn -* @dev permits nullifying of the bonds (or transferring given bonds to address(0)). -* @dev burn function for given class and nonce MUST BE called by only the controller contract. -* @param _from is the address of the holder whose bonds are about to burn. -* @param `_transactions` is the `Transaction[] calldata` structure (i.e., array of tuple with the pairs of (class, nonce and amount) of the bonds that are to be burned). further defined in the rationale. -* @dev burn function for a given class, and nonce category MUST BE done only after certain conditions for maturity (can be end time, total active liquidity, etc). -* @dev furthermore, it SHOULD ONLY be called by the bank or secondary market maker contract. -* e.g: -* burn(0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B,[IERC3475.Transaction(1,14,500)]); -* means burning 500000000 bonds of class 1 nonce 42 owned by address 0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B. -*/ -function burn(address _from, Transaction[] calldata _transactions) external; - -/** -* approve -* @dev Allows `_spender` to withdraw from the msg.sender the bonds of `_amount` and type (classId and nonceId). -* @dev If this function is called again, it overwrites the current allowance with the amount. -* @dev `approve()` should only be callable by the bank, or the owner of the account. -* @param `_spender` argument is the address of the user who is approved to transfer the bonds. -* @param `_transactions` is the `Transaction[] calldata` structure (ie array of tuple with the pairs of (class,nonce, and amount) of the bonds that are to be approved to be spend by _spender). Further defined in the rationale section. -* e.g: -* approve(0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B,[IERC3475.Transaction(1,14,500)]); -* means owner of address 0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B is approved to manage 500 bonds from class 1 and Nonce 14. -*/ - -function approve(address _spender, Transaction[] calldata _transactions) external; - -/** -* SetApprovalFor -* @dev enable or disable approval for a third party (“operator”) to manage all the Bonds in the given class of the caller’s bonds. -* @dev If this function is called again, it overwrites the current allowance with the amount. -* @dev `approve()` should only be callable by the bank or the owner of the account. -* @param `_operator` is the address to add to the set of authorized operators. -* @param `classId` is the class id of the bond. -* @param `_approved` is true if the operator is approved (based on the conditions provided), false meaning approval is revoked. -* @dev contract MUST define internal function regarding the conditions for setting approval and should be callable only by bank or owner. -* e.g: setApprovalFor(0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B,0,true); -* means that address 0x82a55a613429Aeb3D01fbE6841bE1AcA4fFD5b2B is authorized to transfer bonds from class 0 (across all nonces). -*/ - -function setApprovalFor(address _operator, bool _approved) external returns(bool approved); - -/** -* totalSupply -* @dev Here, total supply includes burned and redeemed supply. -* @param classId is the corresponding class Id of the bond. -* @param nonceId is the nonce Id of the given bond class. -* @return the supply of the bonds -* e.g: -* totalSupply(0, 1); -* it finds the total supply of the bonds of classid 0 and bond nonce 1. -*/ -function totalSupply(uint256 classId, uint256 nonceId) external view returns (uint256); - -/** -* redeemedSupply -* @dev Returns the redeemed supply of the bond identified by (classId,nonceId). -* @param classId is the corresponding class id of the bond. -* @param nonceId is the nonce id of the given bond class. -* @return the supply of bonds redeemed. -*/ -function redeemedSupply(uint256 classId, uint256 nonceId) external view returns (uint256); - -/** -* activeSupply -* @dev Returns the active supply of the bond defined by (classId,NonceId). -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonce id of the given bond class. -* @return the non-redeemed, active supply. -*/ -function activeSupply(uint256 classId, uint256 nonceId) external view returns (uint256); - -/** -* burnedSupply -* @dev Returns the burned supply of the bond in defined by (classId,NonceId). -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonce id of the given bond class. -* @return gets the supply of bonds for given classId and nonceId that are already burned. -*/ -function burnedSupply(uint256 classId, uint256 nonceId) external view returns (uint256); - -/** -* balanceOf -* @dev Returns the balance of the bonds (nonReferenced) of given classId and bond nonce held by the address `_account`. -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonce id of the given bond class. -* @param _account address of the owner whose balance is to be determined. -* @dev this also consists of bonds that are redeemed. -*/ -function balanceOf(address _account, uint256 classId, uint256 nonceId) external view returns (uint256); - -/** -* classMetadata -* @dev Returns the JSON metadata of the classes. -* @dev The metadata SHOULD follow a set of structures explained later in the metadata.md -* @param metadataId is the index-id given bond class information. -* @return the JSON metadata of the nonces. — e.g. `[title, type, description]`. -*/ -function classMetadata(uint256 metadataId) external view returns (Metadata memory); - -/** -* nonceMetadata -* @dev Returns the JSON metadata of the nonces. -* @dev The metadata SHOULD follow a set of structures explained later in metadata.md -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonce id of the given bond class. -* @param metadataId is the index of the JSON storage for given metadata information. more is defined in metadata.md. -* @returns the JSON metadata of the nonces. — e.g. `[title, type, description]`. -*/ -function nonceMetadata(uint256 classId, uint256 metadataId) external view returns (Metadata memory); - -/** -* classValues -* @dev allows anyone to read the values (stored in struct Values for different class) for given bond class `classId`. -* @dev the values SHOULD follow a set of structures as explained in metadata along with correct mapping corresponding to the given metadata structure -* @param classId is the corresponding classId of the bond. -* @param metadataId is the index of the JSON storage for given metadata information of all values of given metadata. more is defined in metadata.md. -* @returns the Values of the class metadata. — e.g. `[string, uint, address]`. -*/ -function classValues(uint256 classId, uint256 metadataId) external view returns (Values memory); - -/** -* nonceValues -* @dev allows anyone to read the values (stored in struct Values for different class) for given bond (`nonceId`,`classId`). -* @dev the values SHOULD follow a set of structures explained in metadata along with correct mapping corresponding to the given metadata structure -* @param classId is the corresponding classId of the bond. -* @param metadataId is the index of the JSON storage for given metadata information of all values of given metadata. More is defined in metadata.md. -* @returns the Values of the class metadata. — e.g. `[string, uint, address]`. -*/ -function nonceValues(uint256 classId, uint256 nonceId, uint256 metadataId) external view returns (Values memory); - -/** -* getProgress -* @dev Returns the parameters to determine the current status of bonds maturity. -* @dev the conditions of redemption SHOULD be defined with one or several internal functions. -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonceId of the given bond class . -* @returns progressAchieved defines the metric (either related to % liquidity, time, etc.) that defines the current status of the bond. -* @returns progressRemaining defines the metric that defines the remaining time/ remaining progress. -*/ -function getProgress(uint256 classId, uint256 nonceId) external view returns (uint256 progressAchieved, uint256 progressRemaining); - -/** -* allowance -* @dev Authorizes to set the allowance for given `_spender` by `_owner` for all bonds identified by (classId, nonceId). -* @param _owner address of the owner of bond(and also msg.sender). -* @param _spender is the address authorized to spend the bonds held by _owner of info (classId, nonceId). -* @param classId is the corresponding classId of the bond. -* @param nonceId is the nonceId of the given bond class. -* @notice Returns the _amount which spender is still allowed to withdraw from _owner. -*/ -function allowance(address _owner, address _spender, uint256 classId, uint256 nonceId) external returns(uint256); - -/** -* isApprovedFor -* @dev returns true if address _operator is approved for managing the account’s bonds class. -* @notice Queries the approval status of an operator for a given owner. -* @dev _owner is the owner of bonds. -* @dev _operator is the EOA /contract, whose status for approval on bond class for this approval is checked. -* @returns “true” if the operator is approved, “false” if not. -*/ -function isApprovedFor(address _owner, address _operator) external view returns (bool); -``` - -### Events - -```solidity -/** -* Issue -* @notice Issue MUST trigger when Bonds are issued. This SHOULD not include zero value Issuing. -* @dev This SHOULD not include zero value issuing. -* @dev Issue MUST be triggered when the operator (i.e Bank address) contract issues bonds to the given entity. -* eg: emit Issue(_operator, 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,[IERC3475.Transaction(1,14,500)]); -* issue by address(operator) 500 Bonds(nonce14,class 1) to address 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef. -*/ - -event Issue(address indexed _operator, address indexed _to, Transaction[] _transactions); - -/** -* Redeem -* @notice Redeem MUST trigger when Bonds are redeemed. This SHOULD not include zero value redemption. -*e.g: emit Redeem(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,0x492Af743654549b12b1B807a9E0e8F397E44236E,[IERC3475.Transaction(1,14,500)]); -* emit event when 5000 bonds of class 1, nonce 14 owned by address 0x492Af743654549b12b1B807a9E0e8F397E44236E are being redeemed by 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef. -*/ - -event Redeem(address indexed _operator, address indexed _from, Transaction[] _transactions); - - -/** -* Burn. -* @dev `Burn` MUST trigger when the bonds are being redeemed via staking (or being invalidated) by the bank contract. -* @dev `Burn` MUST trigger when Bonds are burned. This SHOULD not include zero value burning. -* e.g : emit Burn(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef,0x492Af743654549b12b1B807a9E0e8F397E44236E,[IERC3475.Transaction(1,14,500)]); -* emits event when 500 bonds of owner 0x492Af743654549b12b1B807a9E0e8F397E44236E of type (class 1, nonce 14) are burned by operator 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef. -*/ - -event burn(address _operator, address _owner, Transaction[] _transactions); - -/** -* Transfer -* @dev its emitted when the bond is transferred by address(operator) from owner address(_from) to address(_to) with the bonds transferred, whose params are defined by _transactions struct array. -* @dev Transfer MUST trigger when Bonds are transferred. This SHOULD not include zero value transfers. -* @dev Transfer event with the _from `0x0` MUST not create this event(use `event Issued` instead). -* e.g emit Transfer(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, 0x492Af743654549b12b1B807a9E0e8F397E44236E, _to, [IERC3475.Transaction(1,14,500)]); -* transfer by address(_operator) amount 500 bonds with (Class 1 and Nonce 14) from 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, to address(_to). -*/ - -event Transfer(address indexed _operator, address indexed _from, address indexed _to, Transaction[] _transactions); - -/** -* ApprovalFor -* @dev its emitted when address(_owner) approves the address(_operator) to transfer his bonds. -* @notice Approval MUST trigger when bond holders are approving an _operator. This SHOULD not include zero value approval. -* eg: emit ApprovalFor(0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef, 0x492Af743654549b12b1B807a9E0e8F397E44236E, true); -* this means 0x2d03B6C79B75eE7aB35298878D05fe36DC1fE8Ef gives 0x492Af743654549b12b1B807a9E0e8F397E44236E access permission for transfer of its bonds. -*/ - -event ApprovalFor(address indexed _owner, address indexed _operator, bool _approved); -``` - -**Metadata**: -The metadata of a bond class or nonce is stored as an array of JSON objects, represented by the following types. - -**NOTE: all of the metadata schemas are referenced from [here](../assets/eip-3475/Metadata.md)** - -### 1. Description: - -This defines the additional information about the nature of data being stored in the nonce/class metadata structures. They are defined using the structured explained [here](../assets/eip-3475/Metadata.md#1-description-metadata). this will then be used by the frontend of the respective entities participating in the bond markets to interpret the data which is compliant with their jurisdiction. - -### 2. Nonce: - -The key value for indexing the information is the 'class' field. Following are the rules: - -- The title can be any alphanumeric type that is differentiated by the description of metadata (although it can be dependent on certain jurisdictions). -- The title SHOULD not be EMPTY. - -Some specific examples of metadata can be the localization of bonds, jurisdiction details etc., and they can be found in the [metadata.md](../assets/eip-3475/Metadata.md) example description. - -### 3. Class metadata: - -This structure defines the details of the class information (symbol, risk information, etc.). the example is explained [here](../assets/eip-3475/Metadata.md) in the class metadata section. - -### 4. Decoding data - -First, the functions for analyzing the metadata (i.e `ClassMetadata` and `NonceMetadata`) are to be used by the corresponding frontend to decode the information of the bond. - -This is done via overriding the function interface for functions `classValues` and `nonceValues` by defining the key (which SHOULD be an index) to read the corresponding information stored as a JSON object. - -```JSON -{ -"title": "symbol", -"_type": "string", -"description": "defines the unique identifier name in following format: (symbol, bondType, maturity in months)", -"values": ["Class Name 1","Class Name 2","DBIT Fix 6M"], -} -``` - -e.g. In the above example, to get the `symbol` of the given class id, we can use the class id as a key to get the `symbol` value in the values, which then can be used for fetching the detail for instance. - -## Rationale - -### Metadata structure - -Instead of storing the details about the class and their issuances to the user (ie nonce) externally, we store the details in the respective structures. Classes represent the different bond types, and nonces represent the various period of issuances. Nonces under the same class share the same metadata. Meanwhile, nonces are non-fungible. Each nonce can store a different set of metadata. Thus, upon transfer of a bond, all the metadata will be transferred to the new owner of the bond. - -```solidity - struct Values{ - string stringValue; - uint uintValue; - address addressValue; - bool boolValue; - bytes bytesValue; - } -``` - -```solidity - struct Metadata { - string title; - string _type; - string description; - } -``` - -### Batch function - - This EIP supports batch operations. It allows the user to transfer different bonds along with their metadata to a new address instantaneously in a single transaction. After execution, the new owner holds the right to reclaim the face value of each of the bonds. This mechanism helps with the "packaging" of bonds–helpful in use cases like trades on a secondary market. - -```solidity - struct Transaction { - uint256 classId; - uint256 nonceId; - uint256 _amount; - } -``` - -Where: -The `classId` is the class id of the bond. - -The `nonceId` is the nonce id of the given bond class. This param is for distinctions of the issuing conditions of the bond. - -The `_amount` is the amount of the bond for which the spender is approved. - -### AMM optimization - - One of the most obvious use cases of this EIP is the multilayered pool. The early version of AMM uses a separate smart contract and an [EIP-20](./eip-20.md) LP token to manage a pair. By doing so, the overall liquidity inside of one pool is significantly reduced and thus generates unnecessary gas spent and slippage. Using this EIP standard, one can build a big liquidity pool with all the pairs inside (thanks to the presence of the data structures consisting of the liquidity corresponding to the given class and nonce of bonds). Thus by knowing the class and nonce of the bonds, the liquidity can be represented as the percentage of a given token pair for the owner of the bond in the given pool. Effectively, the [EIP-20](./eip-20.md) LP token (defined by a unique smart contract in the pool factory contract) is aggregated into a single bond and consolidated into a single pool. - -- The reason behind the standard's name (abstract storage bond) is its ability to store all the specifications (metadata/values and transaction as defined in the following sections) without needing external storage on-chain/off-chain. - -## Backwards Compatibility - -Any contract that inherits the interface of this EIP is compatible. This compatibility exists for issuer and receiver of the bonds. Also any client EOA wallet can be compatible with the standard if they are able to sign `issue()` and `redeem()` commands. - -However, any existing [EIP-20](./eip-20.md) token contract can issue its bonds by delegating the minting role to a bank contract with the interface of this standard built-in. Check out our reference implementation for the correct interface definition. - -To ensure the indexing of transactions throughout the bond lifecycle (i.e "Issue", "Redeem" and "Transfer" functions), events cited in specification section MUST be emitted when such transaction is passed. - -**Note that the this standard interface is also compatible with [EIP-20](./eip-20.md) and [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md)interface.** - -However, creating a separate bank contract is recommended for reading the bonds and future upgrade needs. - -Acceptable collateral can be in the form of fungible (like [EIP-20](./eip-20.md)), non-fungible ([EIP-721](./eip-721.md), [EIP-1155](./eip-1155.md)) , or other bonds represented by this standard. - -## Test Cases - -Test-case for the minimal reference implementation is [here](../assets/eip-3475/ERC3475.test.ts). Use the Truffle box to compile and test the contracts. - -## Reference Implementation - -- [Interface](../assets/eip-3475/interfaces/IERC3475.sol). - -- [Basic Example](../assets/eip-3475/ERC3475.sol). - - This demonstration shows only minimalist implementation. - -## Security Considerations - -- The `function setApprovalFor(address _operatorAddress)` gives the operator role to `_operatorAddress`. It has all the permissions to transfer, burn and redeem bonds by default. - -- If the owner wants to give a one-time allocation to an address for specific bonds(classId,bondsId), he should call the `function approve()` giving the `Transaction[]` allocated rather than approving all the classes using `setApprovalFor`. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3475.md diff --git a/EIPS/eip-3525.md b/EIPS/eip-3525.md index 5f0573edaf9c87..dc908298645131 100644 --- a/EIPS/eip-3525.md +++ b/EIPS/eip-3525.md @@ -1,575 +1,7 @@ --- eip: 3525 -title: Semi-Fungible Token -description: Defines a specification where EIP-721 compatible tokens with the same SLOT and different IDs are fungible. -author: Will Wang (@will-edge), Mike Meng , Ethan Y. Tsai (@YeeTsai), Ryan Chow , Zhongxin Wu (@Nerverwind), AlvisDu (@AlvisDu) -discussions-to: https://ethereum-magicians.org/t/eip-3525-the-semi-fungible-token -status: Final -type: Standards Track category: ERC -created: 2020-12-01 -requires: 20, 165, 721 +status: Moved --- -## Abstract - -This is a standard for semi-fungible tokens. The set of smart contract interfaces described in this document defines an [EIP-721](./eip-721.md) compatible token standard. This standard introduces an `` triple scalar model that represents the semi-fungible structure of a token. It also introduces new transfer models as well as approval models that reflect the semi-fungible nature of the tokens. - -Token contains an EIP-721 equivalent ID property to identify itself as a universally unique entity, so that the tokens can be transferred between addresses and approved to be operated in EIP-721 compatible way. - -Token also contains a `value` property, representing the quantitative nature of the token. The meaning of the 'value' property is quite like that of the 'balance' property of an [EIP-20](./eip-20.md) token. Each token has a 'slot' attribute, ensuring that the value of two tokens with the same slot be treated as fungible, adding fungibility to the value property of the tokens. - -This EIP introduces new token transfer models for semi-fungibility, including value transfer between two tokens of the same slot and value transfer from a token to an address. - -## Motivation - -Tokenization is one of the most important trends by which to use and control digital assets in crypto. Traditionally, there have been two approaches to do so: fungible and non-fungible tokens. Fungible tokens generally use the EIP-20 standard, where every unit of an asset is identical to each other. EIP-20 is a flexible and efficient way to manipulate fungible tokens. Non-fungible tokens are predominantly EIP-721 tokens, a standard capable of distinguishing digital assets from one another based on identity. - -However, both have significant drawbacks. For example, EIP-20 requires that users create a separate EIP-20 contract for each individual data structure or combination of customizable properties. In practice, this results in an extraordinarily large amount of EIP-20 contracts that need to be created. On the other hand, EIP-721 tokens provide no quantitative feature, significantly undercutting their computability, liquidity, and manageability. For example, if one was to create financial instruments such as bonds, insurance policy, or vesting plans using EIP-721, no standard interfaces are available for us to control the value in them, making it impossible, for example, to transfer a portion of the equity in the contract represented by the token. - -A more intuitive and straightforward way to solve the problem is to create a semi-fungible token that has the quantitative features of EIP-20 and qualitative attributes of EIP-721. The backwards-compatibility with EIP-721 of such semi-fungible tokens would help utilize existing infrastructures already in use and lead to faster adoption. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every [EIP-3525](./eip-3525.md) compliant contract must implement the EIP-3525, EIP-721 and [EIP-165](./eip-165.md) interfaces** - -```solidity -pragma solidity ^0.8.0; - -/** - * @title EIP-3525 Semi-Fungible Token Standard - * Note: the EIP-165 identifier for this interface is 0xd5358140. - */ -interface IERC3525 /* is IERC165, IERC721 */ { - /** - * @dev MUST emit when value of a token is transferred to another token with the same slot, - * including zero value transfers (_value == 0) as well as transfers when tokens are created - * (`_fromTokenId` == 0) or destroyed (`_toTokenId` == 0). - * @param _fromTokenId The token id to transfer value from - * @param _toTokenId The token id to transfer value to - * @param _value The transferred value - */ - event TransferValue(uint256 indexed _fromTokenId, uint256 indexed _toTokenId, uint256 _value); - - /** - * @dev MUST emit when the approval value of a token is set or changed. - * @param _tokenId The token to approve - * @param _operator The operator to approve for - * @param _value The maximum value that `_operator` is allowed to manage - */ - event ApprovalValue(uint256 indexed _tokenId, address indexed _operator, uint256 _value); - - /** - * @dev MUST emit when the slot of a token is set or changed. - * @param _tokenId The token of which slot is set or changed - * @param _oldSlot The previous slot of the token - * @param _newSlot The updated slot of the token - */ - event SlotChanged(uint256 indexed _tokenId, uint256 indexed _oldSlot, uint256 indexed _newSlot); - - /** - * @notice Get the number of decimals the token uses for value - e.g. 6, means the user - * representation of the value of a token can be calculated by dividing it by 1,000,000. - * Considering the compatibility with third-party wallets, this function is defined as - * `valueDecimals()` instead of `decimals()` to avoid conflict with EIP-20 tokens. - * @return The number of decimals for value - */ - function valueDecimals() external view returns (uint8); - - /** - * @notice Get the value of a token. - * @param _tokenId The token for which to query the balance - * @return The value of `_tokenId` - */ - function balanceOf(uint256 _tokenId) external view returns (uint256); - - /** - * @notice Get the slot of a token. - * @param _tokenId The identifier for a token - * @return The slot of the token - */ - function slotOf(uint256 _tokenId) external view returns (uint256); - - /** - * @notice Allow an operator to manage the value of a token, up to the `_value`. - * @dev MUST revert unless caller is the current owner, an authorized operator, or the approved - * address for `_tokenId`. - * MUST emit the ApprovalValue event. - * @param _tokenId The token to approve - * @param _operator The operator to be approved - * @param _value The maximum value of `_toTokenId` that `_operator` is allowed to manage - */ - function approve( - uint256 _tokenId, - address _operator, - uint256 _value - ) external payable; - - /** - * @notice Get the maximum value of a token that an operator is allowed to manage. - * @param _tokenId The token for which to query the allowance - * @param _operator The address of an operator - * @return The current approval value of `_tokenId` that `_operator` is allowed to manage - */ - function allowance(uint256 _tokenId, address _operator) external view returns (uint256); - - /** - * @notice Transfer value from a specified token to another specified token with the same slot. - * @dev Caller MUST be the current owner, an authorized operator or an operator who has been - * approved the whole `_fromTokenId` or part of it. - * MUST revert if `_fromTokenId` or `_toTokenId` is zero token id or does not exist. - * MUST revert if slots of `_fromTokenId` and `_toTokenId` do not match. - * MUST revert if `_value` exceeds the balance of `_fromTokenId` or its allowance to the - * operator. - * MUST emit `TransferValue` event. - * @param _fromTokenId The token to transfer value from - * @param _toTokenId The token to transfer value to - * @param _value The transferred value - */ - function transferFrom( - uint256 _fromTokenId, - uint256 _toTokenId, - uint256 _value - ) external payable; - - - /** - * @notice Transfer value from a specified token to an address. The caller should confirm that - * `_to` is capable of receiving EIP-3525 tokens. - * @dev This function MUST create a new EIP-3525 token with the same slot for `_to`, - * or find an existing token with the same slot owned by `_to`, to receive the transferred value. - * MUST revert if `_fromTokenId` is zero token id or does not exist. - * MUST revert if `_to` is zero address. - * MUST revert if `_value` exceeds the balance of `_fromTokenId` or its allowance to the - * operator. - * MUST emit `Transfer` and `TransferValue` events. - * @param _fromTokenId The token to transfer value from - * @param _to The address to transfer value to - * @param _value The transferred value - * @return ID of the token which receives the transferred value - */ - function transferFrom( - uint256 _fromTokenId, - address _to, - uint256 _value - ) external payable returns (uint256); -} -``` - -The slot's enumeration extension is OPTIONAL. This allows your contract to publish its full list of `SLOT`s and make them discoverable. - -```solidity -pragma solidity ^0.8.0; - -/** - * @title EIP-3525 Semi-Fungible Token Standard, optional extension for slot enumeration - * @dev Interfaces for any contract that wants to support enumeration of slots as well as tokens - * with the same slot. - * Note: the EIP-165 identifier for this interface is 0x3b741b9e. - */ -interface IERC3525SlotEnumerable is IERC3525 /* , IERC721Enumerable */ { - - /** - * @notice Get the total amount of slots stored by the contract. - * @return The total amount of slots - */ - function slotCount() external view returns (uint256); - - /** - * @notice Get the slot at the specified index of all slots stored by the contract. - * @param _index The index in the slot list - * @return The slot at `index` of all slots. - */ - function slotByIndex(uint256 _index) external view returns (uint256); - - /** - * @notice Get the total amount of tokens with the same slot. - * @param _slot The slot to query token supply for - * @return The total amount of tokens with the specified `_slot` - */ - function tokenSupplyInSlot(uint256 _slot) external view returns (uint256); - - /** - * @notice Get the token at the specified index of all tokens with the same slot. - * @param _slot The slot to query tokens with - * @param _index The index in the token list of the slot - * @return The token ID at `_index` of all tokens with `_slot` - */ - function tokenInSlotByIndex(uint256 _slot, uint256 _index) external view returns (uint256); -} -``` - -The slot level approval is OPTIONAL. This allows any contract that wants to support approval for slots, which allows an operator to manage one's tokens with the same slot. - -```solidity -pragma solidity ^0.8.0; - -/** - * @title EIP-3525 Semi-Fungible Token Standard, optional extension for approval of slot level - * @dev Interfaces for any contract that wants to support approval of slot level, which allows an - * operator to manage one's tokens with the same slot. - * See https://eips.ethereum.org/EIPS/eip-3525 - * Note: the EIP-165 identifier for this interface is 0xb688be58. - */ -interface IERC3525SlotApprovable is IERC3525 { - /** - * @dev MUST emit when an operator is approved or disapproved to manage all of `_owner`'s - * tokens with the same slot. - * @param _owner The address whose tokens are approved - * @param _slot The slot to approve, all of `_owner`'s tokens with this slot are approved - * @param _operator The operator being approved or disapproved - * @param _approved Identify if `_operator` is approved or disapproved - */ - event ApprovalForSlot(address indexed _owner, uint256 indexed _slot, address indexed _operator, bool _approved); - - /** - * @notice Approve or disapprove an operator to manage all of `_owner`'s tokens with the - * specified slot. - * @dev Caller SHOULD be `_owner` or an operator who has been authorized through - * `setApprovalForAll`. - * MUST emit ApprovalSlot event. - * @param _owner The address that owns the EIP-3525 tokens - * @param _slot The slot of tokens being queried approval of - * @param _operator The address for whom to query approval - * @param _approved Identify if `_operator` would be approved or disapproved - */ - function setApprovalForSlot( - address _owner, - uint256 _slot, - address _operator, - bool _approved - ) external payable; - - /** - * @notice Query if `_operator` is authorized to manage all of `_owner`'s tokens with the - * specified slot. - * @param _owner The address that owns the EIP-3525 tokens - * @param _slot The slot of tokens being queried approval of - * @param _operator The address for whom to query approval - * @return True if `_operator` is authorized to manage all of `_owner`'s tokens with `_slot`, - * false otherwise. - */ - function isApprovedForSlot( - address _owner, - uint256 _slot, - address _operator - ) external view returns (bool); -} -``` - - -### EIP-3525 Token Receiver - -If a smart contract wants to be informed when they receive values from other addresses, it should implement all of the functions in the `IERC3525Receiver` interface, in the implementation it can decide whether to accept or reject the transfer. See "Transfer Rules" for further detail. - -```solidity - pragma solidity ^0.8.0; - -/** - * @title EIP-3525 token receiver interface - * @dev Interface for a smart contract that wants to be informed by EIP-3525 contracts when receiving values from ANY addresses or EIP-3525 tokens. - * Note: the EIP-165 identifier for this interface is 0x009ce20b. - */ -interface IERC3525Receiver { - /** - * @notice Handle the receipt of an EIP-3525 token value. - * @dev An EIP-3525 smart contract MUST check whether this function is implemented by the recipient contract, if the - * recipient contract implements this function, the EIP-3525 contract MUST call this function after a - * value transfer (i.e. `transferFrom(uint256,uint256,uint256,bytes)`). - * MUST return 0x009ce20b (i.e. `bytes4(keccak256('onERC3525Received(address,uint256,uint256, - * uint256,bytes)'))`) if the transfer is accepted. - * MUST revert or return any value other than 0x009ce20b if the transfer is rejected. - * @param _operator The address which triggered the transfer - * @param _fromTokenId The token id to transfer value from - * @param _toTokenId The token id to transfer value to - * @param _value The transferred value - * @param _data Additional data with no specified format - * @return `bytes4(keccak256('onERC3525Received(address,uint256,uint256,uint256,bytes)'))` - * unless the transfer is rejected. - */ - function onERC3525Received(address _operator, uint256 _fromTokenId, uint256 _toTokenId, uint256 _value, bytes calldata _data) external returns (bytes4); - -} -``` - -### Token Manipulation - -#### Scenarios - -**_Transfer:_** - -Besides EIP-721 compatible token transfer methods, this EIP introduces two new transfer models: value transfer from ID to ID, and value transfer from ID to address. - -```solidity -function transferFrom(uint256 _fromTokenId, uint256 _toTokenId, uint256 _value) external payable; - -function transferFrom(uint256 _fromTokenId, address _to, uint256 _value) external payable returns (uint256 toTokenId_); -``` - -The first one allows value transfers from one token (specified by `_fromTokenId`) to another token (specified by `_toTokenId`) within the same slot, resulting in the `_value` being subtracted from the value of the source token and added to the value of the destination token; - -The second one allows value transfers from one token (specified by `_fromTokenId`) to an address (specified by `_to`), the value is actually transferred to a token owned by the address, and the id of the destination token should be returned. Further explanation can be found in the 'design decision' section for this method. - -#### Rules - -**_approving rules:_** - -This EIP provides four kinds of approving functions indicating different levels of approvals, which can be described as full level approval, slot level approval, token ID level approval as well as value level approval. - -- `setApprovalForAll`, compatible with EIP-721, SHOULD indicate the full level of approval, which means that the authorized operators are capable of managing all the tokens, including their values, owned by the owner. -- `setApprovalForSlot` (optional) SHOULD indicate the slot level of approval, which means that the authorized operators are capable of managing all the tokens with the specified slot, including their values, owned by the owner. -- The token ID level `approve` function, compatible with EIP-721, SHOULD indicate that the authorized operator is capable of managing only the specified token ID, including its value, owned by the owner. -- The value level `approve` function, SHOULD indicate that the authorized operator is capable of managing the specified maximum value of the specified token owned by the owner. -- For any approving function, the caller MUST be the owner or has been approved with a higher level of authority. - -**_transferFrom rules:_** - -- The `transferFrom(uint256 _fromTokenId, uint256 _toTokenId, uint256 _value)` function, SHOULD indicate value transfers from one token to another token, in accordance with the rules below: - - - MUST revert unless `msg.sender` is the owner of `_fromTokenId`, an authorized operator or an operator who has been approved the whole token or at least `_value` of it. - - MUST revert if `_fromTokenId` or `_toTokenId` is zero token id or does not exist. - - MUST revert if slots of `_fromTokenId` and `_toTokenId` do not match. - - MUST revert if `_value` exceeds the value of `_fromTokenId` or its allowance to the operator. - - MUST check for the `onERC3525Received` function if the owner of _toTokenId is a smart contract, if the function exists, MUST call this function after the value transfer, MUST revert if the result is not equal to 0x009ce20b; - - MUST emit `TransferValue` event. - -- The `transferFrom(uint256 _fromTokenId, address _to, uint256 _value)` function, which transfers value from one token ID to an address, SHOULD follow the rule below: - - - MUST either find a EIP-3525 token owned by the address `_to` or create a new EIP-3525 token, with the same slot of `_fromTokenId`, to receive the transferred value. - - MUST revert unless `msg.sender` is the owner of `_fromTokenId`, an authorized operator or an operator who has been approved the whole token or at least `_value` of it. - - MUST revert if `_fromTokenId` is zero token id or does not exist. - - MUST revert if `_to` is zero address. - - MUST revert if `_value` exceeds the value of `_fromTokenId` or its allowance to the operator. - - MUST check for the `onERC3525Received` function if the _to address is a smart contract, if the function exists, MUST call this function after the value transfer, MUST revert if the result is not equal to 0x009ce20b; - - MUST emit `Transfer` and `TransferValue` events. - - -### Metadata - -#### Metadata Extensions - -EIP-3525 metadata extensions are compatible EIP-721 metadata extensions. - -This optional interface can be identified with the EIP-165 Standard Interface Detection. - -```solidity -pragma solidity ^0.8.0; - -/** - * @title EIP-3525 Semi-Fungible Token Standard, optional extension for metadata - * @dev Interfaces for any contract that wants to support query of the Uniform Resource Identifier - * (URI) for the EIP-3525 contract as well as a specified slot. - * Because of the higher reliability of data stored in smart contracts compared to data stored in - * centralized systems, it is recommended that metadata, including `contractURI`, `slotURI` and - * `tokenURI`, be directly returned in JSON format, instead of being returned with a url pointing - * to any resource stored in a centralized system. - * See https://eips.ethereum.org/EIPS/eip-3525 - * Note: the EIP-165 identifier for this interface is 0xe1600902. - */ -interface IERC3525Metadata is - IERC3525 /* , IERC721Metadata */ -{ - /** - * @notice Returns the Uniform Resource Identifier (URI) for the current EIP-3525 contract. - * @dev This function SHOULD return the URI for this contract in JSON format, starting with - * header `data:application/json;`. - * See https://eips.ethereum.org/EIPS/eip-3525 for the JSON schema for contract URI. - * @return The JSON formatted URI of the current EIP-3525 contract - */ - function contractURI() external view returns (string memory); - - /** - * @notice Returns the Uniform Resource Identifier (URI) for the specified slot. - * @dev This function SHOULD return the URI for `_slot` in JSON format, starting with header - * `data:application/json;`. - * See https://eips.ethereum.org/EIPS/eip-3525 for the JSON schema for slot URI. - * @return The JSON formatted URI of `_slot` - */ - function slotURI(uint256 _slot) external view returns (string memory); -} -``` - -#### EIP-3525 Metadata URI JSON Schema - -This is the "EIP-3525 Metadata JSON Schema for `contractURI()`" referenced above. - -```json -{ - "title": "Contract Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Contract Name" - }, - "description": { - "type": "string", - "description": "Describes the contract" - }, - "image": { - "type": "string", - "description": "Optional. Either a base64 encoded imgae data or a URI pointing to a resource with mime type image/* representing what this contract represents." - }, - "external_link": { - "type": "string", - "description": "Optional. A URI pointing to an external resource." - }, - "valueDecimals": { - "type": "integer", - "description": "The number of decimal places that the balance should display - e.g. 18, means to divide the token value by 1000000000000000000 to get its user representation." - } - } -} -``` - -This is the "EIP-3525 Metadata JSON Schema for `slotURI(uint)`" referenced above. - -```json -{ - "title": "Slot Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset category to which this slot represents" - }, - "description": { - "type": "string", - "description": "Describes the asset category to which this slot represents" - }, - "image": { - "type": "string", - "description": "Optional. Either a base64 encoded imgae data or a URI pointing to a resource with mime type image/* representing the asset category to which this slot represents." - }, - "properties": { - "type": "array", - "description": "Each item of `properties` SHOULD be organized in object format, including name, description, value, order (optional), display_type (optional), etc." - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The name of this property." - }, - "description": { - "type": "string", - "description": "Describes this property." - } - "value": { - "description": "The value of this property, which may be a string or a number." - }, - "is_intrinsic": { - "type": "boolean", - "description": "According to the definition of `slot`, one of the best practice to generate the value of a slot is utilizing the `keccak256` algorithm to calculate the hash value of multi properties. In this scenario, the `properties` field should contain all the properties that are used to calculate the value of `slot`, and if a property is used in the calculation, is_intrinsic must be TRUE." - }, - "order": { - "type": "integer", - "description": "Optional, related to the value of is_intrinsic. If is_intrinsic is TRUE, it must be the order of this property appeared in the calculation method of the slot." - }, - "display_type": { - "type": "string", - "description": "Optional. Specifies in what form this property should be displayed." - } - } - } - } - } -} -``` - - -This is the "EIP-3525 Metadata JSON Schema for `tokenURI(uint)`" referenced above. - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents" - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents" - }, - "image": { - "type": "string", - "description": "Either a base64 encoded imgae data or a URI pointing to a resource with mime type image/* representing the asset to which this token represents." - }, - "balance": { - "type": "integer", - "description": "THe value held by this token." - }, - "slot": { - "type": "integer", - "description": "The id of the slot that this token belongs to." - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, objects or arrays. Optional, you can use the same schema as the properties section of EIP-3525 Metadata JSON Schema for slotURI(uint) if you need a better description attribute." - } - } -} -``` - - -## Rationale - -### Metadata generation - -This token standard is designed to represent semi-fungible assets, which are most suited for financial instruments rather than collectibles or in-game items. For maximum transparency and safety of digital assets, we strongly recommend that all implementations should generate metadata directly from contract code rather than giving out an off-chain server URL. - -### Design decision: Value transfer from token to address - -The 'value' of a token is a property of the token and is not linked to an address, so to transfer the value to an address would be actually transferring it to a token owned by that address, not the address itself. - -From the implementation perspective, the process of transferring values from token to address could be done as follows: (1) create a new token for the recipient's address, (2) transfer the value to the new token from the 'source token'. So that this method is not fully independent from the ID-to-ID transfer method, and can be viewed as syntactic sugar that wraps the process described above. - -In a special case, if the destination address owns one or more tokens with the same slot value as the source token, this method will have an alternative implementation as follows: (1) find one token owned by the address with the same slot value of the source token, (2) transfer the value to the found token. - -Both implementations described above should be treated as compliant with this standard. - -The purpose of maintaining id-to-address transfer function is to maximize the compatibility with most wallet apps, since for most of the token standards, the destination of token transfer are addresses. This syntactic wrapping will help wallet apps easily implement the value transfer function from a token to any address. - -### Design decision: Notification/acceptance mechanism instead of 'Safe Transfer' - -EIP-721 and some later token standards introduced 'Safe Transfer' model, for better control of the 'safety' when transferring tokens, this mechanism leaves the choice of different transfer modes (safe/unsafe) to the sender, and may cause some potential problems: - -1. In most situations the sender does not know how to choose between two kinds of transfer methods (safe/unsafe); -2. If the sender calls the `safeTransferFrom` method, the transfer may fail if the recipient contract did not implement the callback function, even if that contract is capable of receiving and manipulating the token without issue. - -This EIP defines a simple 'Check, Notify and Response' model for better flexibility as well as simplicity: - -1. No extra `safeTransferFrom` methods are needed, all callers only need to call one kind of transfer; -2. All EIP-3525 contracts MUST check for the existence of `onERC3525Received` on the recipient contract and call the function when it exists; -3. Any smart contract can implement `onERC3525Received` function for the purpose of being notified after receiving values; this function MUST return 0x009ce20b (i.e. `bytes4(keccak256('onERC3525Received(address,uint256,uint256,uint256,bytes)'))`) if the transfer is accepted, or any other value if the transfer is rejected. - -There is a special case for this notification/acceptance mechanism: since EIP-3525 allows value transfer from an address to itself, when a smart contract which implements `onERC3525Received` transfers value to itself, `onERC3525Received` will also be called. This allows for the contract to implement different rules of acceptance between self-value-transfer and receiving value from other addresses. - -### Design decision: Relationship between different approval models - -For semantic compatibility with EIP-721 as well as the flexibility of value manipulation of tokens, we decided to define the relationships between some of the levels of approval like that: - -1. Approval of an id will lead to the ability to partially transfer values from this id by the approved operator; this will simplify the value approval for an id. However, the approval of total values in a token should not lead to the ability to transfer the token entity by the approved operator. -2. `setApprovalForAll` will lead to the ability to partially transfer values from any token, as well as the ability to approve partial transfer of values from any token to a third party; this will simplify the value transfer and approval of all tokens owned by an address. - -## Backwards Compatibility - -As mentioned in the beginning, this EIP is backward compatible with EIP-721. - -## Reference Implementation - -- [EIP-3525 implementation](../assets/eip-3525/contracts/ERC3525.sol) - -## Security Considerations - -The value level approval and slot level approval (optional) is isolated from EIP-721 approval models, so that approving value should not affect EIP-721 level approvals. Implementations of this EIP must obey this principle. - -Since this EIP is EIP-721 compatible, any wallets and smart contracts that can hold and manipulate standard EIP-721 tokens will have no risks of asset loss for EIP-3525 tokens due to incompatible standards implementations. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3525.md diff --git a/EIPS/eip-3540.md b/EIPS/eip-3540.md index 78f594f49303be..137ecc2ae5d9ce 100644 --- a/EIPS/eip-3540.md +++ b/EIPS/eip-3540.md @@ -8,7 +8,7 @@ status: Review type: Standards Track category: Core created: 2021-03-16 -requires: 3541, 3860, 4750, 5450 +requires: 3541, 3860 --- ## Abstract @@ -18,7 +18,7 @@ We introduce an extensible and versioned container format for the EVM with a onc To summarise, EOF bytecode has the following layout: ``` -magic, version, (section_kind, section_size)+, 0,
+magic, version, (section_kind, section_size_or_sizes)+, 0,
``` ## Motivation @@ -35,7 +35,6 @@ A non-exhaustive list of proposed changes which could benefit from this format: - Including a `JUMPDEST`-table (to avoid analysis at execution time) and/or removing `JUMPDEST`s entirely. - Introducing static jumps (with relative addresses) and jump tables, and disallowing dynamic jumps at the same time. -- Requiring the execution of a code section ends with a terminating instruction. (Assumptions like this can provide significant speed improvements in interpreters, such as a speed-up of ~7% seen in evmone (ethereum/evmone#295). - Multibyte opcodes without any workarounds. - Representing functions as individual code sections instead of subroutines. - Introducing special sections for different use cases, notably Account Abstraction. @@ -48,9 +47,11 @@ In order to guarantee that every EOF-formatted contract in the state is valid, w ### Remarks -The *initcode* is the code executed in the context of the *create* transaction, `CREATE`, or `CREATE2` instructions. The *initcode* returns *code* (via the `RETURN` instruction), which is inserted into the account. See section 7 ("Contract Creation") in the Yellow Paper for more information. +If code starts with the `MAGIC`, it is considered to be EOF formatted, otherwise it is considered to be *legacy* code. For clarity, the `MAGIC` together with a version number *n* is denoted as the *EOFn prefix*, e.g. *EOF1 prefix*. -The opcode `0xEF` is currently an undefined instruction, therefore: *It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed.* This means *initcode* or already deployed *code* starting with this instruction will continue to abort execution. +EOF-formatted contracts are created using new instructions which are introduced in a separate EIP. + +The opcode `0xEF` is currently an undefined instruction, therefore: *It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed.* This means legacy *initcode* or already deployed legacy *code* starting with this instruction will continue to abort execution. Unless otherwised specified, all integers are encoded in big-endian byte order. @@ -58,30 +59,23 @@ Unless otherwised specified, all integers are encoded in big-endian byte order. We introduce *code validation* for new contract creation. To achieve this, we define a format called EVM Object Format (EOF), containing a version indicator, and a ruleset of validity tied to a given version. -At `block.number == HF_BLOCK` new contract creation is modified: - -- if *initcode* or *code* starts with the `MAGIC`, it is considered to be EOF formatted and will undergo validation specified in the following sections, -- else if *code* starts with `0xEF`, creation continues to result in an exceptional abort (the rule introduced in EIP-3541), -- otherwise code is considered *legacy code* and the following rules do not apply to it. - -For a create transaction, if *initcode* or *code* is invalid, the contract creation results in an exceptional abort. Such a transaction is valid and may be included in a block. +Legacy code is not affected by EOF code validation. -For the `CREATE` and `CREATE2` instructions, if *initcode* or *code* is invalid, instructions' execution ends with the result `0` pushed on stack. - -In case *initcode* is invalid, gas for its execution is not deducted. In case *code* is invalid, all creation gas is deducted, similar to exceptional abort during *initcode* execution. +Code validation is performed during contract creation, and is elaborated on in separate EIPs. +The EOF format itself and its formal validation are described in the following sections. ### Container specification EOF container is a binary format with the capability of providing the EOF version number and a list of EOF sections. -The container starts with the EOF header: +The container starts with the EOF prefix: | description | length | value | | |-------------|----------|------------|--------------------| | magic | 2-bytes | 0xEF00 | | | version | 1-byte | 0x01–0xFF | EOF version number | -The EOF header is followed by at least one section header. Each section header contains two fields, `section_kind` and either `section_size` or `section_size_list`, depending on the kind. `section_size_list` is a list of size values when multiple sections of this kind are allowed. +The EOF prefix is followed by at least one section header. Each section header contains two fields, `section_kind` and either `section_size` or `section_size_list`, depending on the kind. `section_size_list` is a list of size values when multiple sections of this kind are allowed, encoded as a count of items followed by the items. | description | length | value | | |-------------------|---------|---------------|-------------------| @@ -93,88 +87,98 @@ The list of section headers is terminated with the *section headers terminator b #### Container validation rules -1. `version` MUST NOT be `0`.[^1](#eof-version-range-start-with-1) +1. `version` MUST NOT be `0`. 2. `section_kind` MUST NOT be `0`. The value `0` is reserved for *section headers terminator byte*. 3. There MUST be at least one section (and therefore section header). -4. Section content size MUST be equal to size declared in its header. 5. Stray bytes outside of sections MUST NOT be present. This includes trailing bytes after the last section. ### EOF version 1 -EOF version 1 is made up of 5 EIPs, including this one: [EIP-3540](./eip-3540.md), [EIP-3670](./eip-3670.md), [EIP-4200](./eip-4200.md), [EIP-4750](./eip-4750.md), and [EIP-5450](./eip-5450.md). Some values in this specification are only discussed briefly. To understand the full scope of EOF, it is necessary to review each EIP in-depth. +EOF version 1 is made up of several EIPs, including this one. Some values in this specification are only discussed briefly. To understand the full scope of EOF, it is necessary to review each EIP in-depth. #### Container The EOF version 1 container consists of a `header` and `body`. ``` -container := header, body -header := magic, version, kind_type, type_size, kind_code, num_code_sections, code_size+, kind_data, data_size, terminator -body := type_section, code_section+, data_section -type_section := (inputs, outputs, max_stack_height)+ +container := header, body +header := + magic, version, + kind_type, type_size, + kind_code, num_code_sections, code_size+, + [kind_container, num_container_sections, container_size+,] + kind_data, data_size, + terminator +body := types_section, code_section+, container_section*, data_section +types_section := (inputs, outputs, max_stack_height)+ ``` -*note: `,` is a concatenation operator and `+` should be interpreted as "one or more" of the preceding item* - -##### Header - -| name | length | value | description | -|-------------------|----------|---------------|------------------------------------------------------------------------------------| -| magic | 2 bytes | 0xEF00 | EOF prefix | -| version | 1 byte | 0x01 | EOF version | -| kind_type | 1 byte | 0x01 | kind marker for EIP-4750 type section header | -| type_size | 2 bytes | 0x0004-0xFFFC | uint16 denoting the length of the type section content, 4 bytes per code segment | -| kind_code | 1 byte | 0x02 | kind marker for code size section | -| num_code_sections | 2 bytes | 0x0001-0x0400 | uint16 denoting the number of the code sections | -| code_size | 2 bytes | 0x0001-0xFFFF | uint16 denoting the length of the code section content | -| kind_data | 1 byte | 0x03 | kind marker for data size section | -| data_size | 2 bytes | 0x0000-0xFFFF | uint16 integer denoting the length of the data section content | -| terminator | 1 byte | 0x00 | marks the end of the header | - -##### Body - -| name | length | value | description | -|------------------|----------|--------------|----------------------------------------------------| -| type_section | variable | n/a | stores EIP-4750 and EIP-5450 code section metadata | -| inputs | 1 byte | 0x00-0x7F | number of stack elements the code section consumes | -| outputs | 1 byte | 0x00-0x7F | number of stack elements the code section returns | -| max_stack_height | 2 bytes | 0x0000-0x3FF | max height of operand stack during execution | -| code_section | variable | n/a | arbitrary bytecode | -| data_section | variable | n/a | arbitrary sequence of bytes | +*note: `,` is a concatenation operator, `+` should be interpreted as "one or more" of the preceding item, `*` should be interpreted as "zero or more" of the preceding item, and `[item]` should be interpreted as an optional item.* + +#### Header + +| name | length | value | description | +|------------------------|----------|---------------|--------------------------------------------------------------------------------------------------------------| +| magic | 2 bytes | 0xEF00 | | +| version | 1 byte | 0x01 | EOF version | +| kind_type | 1 byte | 0x01 | kind marker for type section | +| type_size | 2 bytes | 0x0004-0x1000 | 16-bit unsigned big-endian integer denoting the length of the type section content, 4 bytes per code section | +| kind_code | 1 byte | 0x02 | kind marker for code size section | +| num_code_sections | 2 bytes | 0x0001-0x0400 | 16-bit unsigned big-endian integer denoting the number of the code sections | +| code_size | 2 bytes | 0x0001-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the code section content | +| kind_container | 1 byte | 0x03 | kind marker for container size section | +| num_container_sections | 2 bytes | 0x0001-0x00FF | 16-bit unsigned big-endian integer denoting the number of the container sections | +| container_size | 2 bytes | 0x0001-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the container section content | +| kind_data | 1 byte | 0x04 | kind marker for data size section | +| data_size | 2 bytes | 0x0000-0xFFFF | 16-bit unsigned big-endian integer denoting the length of the data section content (*) | +| terminator | 1 byte | 0x00 | marks the end of the header | + +(*) For not yet deployed containers this can be greater than the actual content length. + +#### Body + +| name | length | value | description | +|-------------------|----------|---------------|--------------------------------------------------------------------------------------------| +| types_section | variable | n/a | stores code section metadata | +| inputs | 1 byte | 0x00-0x7F | number of stack elements the code section consumes | +| outputs | 1 byte | 0x00-0x7F | number of stack elements the code section returns | +| max_stack_height | 2 bytes | 0x0000-0x03FF | maximum number of elements ever placed onto the operand stack by the code section | +| code_section | variable | n/a | arbitrary bytecode | +| container_section | variable | n/a | arbitrary EOF-formatted container | +| data_section | variable | n/a | arbitrary sequence of bytes | See [EIP-4750](./eip-4750.md) for more information on the type section content. +**NOTE**: A special value of `outputs` being `0x80` is designated to denote non-returning functions as defined in a separate EIP. + #### EOF version 1 validation rules -1. In addition to general validation rules above, EOF version 1 bytecode conforms to the rules specified below: - - Exactly one type section header MUST be present immediately following the EOF version. Each code section MUST have a specified type signature in the type body. - - Exactly one code section header MUST be present immediately following the type section. A maxmimum of 1024 individual code sections are allowed. - - Exactly one data section header MUST be present immediately following the code section. -2. Any version other than `0x01` is invalid. +The following validity constraints are placed on the container format: -(*Remark:* Contract creation code SHOULD set the section size of the data section so that the constructor arguments fit it.) +- `version` must be `0x01` +- `types_size` is divisible by `4` +- the number of code sections must be equal to `types_size / 4` +- the number of code sections must be greater than `0` and not exceed `1024` +- `code_size` may not be `0` +- the number of container sections must not exceed `256`. The number of container sections may not be `0`, if declared in the header +- `container_size` may not be `0` +- data section is mandatory, but `data_size` may be `0` +- data body length may be shorter than `data_size` for a not yet deployed container ### Changes to execution semantics -For clarity, the *container* refers to the complete account code, while *code* refers to the contents of the code section only. +For an EOF contract: -1. Execution starts at the first byte of the first code section, and PC is set to 0. -2. Execution stops if `PC` goes outside the code section bounds. -3. `PC` returns the current position within the *code*. -4. `CODECOPY`/`CODESIZE`/`EXTCODECOPY`/`EXTCODESIZE`/`EXTCODEHASH` keeps operating on the entire *container*. -5. The input to `CREATE`/`CREATE2` is still the entire *container*. -6. The size limit for deployed code as specified in [EIP-170](./eip-170.md) and for initcode as specified in [EIP-3860](./eip-3860.md) is applied to the entire *container* size, not to the *code* size. This also means if initcode validation fails, it is still charged the EIP-3860 `initcode_cost`. +- Execution starts at the first byte of code section 0 +- `CODESIZE`, `CODECOPY`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, `GAS` are rejected by validation in EOF contracts, with no replacements +- `CALL`, `DELEGATECALL`, `STATICCALL` are rejected by validation in EOF contracts, replacement instructions to be introduced in a separate EIP. +- `EXTDELEGATECALL` (`DELEGATECALL` replacement) from an EOF contract to a non-EOF contract (legacy contract, EOA, empty account) is disallowed, and it should fail in the same mode as if the call depth check failed. We allow legacy to EOF path for existing proxy contracts to be able to use EOF upgrades. -(*Remark:* Due to [EIP-4750](./eip-4750.md), `JUMP` and `JUMPI` are disabled and therefore are not discussed in relation to EOF.) +For a legacy contract: -### Changes to contract creation semantics - -For clarity, the *EOF prefix* together with a version number *n* is denoted as the *EOFn prefix*, e.g. *EOF1 prefix*. - -1. If *initcode's container* has EOF1 prefix it MUST be valid EOF1 code. -2. If *code's container* has EOF1 prefix it MUST be valid EOF1 code. -3. If *initcode's container* is valid EOF1 code the resulting *code's container* MUST be valid EOF1 code (i.e. it MUST NOT be empty and MUST NOT produce legacy code). -4. If `CREATE` or `CREATE2` instruction is executed in an EOF1 code the instruction's *initcode* MUST be valid EOF1 code (i.e. EOF1 contracts MUST NOT produce legacy code). +- If the target account of `EXTCODECOPY` is an EOF contract, then it will copy up to 2 bytes from `EF00`, as if that would be the code. +- If the target account of `EXTCODEHASH` is an EOF contract, then it will return `0x9dbf3648db8210552e9c4f75c6a1c3057c0ca432043bd648be15fe7be05646f5` (the hash of `EF00`, as if that would be the code). +- If the target account of `EXTCODESIZE` is an EOF contract, then it will return 2. ## Rationale @@ -197,21 +201,6 @@ The alternative is to have execution time validation for EOF. This is performed - Can be enabled via a single hard-fork. - Better backwards compatibility: data contracts starting with the `0xEF` byte or the *EOF prefix* can be deployed. This is a dubious benefit, however. -### Contract creation restrictions - -The [Changes to contact creation semantics](#changes-to-contract-creation-semantics) section defines -minimal set of restrictions related to the contract creation: if *initcode* or *code* has the EOF1 -container prefix it must be validated. This adds two validation steps in the contract creation, -any of it failing will result in contract creation failure. - -Moreover, it is not allowed to create legacy contracts from EOF1 ones. And the EOF version of *initcode* must match the EOF version of the produced *code*. -The rule can be generalized in the future: EOFn contract must only create EOFm contracts, where m ≥ n. - -This guarantees that a cluster of EOF contracts will never spawn new legacy contracts. -Furthermore, some exotic contract creation combinations are eliminated (e.g. EOF1 contract creating new EOF1 contract with legacy *initcode*). - -Finally, create transaction must be allowed to contain legacy *initcode* and deploy legacy *code* because otherwise there is no transition period allowing upgrading transaction signing tools. Deprecating such transactions may be considered in the future. - ### The MAGIC 1. The first byte `0xEF` was chosen because it is reserved for this purpose by [EIP-3541](./eip-3541.md). @@ -223,6 +212,8 @@ Finally, create transaction must be allowed to contain legacy *initcode* and dep 3. No contracts starting with `0xEF` bytes exist on public testnets: Goerli, Ropsten, Rinkeby, Kovan and Sepolia at their London fork block. +**NOTE**: This EIP MUST NOT be enabled on chains which contain bytecodes starting with `MAGIC` and not being valid EOF. + ### EOF version range start with 1 The version number 0 will never be used in EOF, so we can call legacy code *EOF0*. @@ -234,21 +225,16 @@ We have considered different questions for the sections: - Streaming headers (i.e. `section_header, section_data, section_header, section_data, ...`) are used in some other formats (such as WebAssembly). They are handy for formats which are subject to editing (adding/removing sections). That is not a useful feature for EVM. One minor benefit applicable to our case is that they do not require a specific "header terminator". On the other hand they seem to play worse with code chunking / merkleization, as it is better to have all section headers in a single chunk. - Whether to have a header terminator or to encode `number_of_sections` or `total_size_of_headers`. Both raise the question of how large of a value these fields should be able to hold. A terminator byte seems to avoid the problem of choosing a size which is too small without any perceptible downside, so it is the path taken. -- Whether to encode `section_size` as a fixed 16-bit value or some kind of variable length field (e.g. LEB128). We have opted for fixed size, because it simplifies client implementations, and 16-bit seems enough, because of the currently exposed code size limit of 24576 bytes (see [EIP-170](./eip-170.md) and [EIP-3860](./eip-3860.md)). Should this be limiting in the future, a new EOF version could change the format. Besides simplifying client implementations, not using LEB128 also greatly simplifies on-chain parsing. +- (EOF1) Whether to encode section sizes as fixed 16-bit values or some kind of variable length field (e.g. LEB128). We have opted for fixed size, because it simplifies client implementations, and 16-bit seems enough, because of the currently exposed code size limit of 24576 bytes (see [EIP-170](./eip-170.md) and [EIP-3860](./eip-3860.md)). Should this be limiting in the future, a new EOF version could change the format. Besides simplifying client implementations, not using LEB128 also greatly simplifies on-chain parsing. +- Whether or not to have more structure to the container header for all EOF versions to follow. In order to allow future formats optimized for chunking and merkleization (verkleization) it was decided to keep it generic and specify the structure only for a specific EOF version. ### Data-only contracts -The EOF prevents deploying contracts with arbitrary bytes (data-only contracts: their purpose is to store data not execution). **EOF1 requires** presence of a **code section** therefore the minimal overhead EOF data contract consist of a data section and one code section with single instruction. We recommend to use `INVALID` instruction in this case. In total there are 20 additional bytes required. +See section [Lack of `EXTDATACOPY` in EIP-7480](./eip-7480.md#lack-of-extdatacopy). -``` -EF0001 010004 020001 0001 03 00 00000000 FE -``` - -It is possible in the future that this data will be accessible with data-specific opcodes, such as `DATACOPY` or `EXTDATACOPY`. Until then, callers will need to determine the data offset manually. +### EOF1 contracts can only `DELEGATECALL` EOF1 contracts -### PC starts with 0 at the code section - -The value for `PC` is specified to start at 0 and to be within the active *code* section. We considered keeping `PC` to operate on the whole *container* and be consistent with `CODECOPY`/`EXTCODECOPY` but in the end decided otherwise. This also feels more natural and easier to implement in EVM: the new EOF EVM should only care about traversing *code* and accessing other parts of the *container* only on special occasions (e.g. in `CODECOPY` instruction). +Currently contracts can selfdestruct in three different ways (directly through `SELFDESTRUCT`, indirectly through `CALLCODE` and indirectly through `DELEGATECALL`). [EIP-3670](./eip-3670.md) disables the first two possibilities, however the third possibility remains. Allowing EOF1 contracts to only `DELEGATECALL` other EOF1 contracts allows the following strong statement: EOF1 contract can never be destructed. Attacks based on `SELFDESTRUCT` completely disappear for EOF1 contracts. These include destructed library contracts (e.g. Parity Multisig). ## Backwards Compatibility @@ -256,42 +242,6 @@ This is a breaking change given that any code starting with `0xEF` was not deplo The choice of `MAGIC` guarantees that none of the contracts existing on the chain are affected by the new rules. -## Test Cases - -### Contract creation - -All cases should be checked for creation transaction, `CREATE` and `CREATE2`. - -- Legacy init code - - Returns legacy code - - Returns valid EOF1 code - - Returns invalid EOF1 code, contract creation fails - - Returns 0xEF not followed by EOF1 code, contract creation fails -- Valid EOF1 init code - - Returns legacy code, contract creation fails - - Returns valid EOF1 code - - Returns invalid EOF1 code, contract creation fails - - Returns 0xEF not followed by EOF1 code, contract creation fails -- Invalid EOF1 init code - -### Contract execution - -- EOF code containing `PC` opcode - offset inside code section is returned -- EOF code containing `CODECOPY/CODESIZE` - works as in legacy code - - `CODESIZE` returns the size of entire container - - `CODECOPY` can copy from code section - - `CODECOPY` can copy from data section - - `CODECOPY` can copy from the EOF header - - `CODECOPY` can copy entire container -- `EXTCODECOPY/EXTCODESIZE/EXTCODEHASH` with the EOF *target* contract - works as with legacy target contract - - `EXTCODESIZE` returns the size of entire target container - - `EXTCODEHASH` returns the hash of entire target container - - `EXTCODECOPY` can copy from target's code section - - `EXTCODECOPY` can copy from target's data section - - `EXTCODECOPY` can copy from target's EOF header - - `EXTCODECOPY` can copy entire target container - - Results don't differ when executed inside legacy or EOF contract - ## Security Considerations With the anticipated EOF extensions, the validation is expected to have linear computational and space complexity. diff --git a/EIPS/eip-3561.md b/EIPS/eip-3561.md index f3fbee881717ab..4f7e495cc95398 100644 --- a/EIPS/eip-3561.md +++ b/EIPS/eip-3561.md @@ -1,282 +1,7 @@ --- eip: 3561 -title: Trust Minimized Upgradeability Proxy -description: proxy with a delay before specified upgrade goes live -author: Sam Porter (@SamPorter1984) -discussions-to: https://ethereum-magicians.org/t/trust-minimized-proxy/5742 -status: Review -type: Standards Track category: ERC -created: 2021-05-09 +status: Moved --- -## Abstract - -Removing trust from upgradeability proxy is necessary for anonymous developers. In order to accomplish this, instant and potentially malicious upgrades must be prevented. This EIP introduces additional storage slots for upgradeability proxy which are assumed to decrease trust in interaction with upgradeable smart contracts. Defined by the admin implementation logic can be made an active implementation logic only after Zero Trust Period allows. - -## Motivation - -Anonymous developers who utilize upgradeability proxies typically struggle to earn the trust of the community. - -Fairer, better future for humanity absolutely requires some developers to stay anonymous while still attract vital attention to solutions they propose and at the same time leverage the benefits of possible upgradeability. - -## Specification - -The specification is an addition to the standard [EIP-1967](./eip-1967.md) transparent proxy design. -The specification focuses on the slots it adds. All admin interactions with trust minimized proxy must emit an event to make admin actions trackable, and all admin actions must be guarded with `onlyAdmin()` modifier. - -### Next Logic Contract Address - -Storage slot `0x19e3fabe07b65998b604369d85524946766191ac9434b39e27c424c976493685` (obtained as `bytes32(uint256(keccak256('eip3561.proxy.next.logic')) - 1)`). -Desirable implementation logic address must be first defined as next logic, before it can function as actual logic implementation stored in EIP-1967 `IMPLEMENTATION_SLOT`. -Admin interactions with next logic contract address correspond with these methods and events: - -```solidity -// Sets next logic contract address. Emits NextLogicDefined -// If current implementation is address(0), then upgrades to IMPLEMENTATION_SLOT -// immedeatelly, therefore takes data as an argument -function proposeTo(address implementation, bytes calldata data) external IfAdmin -// As soon UPGRADE_BLOCK_SLOT allows, sets the address stored as next implementation -// as current IMPLEMENTATION_SLOT and initializes it. -function upgrade(bytes calldata data) external IfAdmin -// cancelling is possible for as long as upgrade() for given next logic was not called -// emits NextLogicCanceled -function cancelUpgrade() external onlyAdmin; - -event NextLogicDefined(address indexed nextLogic, uint earliestArrivalBlock); // important to have -event NextLogicCanceled(address indexed oldLogic); -``` - -### Upgrade Block - -Storage slot `0xe3228ec3416340815a9ca41bfee1103c47feb764b4f0f4412f5d92df539fe0ee` (obtained as `bytes32(uint256(keccak256('eip3561.proxy.next.logic.block')) - 1)`). -On/after this block next logic contract address can be set to EIP-1967 `IMPLEMENTATION_SLOT` or, in other words, `upgrade()` can be called. Updated automatically according to Zero Trust Period, shown as `earliestArrivalBlock` in the event `NextLogicDefined`. - -### Propose Block - -Storage slot `0x4b50776e56454fad8a52805daac1d9fd77ef59e4f1a053c342aaae5568af1388` (obtained as `bytes32(uint256(keccak256('eip3561.proxy.propose.block')) - 1)`). -Defines after/on which block *proposing* next logic is possible. Required for convenience, for example can be manually set to a year from given time. Can be set to maximum number to completely seal the code. -Admin interactions with this slot correspond with this method and event: - -```solidity -function prolongLock(uint b) external onlyAdmin; -event ProposingUpgradesRestrictedUntil(uint block, uint nextProposedLogicEarliestArrival); -``` - -### Zero Trust Period - -Storage slot `0x7913203adedf5aca5386654362047f05edbd30729ae4b0351441c46289146720` (obtained as `bytes32(uint256(keccak256('eip3561.proxy.zero.trust.period')) - 1)`). -Zero Trust Period in amount of blocks, can only be set higher than previous value. While it is at default value(0), the proxy operates exactly as standard EIP-1967 transparent proxy. After zero trust period is set, all above specification is enforced. -Admin interactions with this slot should correspond with this method and event: - -```solidity -function setZeroTrustPeriod(uint blocks) external onlyAdmin; -event ZeroTrustPeriodSet(uint blocks); -``` - -### Implementation Example - -```solidity -pragma solidity >=0.8.0; //important - -// EIP-3561 trust minimized proxy implementation https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3561.md -// Based on EIP-1967 upgradeability proxy: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1967.md - -contract TrustMinimizedProxy { - event Upgraded(address indexed toLogic); - event AdminChanged(address indexed previousAdmin, address indexed newAdmin); - event NextLogicDefined(address indexed nextLogic, uint earliestArrivalBlock); - event ProposingUpgradesRestrictedUntil(uint block, uint nextProposedLogicEarliestArrival); - event NextLogicCanceled(); - event ZeroTrustPeriodSet(uint blocks); - - bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; - bytes32 internal constant LOGIC_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - bytes32 internal constant NEXT_LOGIC_SLOT = 0x19e3fabe07b65998b604369d85524946766191ac9434b39e27c424c976493685; - bytes32 internal constant NEXT_LOGIC_BLOCK_SLOT = 0xe3228ec3416340815a9ca41bfee1103c47feb764b4f0f4412f5d92df539fe0ee; - bytes32 internal constant PROPOSE_BLOCK_SLOT = 0x4b50776e56454fad8a52805daac1d9fd77ef59e4f1a053c342aaae5568af1388; - bytes32 internal constant ZERO_TRUST_PERIOD_SLOT = 0x7913203adedf5aca5386654362047f05edbd30729ae4b0351441c46289146720; - - constructor() payable { - require( - ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) && - LOGIC_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) && - NEXT_LOGIC_SLOT == bytes32(uint256(keccak256('eip3561.proxy.next.logic')) - 1) && - NEXT_LOGIC_BLOCK_SLOT == bytes32(uint256(keccak256('eip3561.proxy.next.logic.block')) - 1) && - PROPOSE_BLOCK_SLOT == bytes32(uint256(keccak256('eip3561.proxy.propose.block')) - 1) && - ZERO_TRUST_PERIOD_SLOT == bytes32(uint256(keccak256('eip3561.proxy.zero.trust.period')) - 1) - ); - _setAdmin(msg.sender); - } - - modifier IfAdmin() { - if (msg.sender == _admin()) { - _; - } else { - _fallback(); - } - } - - function _logic() internal view returns (address logic) { - assembly { - logic := sload(LOGIC_SLOT) - } - } - - function _nextLogic() internal view returns (address nextLogic) { - assembly { - nextLogic := sload(NEXT_LOGIC_SLOT) - } - } - - function _proposeBlock() internal view returns (uint b) { - assembly { - b := sload(PROPOSE_BLOCK_SLOT) - } - } - - function _nextLogicBlock() internal view returns (uint b) { - assembly { - b := sload(NEXT_LOGIC_BLOCK_SLOT) - } - } - - function _zeroTrustPeriod() internal view returns (uint ztp) { - assembly { - ztp := sload(ZERO_TRUST_PERIOD_SLOT) - } - } - - function _admin() internal view returns (address adm) { - assembly { - adm := sload(ADMIN_SLOT) - } - } - - function _setAdmin(address newAdm) internal { - assembly { - sstore(ADMIN_SLOT, newAdm) - } - } - - function changeAdmin(address newAdm) external IfAdmin { - emit AdminChanged(_admin(), newAdm); - _setAdmin(newAdm); - } - - function upgrade(bytes calldata data) external IfAdmin { - require(block.number >= _nextLogicBlock(), 'too soon'); - address logic; - assembly { - logic := sload(NEXT_LOGIC_SLOT) - sstore(LOGIC_SLOT, logic) - } - (bool success, ) = logic.delegatecall(data); - require(success, 'failed to call'); - emit Upgraded(logic); - } - - fallback() external payable { - _fallback(); - } - - receive() external payable { - _fallback(); - } - - function _fallback() internal { - require(msg.sender != _admin()); - _delegate(_logic()); - } - - function cancelUpgrade() external IfAdmin { - address logic; - assembly { - logic := sload(LOGIC_SLOT) - sstore(NEXT_LOGIC_SLOT, logic) - } - emit NextLogicCanceled(); - } - - function prolongLock(uint b) external IfAdmin { - require(b > _proposeBlock(), 'can be only set higher'); - assembly { - sstore(PROPOSE_BLOCK_SLOT, b) - } - emit ProposingUpgradesRestrictedUntil(b, b + _zeroTrustPeriod()); - } - - function setZeroTrustPeriod(uint blocks) external IfAdmin { - // before this set at least once acts like a normal eip 1967 transparent proxy - uint ztp; - assembly { - ztp := sload(ZERO_TRUST_PERIOD_SLOT) - } - require(blocks > ztp, 'can be only set higher'); - assembly { - sstore(ZERO_TRUST_PERIOD_SLOT, blocks) - } - _updateNextBlockSlot(); - emit ZeroTrustPeriodSet(blocks); - } - - function _updateNextBlockSlot() internal { - uint nlb = block.number + _zeroTrustPeriod(); - assembly { - sstore(NEXT_LOGIC_BLOCK_SLOT, nlb) - } - } - - function _setNextLogic(address nl) internal { - require(block.number >= _proposeBlock(), 'too soon'); - _updateNextBlockSlot(); - assembly { - sstore(NEXT_LOGIC_SLOT, nl) - } - emit NextLogicDefined(nl, block.number + _zeroTrustPeriod()); - } - - function proposeTo(address newLogic, bytes calldata data) external payable IfAdmin { - if (_zeroTrustPeriod() == 0 || _logic() == address(0)) { - _updateNextBlockSlot(); - assembly { - sstore(LOGIC_SLOT, newLogic) - } - (bool success, ) = newLogic.delegatecall(data); - require(success, 'failed to call'); - emit Upgraded(newLogic); - } else { - _setNextLogic(newLogic); - } - } - - function _delegate(address logic_) internal { - assembly { - calldatacopy(0, 0, calldatasize()) - let result := delegatecall(gas(), logic_, 0, calldatasize(), 0, 0) - returndatacopy(0, 0, returndatasize()) - switch result - case 0 { - revert(0, returndatasize()) - } - default { - return(0, returndatasize()) - } - } - } -} -``` - -## Rationale - -An argument "just don't make such contracts upgadeable at all" fails when it comes to complex systems which do or do not heavily rely on human factor, which might manifest itself in unprecedented ways. It might be impossible to model some systems right on first try. Using decentralized governance for upgrade management coupled with EIP-1967 proxy might become a serious bottleneck for certain protocols before they mature and data is at hand. - -A proxy without a time delay before an actual upgrade is obviously abusable. A time delay is probably unavoidable, even if it means that inexperienced developers might not have confidence using it. Albeit this is a downside of this EIP, it's a critically important option to have in smart contract development today. - -## Security Considerations - -Users must ensure that a trust-minimized proxy they interact with does not allow overflows, ideally represents the exact copy of the code in implementation example above, and also they must ensure that Zero Trust Period length is reasonable(at the very least two weeks if upgrades are usually being revealed beforehand, and in most cases at least a month). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3561.md diff --git a/EIPS/eip-3569.md b/EIPS/eip-3569.md index e2419c3d9f8f7b..c7e67bcdf4946e 100644 --- a/EIPS/eip-3569.md +++ b/EIPS/eip-3569.md @@ -1,139 +1,7 @@ --- eip: 3569 -title: Sealed NFT Metadata Standard -author: Sean Papanikolas (@pizzarob) -discussions-to: https://ethereum-magicians.org/t/eip-3569-sealed-nft-metadata-standard/7130 -status: Stagnant -type: Standards Track category: ERC -created: 2021-05-07 +status: Moved --- -## Simple Summary - -The Sealed NFT Metadata Extension provides a mechanism to immortalize NFT metadata in a cost-effective manner. - -## Abstract - -This standard accomplishes three things; it provides a way for potential collectors to verify that the NFT metadata will not change, allows creators to immortalize metadata for multiple tokens at one time, and allows metadata for many NFTs to be read and cached from one file. A creator can call the `seal` function for a range of one or many sequential NFTs. Included as an argument is a URI which points to a decentralized storage service like IPFS and will be stored in the smart contract. The URI will return a JSON object in which the keys are token IDs and the values are either a string which is a URI pointing to a metadata file stored on a decentralized file system, or raw metadata JSON for each token ID. The token ID(s) will then be marked as sealed in the smart contract and cannot be sealed again. The `seal` function can be called after NFT creation, or during the NFT creation process. - -## Motivation - -In the original ERC-721 standard, the metadata extension specifies a `tokenURI` function which returns a URI for a single token ID. This may be hosted on IPFS or might be hosted on a centralized server. There's no guarantee that the NFT metadata will not change. This is the same for the ERC-1155 metadata extension. In addition to that - if you want to update the metadata for many NFTs you would need to do so in O(n) time, which as we know is not financially feasible at scale. By allowing for a decentralized URI to point to a JSON object of many NFT IDs we can solve this issue by providing metadata for many tokens at one time rather than one at a time. We can also provide methods which give transparency into whether the NFT has be explicitly "sealed" and that the metadata is hosted on a decentralized storage space. - -There is not a way for the smart contract layer to communicate with a storage layer and as such we need a solution which provides a way for potential NFT collectors on Ethereum to verify that their NFT will not be "rug pulled". This standard provides a solution for that. By allowing creators to seal their NFTs during or after creation, they are provided with full flexibility when it comes to creating their NFTs. Decentralized storage means permanence - in the fast-moving world of digital marketing campaigns, or art projects mistakes can happen. As such, it is important for creators to have flexibility when creating their projects. Therefore, this standard allows creators to opt in at a time of their choosing. Mistakes do happen and metadata should be flexible enough so that creators can fix mistakes or create dynamic NFTs (see Beeple's CROSSROAD NFT). If there comes a time when the NFT metadata should be immortalized, then the creator can call the `seal` method. Owners, potential owners, or platforms can verify that the NFT was sealed and can check the returned URI. If the `sealedURI` return value is not hosted on a decentralized storage platform, or the `isSealed` method does not return `true` for the given NFT ID then it can be said that one cannot trust that these NFTs will not change at a future date and can then decide if they want to proceed with collecting the given NFT. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -``` -interface SealedMetadata { - /** - @notice This function is used to set a sealed URI for the given range of tokens. - @dev - - If the sealed URI is being set for one token then the fromTokenId and toTokenId - values MUST be the same. - - - If any token within the range of tokens specified has already - been sealed then this function MUST throw. - - - This function MAY be called at the time of NFT creation, or after the NFTs have been created. - - - It is RECOMMENDED that this function only be executable by either the creator of the smart contract, - or the creator of the NFTs, but this is OPTIONAL and should be implemented based on use case. - - - This function MUST emit the Sealed event - - - The URI argument SHOULD point to a JSON file hosted within a decentralized file system like IPFS - - @param fromTokenId The first token in a consecutive range of tokens - @param toTokenId The ending token in a consecutive range of tokens - @param uri A URI which points to a JSON file hosted on a decentralized file system. - */ - function seal(uint256 fromTokenId, uint256 toTokenId, string memory uri) external; - - /** - @notice This function returns the URI which the sealed metadata can be found for the given token ID - @dev - - This function MUST throw if the token ID does not exist, or is not sealed - - @param tokenId Token ID to retrieve the sealed URI for - - @return The sealed URI in which the metadata for the given token ID can be found - */ - function sealedURI(uint256 tokenId) external view returns (string); - - /** - @notice This function returns a boolean stating if the token ID is sealed or not - @dev This function should throw if the token ID does not exist - - @param tokenId The token ID that will be checked if sealed or not - - @return Boolean stating if token ID is sealed - */ - function isSealed(uint256 tokenId) external view returns (bool) - - /// @dev This emits when a range of tokens is sealed - event Sealed(uint256 indexed fromTokenId, uint256 indexed toTokenId, string memory uri); - -} -``` - -### Sealed Metadata JSON Format - -The sealed metadata JSON file MAY contain metadata for many different tokens. The top level keys of the JSON object MUST be token IDs. - -``` - -type ERC721Metadata = { - name?: string; - image?: string; - description?: string; -} - -type SealedMetaDataJson = { - [tokenId: string]: string | ERC721Metadata; -} - -const sealedMetadata: SealedMetaDataJson = { - '1': { - name: 'Metadata for token with ID 1' - }, - '2': { - name: 'Metadata for token with ID 2' - }, - // Example pointing to another file - '3': 'ipfs://SOME_HASH_ON_IPFS' -}; -``` - -## Rationale - -**Rationale for rule not explicitly requiring that sealed URI be hosted on decentralized filestorage** - -In order for this standard to remain future proof there is no validation within the smart contract that would verify the sealed URI is hosted on IPFS or another decentralized file storage system. The standard allows potential collectors and platforms to validate the URI on the client. - -**Rationale to include many NFT metadata objects, or URIs in one JSON file** - -By including metadata for many NFTs in one JSON file we can eliminate the need for many transactions to set the metadata for multiple NFTs. Given that this file should not change NFT platforms, or explorers can cache the metadata within the file. - -**Rationale for emitting `Sealed` event** - -Platforms and explorers can use the `Sealed` event to automatically cache metadata, or update information regarding specified NFTs. - -**Rationale for allowing URIs as values in the JSON file** - -If a token's metadata is very large, or there are many tokens you can save file space by referencing another URI rather than storing the metadata JSON within the top level metadata file. - -## Backwards Compatibility - -There is no backwards compatibility with existing standards. This is an extension which could be added to existing NFT standards. - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3569.md diff --git a/EIPS/eip-3589.md b/EIPS/eip-3589.md index 1bfeb2edead5bd..366b587d703e0b 100644 --- a/EIPS/eip-3589.md +++ b/EIPS/eip-3589.md @@ -1,198 +1,7 @@ --- eip: 3589 -title: Assemble assets into NFTs -author: Zhenyu Sun (@Ungigdu), Xinqi Yang (@xinqiyang) -discussions-to: https://github.com/ethereum/EIPs/issues/3590 -status: Stagnant -type: Standards Track category: ERC -created: 2021-05-24 -requires: 721 +status: Moved --- -## Simple Summary -This standard defines a ERC-721 token called assembly token which can represent a combination of assets. - -## Abstract -The ERC-1155 multi-token contract defines a way to batch transfer tokens, but those tokens must be minted by the ERC-1155 contract itself. This EIP is an ERC-721 extension with ability to assemble assets such as ether, ERC-20 tokens, ERC-721 tokens and ERC-1155 tokens into one ERC-721 token whose token id is also the asset's signature. As assets get assembled into one, batch transfer or swap can be implemented very easily. - -## Motivation -As NFT arts and collectors rapidly increases, some collectors are not satisfied with traditional trading methods. When two collectors want to swap some of their collections, currently they can list their NFTs on the market and notify the other party to buy, but this is inefficient and gas-intensive. Instead, some collectors turn to social media or chat group looking for a trustworthy third party to swap NFTs for them. The third party takes NFTs from both collector A and B, and transfer A's collections to B and B's to A. This is very risky. - -The safest way to do batch swap, is to transform batch swap into atomic swap, i.e. one to one swap. But first we should "assemble" those ether, ERC-20 tokens, ERC-721 tokens and ERC-1155 tokens together, and this is the main purpose of this EIP. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -ERC-721 compliant contracts MAY implement this ERC to provide a standard method to assemble assets. - -`mint` and `safeMint` assemble assets into one ERC-721 token. `mint` SHOULD be implemented for normal ERC-20 tokens whose `_transfer` is lossless. `safeMint` MUST takes care for lossy token such as PIG token whose `_transfer` function is taxed. - -`_salt` of `hash` function MAY be implemented other way, even provided as user input. But the token id MUST be generated by `hash` function. - -Implementations of the standard MAY supports different set of assets. - -Implementers of this standard MUST have all of the following functions: - -``` -pragma solidity ^0.8.0; - -interface AssemblyNFTInterface { - - event AssemblyAsset(address indexed firstHolder, - uint256 indexed tokenId, - uint256 salt, - address[] addresses, - uint256[] numbers); - - /** - * @dev hash function assigns the combination of assets with salt to bytes32 signature that is also the token id. - * @param `_salt` prevents hash collision, can be chosen by user input or increasing nonce from contract. - * @param `_addresses` concat assets addresses, e.g. [ERC-20_address1, ERC-20_address2, ERC-721_address_1, ERC-1155_address_1, ERC-1155_address_2] - * @param `_numbers` describes how many eth, ERC-20 token addresses length, ERC-721 token addresses length, ERC-1155 token addresses length, - * ERC-20 token amounts, ERC-721 token ids, ERC-1155 token ids and amounts. - */ - function hash(uint256 _salt, address[] memory _addresses, uint256[] memory _numbers) external pure returns (uint256 tokenId); - - /// @dev to assemble lossless assets - /// @param `_to` the receiver of the assembly token - function mint(address _to, address[] memory _addresses, uint256[] memory _numbers) payable external returns(uint256 tokenId); - - /// @dev mint with additional logic that calculates the actual received value for tokens. - function safeMint(address _to, address[] memory _addresses, uint256[] memory _numbers) payable external returns(uint256 tokenId); - - /// @dev burn this token and releases assembled assets - /// @param `_to` to which address the assets is released - function burn(address _to, uint256 _tokenId, uint256 _salt, address[] calldata _addresses, uint256[] calldata _numbers) external; - -} - -``` - -## Rationale -There are many reasons why people want to pack their NFTs together. For example, a collector want to pack a set of football players into a football team; a collector has hundreds of of NFTs with no categories to manage them; a collector wants to buy a full collection of NFTs or none of them. They all need a way a assemble those NFTs together. - -The reason for choosing ERC-721 standard as a wrapper is ERC-721 token is already widely used and well supported by NFT wallets. And assembly token itself can also be assembled again. Assembly token is easier for smart contract to use than a batch of assets, in scenarios like batch trade, batch swap or collections exchange. - -This standard has AssemblyAsset event which records the exact kinds and amounts of assets the assembly token represents. The wallet can easily display those NFTs to user just by the token id. - -## Backwards Compatibility -This proposal combines already available 721 extensions and is backwards compatible with the ERC-721 standard. - -## Implementation -``` -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; -import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; -import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; -import "./AssemblyNFTInterface.sol"; - -abstract contract AssemblyNFT is ERC721, ERC721Holder, ERC1155Holder, AssemblyNFTInterface{ - using SafeERC20 for IERC20; - - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC1155Receiver) returns (bool) { - return ERC721.supportsInterface(interfaceId) || ERC1155Receiver.supportsInterface(interfaceId); - } - - uint256 nonce; - - /** - * layout of _addresses: - * erc20 addresses | erc721 addresses | erc1155 addresses - * layout of _numbers: - * eth | erc20.length | erc721.length | erc1155.length | erc20 amounts | erc721 ids | erc1155 ids | erc1155 amounts - */ - - function hash(uint256 _salt, address[] memory _addresses, uint256[] memory _numbers) public pure override returns (uint256 tokenId){ - bytes32 signature = keccak256(abi.encodePacked(_salt)); - for(uint256 i=0; i< _addresses.length; i++){ - signature = keccak256(abi.encodePacked(signature, _addresses[i])); - } - for(uint256 j=0; j<_numbers.length; j++){ - signature = keccak256(abi.encodePacked(signature, _numbers[j])); - } - assembly { - tokenId := signature - } - } - - function mint(address _to, address[] memory _addresses, uint256[] memory _numbers) payable external override returns(uint256 tokenId){ - require(_to != address(0), "can't mint to address(0)"); - require(msg.value == _numbers[0], "value not match"); - require(_addresses.length == _numbers[1] + _numbers[2] + _numbers[3], "2 array length not match"); - require(_addresses.length == _numbers.length -4 - _numbers[3], "numbers length not match"); - uint256 pointerA; //points to first erc20 address, if there is any - uint256 pointerB =4; //points to first erc20 amount, if there is any - for(uint256 i = 0; i< _numbers[1]; i++){ - require(_numbers[pointerB] > 0, "transfer erc20 0 amount"); - IERC20(_addresses[pointerA++]).safeTransferFrom(_msgSender(), address(this), _numbers[pointerB++]); - } - for(uint256 j = 0; j< _numbers[2]; j++){ - IERC721(_addresses[pointerA++]).safeTransferFrom(_msgSender(), address(this), _numbers[pointerB++]); - } - for(uint256 k =0; k< _numbers[3]; k++){ - IERC1155(_addresses[pointerA++]).safeTransferFrom(_msgSender(), address(this), _numbers[pointerB], _numbers[_numbers[3] + pointerB++], ""); - } - tokenId = hash(nonce, _addresses, _numbers); - super._mint(_to, tokenId); - emit AssemblyAsset(_to, tokenId, nonce, _addresses, _numbers); - nonce ++; - } - - function safeMint(address _to, address[] memory _addresses, uint256[] memory _numbers) payable external override returns(uint256 tokenId){ - require(_to != address(0), "can't mint to address(0)"); - require(msg.value == _numbers[0], "value not match"); - require(_addresses.length == _numbers[1] + _numbers[2] + _numbers[3], "2 array length not match"); - require(_addresses.length == _numbers.length -4 - _numbers[3], "numbers length not match"); - uint256 pointerA; //points to first erc20 address, if there is any - uint256 pointerB =4; //points to first erc20 amount, if there is any - for(uint256 i = 0; i< _numbers[1]; i++){ - require(_numbers[pointerB] > 0, "transfer erc20 0 amount"); - IERC20 token = IERC20(_addresses[pointerA++]); - uint256 orgBalance = token.balanceOf(address(this)); - token.safeTransferFrom(_msgSender(), address(this), _numbers[pointerB]); - _numbers[pointerB++] = token.balanceOf(address(this)) - orgBalance; - } - for(uint256 j = 0; j< _numbers[2]; j++){ - IERC721(_addresses[pointerA++]).safeTransferFrom(_msgSender(), address(this), _numbers[pointerB++]); - } - for(uint256 k =0; k< _numbers[3]; k++){ - IERC1155(_addresses[pointerA++]).safeTransferFrom(_msgSender(), address(this), _numbers[pointerB], _numbers[_numbers[3] + pointerB++], ""); - } - tokenId = hash(nonce, _addresses, _numbers); - super._mint(_to, tokenId); - emit AssemblyAsset(_to, tokenId, nonce, _addresses, _numbers); - nonce ++; - } - - function burn(address _to, uint256 _tokenId, uint256 _salt, address[] calldata _addresses, uint256[] calldata _numbers) override external { - require(_msgSender() == ownerOf(_tokenId), "not owned"); - require(_tokenId == hash(_salt, _addresses, _numbers)); - super._burn(_tokenId); - payable(_to).transfer(_numbers[0]); - uint256 pointerA; //points to first erc20 address, if there is any - uint256 pointerB =4; //points to first erc20 amount, if there is any - for(uint256 i = 0; i< _numbers[1]; i++){ - require(_numbers[pointerB] > 0, "transfer erc20 0 amount"); - IERC20(_addresses[pointerA++]).safeTransfer(_to, _numbers[pointerB++]); - } - for(uint256 j = 0; j< _numbers[2]; j++){ - IERC721(_addresses[pointerA++]).safeTransferFrom(address(this), _to, _numbers[pointerB++]); - } - for(uint256 k =0; k< _numbers[3]; k++){ - IERC1155(_addresses[pointerA++]).safeTransferFrom(address(this), _to, _numbers[pointerB], _numbers[_numbers[3] + pointerB++], ""); - } - } - -} -``` - -## Security Considerations -Before using `mint` or `safeMint` functions, user should be aware that some implementations of tokens are pausable. If one of the assets get paused after assembled into one NFT, the `burn` function may not be executed successfully. Platforms using this standard should make support lists or block lists to avoid this situation. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3589.md diff --git a/EIPS/eip-3607.md b/EIPS/eip-3607.md index c4479a5b198868..78ed1ee17a83aa 100644 --- a/EIPS/eip-3607.md +++ b/EIPS/eip-3607.md @@ -46,7 +46,7 @@ We note that it was always the expected that a contract account's behaviour is c This does not exclude all possible attack vectors, only the most serious one. Further possible attack vectors via address collisions between contracts and EOAs are: 1. An attacker can convince a user to send funds to an account before it is deployed. Some applications require this behaviour (e.g. state channels). 2. A chain reorg can happen after a contract is deployed. If the reorg removes the contract deployment transaction the funds can still be accessed using the private key. -3. A contract can self desctruct, with the stated intention that ERC20s (or other tokens) in the contract would be burned. However, they can now be accessed by a key for that address. +3. A contract can self destruct, with the stated intention that ERC20s (or other tokens) in the contract would be burned. However, they can now be accessed by a key for that address. All these scenarios are much harder to exploit for an attacker, and likely have much lower yield making the attacks unlikely to be economically viable. diff --git a/EIPS/eip-3643.md b/EIPS/eip-3643.md index 9a41f2e0af7d32..5a68a2e19e5d9e 100644 --- a/EIPS/eip-3643.md +++ b/EIPS/eip-3643.md @@ -1,382 +1,7 @@ --- eip: 3643 -title: T-REX - Token for Regulated EXchanges -description: An institutional grade security token standard that provides interfaces for the management and compliant transfer of security tokens. -author: Joachim Lebrun (@Joachim-Lebrun), Tony Malghem (@TonyMalghem), Kevin Thizy (@Nakasar), Luc Falempin (@lfalempin), Adam Boudjemaa (@Aboudjem) -type: Standards Track category: ERC -status: Stagnant -requires: 20, 1822 -discussions-to: https://ethereum-magicians.org/t/eip-3643-proposition-of-the-t-rex-token-standard-for-securities/6844 -created: 2021-07-09 +status: Moved --- -## Simple Summary - -The T-REX token is -This standard - - -## Abstract - -Standards should be backwards compatible with [ERC-20](./eip-20.md) and should be able to interact with [ERC-735](https://github.com/ethereum/EIPs/issues/735) to validate the claims linked to an [`ONCHAINID`](https://github.com/onchain-id/solidity), based on [ERC-734](https://github.com/ethereum/EIPs/issues/734) and ERC-735. -The standard defines several interfaces that are described hereunder: -- Token -- Identity Registry -- Identity Registry Storage -- Compliance -- Trusted Issuers Registry -- Claim Topics Registry - -## Motivation - -Give standard interfaces for security tokens issued on Ethereum, through which any third party could interact with the security token. -The functions described by these interfaces vary and allow the appropriate users to call a range of different actions, such as forced transfers, freeze tokens (partially or totally on a wallet or even freeze the entire token), minting, burning, recover lost tokens (if an investor loses access to his wallet), etc. - -The following requirements have been compiled following discussions with parties across financial institutions that are looking to issue securities on a DLT infrastructure such as ethereum. - -- **MUST** be [ERC-20](./eip-20.md) compatible. -- **MUST** be used in combination with an Identification system onchain ([ONCHAINID](https://github.com/onchain-id/solidity)) -- **MUST** be able to apply any rule of compliance that is required by the regulator or by the token issuer (about the factors of eligibility of an identity or about the rules of the token itself) -- **MUST** have a standard interface to pre-check if a transfer is going to pass or fail before sending it to the blockchain -- **MUST** have a recovery system in case an investor loses access to his private key -- **MUST** be able to freeze tokens on the wallet of investors if needed, partially or totally -- **MUST** have the possibility to pause the token -- **MUST** be able to mint and burn tokens -- **MUST** define an Agent role and an Owner (token issuer) role -- **MUST** be able to force transfers from an Agent wallet -- **MUST** be able to issue transactions in batch (to save gas and to have all the transactions performed in the same block) -- **MUST** be upgradeable (code of the smart contract should be upgradeable without changing the token smart contract address) - -## Rationale - -### Transfer Restrictions - -Transfers of securities can fail for a variety of reasons. This is in direct contrast to utility tokens, of which generally only require the sender to have a sufficient balance. -These conditions can be related to the status of an investor’s wallet, the identity of the sender and receiver of the securities (i.e. whether they -have been through a KYC process, whether they are accredited or an affiliate of the issuer) or for reasons unrelated to the specific transfer but instead set at -the token level (i.e. the token contract enforces a maximum number of investors or a cap on the percentage held by any single investor). -For [ERC-20](./eip-20.md) tokens, the `balanceOf` and `allowance` functions provide a way to check that a transfer is likely to succeed before executing the transfer, which can be -executed both on-chain and off-chain. -For tokens representing securities, the T-REX standard introduces a function `canTransfer` which provides a more general purpose way to achieve this. I.e. when the reasons for -failure are related to the compliance rules of the token and a function `isVerified` which allows to check the eligibility status of the identity of the investor. - -### Upgradeability - -The token contract should be upgradeable without changing its address on the blockchain, therefore, we decided to make it `proxiable` through [ERC-1822](./eip-1822.md) (Universal Upgradeable Proxy Standard) - -### Identity Management - -Security and compliance of transfers is issued through the management of onchain identities. -- ONCHAINID -- Claim -- Identity Storage/registry -Transfers of securities can fail for a variety of reasons in contrast to utility tokens which generally only require the sender to have a sufficient balance. - - -## Specification - -This standard is backwards compatible with [ERC-20](./eip-20.md), therefore, all ERC-20 functions can be called on an ERC-3643 token, the interfaces being compatible. -But the functions are not implemented in the same way as a classic ERC-20 as ERC-3643 is a permissioned token, which implies a check to be performed on each single -token transfer to validate the compliance of the transfer and the eligibility of the stakeholder’s identities. - -### Main functions - -#### Transfer - -To be able to perform a transfer on T-REX you need to fulfill several conditions : - -- The sender needs to hold enough free balance (total balance - frozen tokens, if any) -- The receiver needs to be whitelisted on the Identity Registry and verified (hold the necessary claims on his [ONCHAINID](https://github.com/onchain-id/solidity)) -- The sender's wallet cannot be frozen -- The receiver's wallet cannot be frozen -- The transfer has to respect all the rules of compliance defined in the `Compliance` smart contract (`canTransfer` needs to return `TRUE`) - -Here is an example of `transfer` function implementation : -```solidity -function transfer(address _to, uint256 _amount) public override whenNotPaused returns (bool) { - require(!frozen[_to] && !frozen[msg.sender], 'wallet is frozen'); - require(_amount <= balanceOf(msg.sender).sub(frozenTokens[msg.sender]), 'Insufficient Balance'); - if (tokenIdentityRegistry.isVerified(_to) && tokenCompliance.canTransfer(msg.sender, _to, _amount)) { - tokenCompliance.transferred(msg.sender, _to, _amount); - _transfer(msg.sender, _to, _amount); - return true; - } - revert('Transfer not possible'); - } - ``` - - The `transferFrom` function works the same way while the `mint` function and the `forcedTransfer` function only require the receiver to be whitelisted and verified on the Identity Registry (they bypass the compliance rules). The `burn` function bypasses all checks on eligibility. - -#### isVerified - -The `isVerified` function is called from within the transfer functions `transfer`, `transferFrom`, `mint` and `forcedTransfer` to instruct the `Identity Registry` to check if the receiver is a valid investor, i.e. if his wallet address is in the `Identity Registry` of the token, and if the `ONCHAINID`contract linked to his wallet contains the claims (see ERC-735) required in the `Claim Topics Registry` and if these claims are signed by an authorized Claim Issuer as required in the `Trusted Issuers Registry`. -If all the requirements are fulfilled, the `isVerified` function returns `TRUE`, otherwise it returns `FALSE`. An implementation of this function can be found on the [T-REX repository](https://github.com/TokenySolutions/T-REX). - -#### canTransfer - -The `canTransfer` function is also called from within transfer functions. This function checks if the transfer is compliant with global compliance rules applied to the token, in opposition with `isVerified` that only checks the eligibility of an investor to hold and receive tokens, the `canTransfer` function is looking at global compliance rules, e.g. check if the transfer is compliant in the case there is a fixed maximum number of token holders to respect (can be a limited number of holders per country as well), check if the transfer respects rules setting a maximum amount of tokens per investor, ... -If all the requirements are fulfilled, the `canTransfer` function will return `TRUE` otherwise it will return `FALSE` and the transfer will not be allowed to happen. An implementation of this function can be found on the [T-REX repository](https://github.com/TokenySolutions/T-REX). - -#### Other functions - -Description of other functions of the ERC-3643 can be found in the `interfaces` folder. An implementation of the ERC-3643 suite of smart contracts can be found on the [T-REX repository](https://github.com/TokenySolutions/T-REX). - -### Token interface - -ERC-3643 permissioned tokens are based on a standard ERC-20 structure but with some functions being added in order to ensure compliance in the transactions of the security tokens. The functions `transfer` and `transferFrom` are implemented in a conditional way, allowing them to proceed with a transfer only IF the transaction is valid. The permissioned tokens are allowed to be transferred only to validated counterparties, in order to avoid tokens being held in wallets/ONCHAINIDs of ineligible/unauthorized investors. The ERC-3643 standard also supports the recovery of security tokens in case an investor loses his/her wallet private key. A history of recovered tokens is maintained on the blockchain for transparency reasons. ERC-3643 tokens are implementing a lot of additional functions to give the owner or his agent the possibility to manage supply, transfer rules, lockups and everything that could be required in the management of a security. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces). - -```solidity -interface IERC3643 is IERC20 { - - // events - event UpdatedTokenInformation(string _newName, string _newSymbol, uint8 _newDecimals, string _newVersion, address _newOnchainID); - event IdentityRegistryAdded(address indexed _identityRegistry); - event ComplianceAdded(address indexed _compliance); - event RecoverySuccess(address _lostWallet, address _newWallet, address _investorOnchainID); - event AddressFrozen(address indexed _userAddress, bool indexed _isFrozen, address indexed _owner); - event TokensFrozen(address indexed _userAddress, uint256 _amount); - event TokensUnfrozen(address indexed _userAddress, uint256 _amount); - event Paused(address _userAddress); - event Unpaused(address _userAddress); - - - // functions - // getters - function decimals() external view returns (uint8); - function name() external view returns (string memory); - function onchainID() external view returns (address); - function symbol() external view returns (string memory); - function version() external view returns (string memory); - function identityRegistry() external view returns (IIdentityRegistry); - function compliance() external view returns (ICompliance); - function paused() external view returns (bool); - function isFrozen(address _userAddress) external view returns (bool); - function getFrozenTokens(address _userAddress) external view returns (uint256); - - // setters - function setName(string calldata _name) external; - function setSymbol(string calldata _symbol) external; - function setOnchainID(address _onchainID) external; - function pause() external; - function unpause() external; - function setAddressFrozen(address _userAddress, bool _freeze) external; - function freezePartialTokens(address _userAddress, uint256 _amount) external; - function unfreezePartialTokens(address _userAddress, uint256 _amount) external; - function setIdentityRegistry(address _identityRegistry) external; - function setCompliance(address _compliance) external; - - // transfer actions - function forcedTransfer(address _from, address _to, uint256 _amount) external returns (bool); - function mint(address _to, uint256 _amount) external; - function burn(address _userAddress, uint256 _amount) external; - function recoveryAddress(address _lostWallet, address _newWallet, address _investorOnchainID) external returns (bool); - - // batch functions - function batchTransfer(address[] calldata _toList, uint256[] calldata _amounts) external; - function batchForcedTransfer(address[] calldata _fromList, address[] calldata _toList, uint256[] calldata _amounts) external; - function batchMint(address[] calldata _toList, uint256[] calldata _amounts) external; - function batchBurn(address[] calldata _userAddresses, uint256[] calldata _amounts) external; - function batchSetAddressFrozen(address[] calldata _userAddresses, bool[] calldata _freeze) external; - function batchFreezePartialTokens(address[] calldata _userAddresses, uint256[] calldata _amounts) external; - function batchUnfreezePartialTokens(address[] calldata _userAddresses, uint256[] calldata _amounts) external; - - // roles setting - function transferOwnershipOnTokenContract(address _newOwner) external; - function addAgentOnTokenContract(address _agent) external; - function removeAgentOnTokenContract(address _agent) external; -} - -``` - -### Identity Registry Interface - -This Identity Registry is linked to storage that contains a dynamic whitelist of identities. The Identity Registry makes the link between a wallet address, an [ONCHAINID](https://tokeny.com/onchainid/) and a country code corresponding to the country of residence of the investor, this country code is set in accordance with the [ISO-3166 standard](https://www.iso.org/iso-3166-country-codes.html). It also contains a function called `isVerified()`, which returns a status based on the validity of claims (as per the security token requirements) in the user’s ONCHAINID. The Identity Registry is managed by the agent wallet(s) i.e. only the agent(s) can add or remove identities in the registry (note: the agent role on the Identity Registry is set by the owner, therefore the owner could set himself as the agent if he wants to keep everything under his own control). There is a specific identity registry for each security token. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces). - -Note that [`IClaimIssuer`](https://github.com/onchain-id/solidity/blob/master/contracts/interface/IClaimIssuer.sol) and [`IIdentity`](https://github.com/onchain-id/solidity/blob/master/contracts/interface/IIdentity.sol) are needed in this interface and are coming from [ONCHAINID](https://github.com/onchain-id/solidity) - -```solidity -interface IIdentityRegistry { - - - // events - event ClaimTopicsRegistrySet(address indexed claimTopicsRegistry); - event IdentityStorageSet(address indexed identityStorage); - event TrustedIssuersRegistrySet(address indexed trustedIssuersRegistry); - event IdentityRegistered(address indexed investorAddress, IIdentity indexed identity); - event IdentityRemoved(address indexed investorAddress, IIdentity indexed identity); - event IdentityUpdated(IIdentity indexed oldIdentity, IIdentity indexed newIdentity); - event CountryUpdated(address indexed investorAddress, uint16 indexed country); - - - // functions - // identity registry getters - function identityStorage() external view returns (IIdentityRegistryStorage); - function issuersRegistry() external view returns (ITrustedIssuersRegistry); - function topicsRegistry() external view returns (IClaimTopicsRegistry); - - //identity registry setters - function setIdentityRegistryStorage(address _identityRegistryStorage) external; - function setClaimTopicsRegistry(address _claimTopicsRegistry) external; - function setTrustedIssuersRegistry(address _trustedIssuersRegistry) external; - - // registry actions - function registerIdentity(address _userAddress, IIdentity _identity, uint16 _country) external; - function deleteIdentity(address _userAddress) external; - function updateCountry(address _userAddress, uint16 _country) external; - function updateIdentity(address _userAddress, IIdentity _identity) external; - function batchRegisterIdentity(address[] calldata _userAddresses, IIdentity[] calldata _identities, uint16[] calldata _countries) external; - - // registry consultation - function contains(address _userAddress) external view returns (bool); - function isVerified(address _userAddress) external view returns (bool); - function identity(address _userAddress) external view returns (IIdentity); - function investorCountry(address _userAddress) external view returns (uint16); - - // roles setters - function transferOwnershipOnIdentityRegistryContract(address _newOwner) external; - function addAgentOnIdentityRegistryContract(address _agent) external; - function removeAgentOnIdentityRegistryContract(address _agent) external; -} -``` - -### Identity Registry Storage Interface - -The Identity Registry Storage stores the identity addresses of all the authorized investors in the security token(s) linked to the storage contract i.e. all identities of investors who have been authorized to hold the token(s) after having gone through the appropriate KYC and eligibility checks. The Identity Registry Storage can be bound to one or several Identity Registry contract(s). The goal of the Identity Registry storage is to separate the Identity Registry functions and specifications from its storage, this way it is possible to keep one single Identity Registry contract per token, with its own Trusted Issuers Registry and Claim Topics Registry but with a shared whitelist of investors used by the `isVerifed()` function implemented in the Identity Registries to check the eligibility of the receiver in a transfer transaction. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces). - -```solidity -interface IIdentityRegistryStorage { - - //events - event IdentityStored(address indexed investorAddress, IIdentity indexed identity); - event IdentityUnstored(address indexed investorAddress, IIdentity indexed identity); - event IdentityModified(IIdentity indexed oldIdentity, IIdentity indexed newIdentity); - event CountryModified(address indexed investorAddress, uint16 indexed country); - event IdentityRegistryBound(address indexed identityRegistry); - event IdentityRegistryUnbound(address indexed identityRegistry); - - //functions - // storage related functions - function storedIdentity(address _userAddress) external view returns (IIdentity); - function storedInvestorCountry(address _userAddress) external view returns (uint16); - function addIdentityToStorage(address _userAddress, IIdentity _identity, uint16 _country) external; - function removeIdentityFromStorage(address _userAddress) external; - function modifyStoredInvestorCountry(address _userAddress, uint16 _country) external; - function modifyStoredIdentity(address _userAddress, IIdentity _identity) external; - - // role setter - function transferOwnershipOnIdentityRegistryStorage(address _newOwner) external; - function bindIdentityRegistry(address _identityRegistry) external; - function unbindIdentityRegistry(address _identityRegistry) external; - - // getter for bound IdentityRegistry role - function linkedIdentityRegistries() external view returns (address[] memory); -} - -``` - -### Compliance Interface - -The Compliance is used to set the rules of the offering itself and ensures these rules are respected during the whole lifecycle of the token, e.g. the compliance contract will define the maximum amount of investors per country, the maximum amount of tokens per investor, the accepted countries for the circulation of the token (using the country code corresponding to each investor in the Identity Registry). The compliance smart contract is a “tailor-made” contract that is implemented in accordance with the legal requirements and following the desires of the token issuer. This contract is triggered at every transaction by the Token and returns `TRUE` if the transaction is compliant with the rules of the offering and `FALSE` otherwise. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces). - -```solidity -interface ICompliance { - - // events - event TokenAgentAdded(address _agentAddress); - event TokenAgentRemoved(address _agentAddress); - event TokenBound(address _token); - event TokenUnbound(address _token); - - // functions - // initialization of the compliance contract - function addTokenAgent(address _agentAddress) external; - function removeTokenAgent(address _agentAddress) external; - function bindToken(address _token) external; - function unbindToken(address _token) external; - - // check the parameters of the compliance contract - function isTokenAgent(address _agentAddress) external view returns (bool); - function isTokenBound(address _token) external view returns (bool); - - // compliance check and state update - function canTransfer(address _from, address _to, uint256 _amount) external view returns (bool); - function transferred(address _from, address _to, uint256 _amount) external; - function created(address _to, uint256 _amount) external; - function destroyed(address _from, uint256 _amount) external; - - // setting owner role - function transferOwnershipOnComplianceContract(address newOwner) external; -} -``` - -### Trusted Issuer's Registry Interface - -The Trusted Issuer's Registry stores the contract addresses ([ONCHAINID](https://tokeny.com/onchainid/)) of all the trusted claim issuers for a specific security token. The [ONCHAINID](https://tokeny.com/onchainid/) of token owners (the investors) must have claims signed by the claim issuers stored in this smart contract in order to be able to hold the token. The ownership of this contract is given to the token issuer allowing them to manage this registry as per their requirements. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces) - -```solidity -interface ITrustedIssuersRegistry { - - // events - event TrustedIssuerAdded(IClaimIssuer indexed trustedIssuer, uint[] claimTopics); - event TrustedIssuerRemoved(IClaimIssuer indexed trustedIssuer); - event ClaimTopicsUpdated(IClaimIssuer indexed trustedIssuer, uint[] claimTopics); - - // functions - // setters - function addTrustedIssuer(IClaimIssuer _trustedIssuer, uint[] calldata _claimTopics) external; - function removeTrustedIssuer(IClaimIssuer _trustedIssuer) external; - function updateIssuerClaimTopics(IClaimIssuer _trustedIssuer, uint[] calldata _claimTopics) external; - - // getters - function getTrustedIssuers() external view returns (IClaimIssuer[] memory); - function isTrustedIssuer(address _issuer) external view returns(bool); - function getTrustedIssuerClaimTopics(IClaimIssuer _trustedIssuer) external view returns(uint[] memory); - function hasClaimTopic(address _issuer, uint _claimTopic) external view returns(bool); - - // role setter - function transferOwnershipOnIssuersRegistryContract(address _newOwner) external; -} -``` - -### Claim Topics Registry Interface - -The Claim Topics Registry stores all the trusted claim topics for the security token. The [ONCHAINID](https://tokeny.com/onchainid/) of token owners must contain claims of the claim topics stored in this smart contract. The ownership of this contract is given to the token issuer allowing them to manage this registry as per their requirements. -A detailed description of the functions can be found in the [interfaces folder](https://github.com/TokenySolutions/EIP3643/tree/main/interfaces) - -```solidity -interface IClaimTopicsRegistry { - - // events - event ClaimTopicAdded(uint256 indexed claimTopic); - event ClaimTopicRemoved(uint256 indexed claimTopic); - - // functions - // setters - function addClaimTopic(uint256 _claimTopic) external; - function removeClaimTopic(uint256 _claimTopic) external; - - // getter - function getClaimTopics() external view returns (uint256[] memory); - - // role setter - function transferOwnershipOnClaimTopicsRegistryContract(address _newOwner) external; -} -``` - -## Test Cases - -The standard is implemented and tested with full coverage on Tokeny's [T-REX repository](https://github.com/TokenySolutions/T-REX) - -## Security Considerations - -The suite of Smart Contracts has been audited by an external and independent company. The results can be found in [this document](https://tokeny.com/wp-content/uploads/2020/05/Tokeny-Solutions_T-REX-v3_Smart-Contract-Audit-Report_Kapersky.pdf). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3643.md diff --git a/EIPS/eip-3651.md b/EIPS/eip-3651.md index 67666a415871b2..d94c694c6f1229 100644 --- a/EIPS/eip-3651.md +++ b/EIPS/eip-3651.md @@ -4,7 +4,7 @@ title: Warm COINBASE description: Starts the `COINBASE` address warm author: William Morriss (@wjmelements) discussions-to: https://ethereum-magicians.org/t/eip-3651-warm-coinbase/6640 -status: Review +status: Final type: Standards Track category: Core created: 2021-07-12 @@ -19,7 +19,7 @@ The `COINBASE` address shall be warm at the start of transaction execution, in a Direct `COINBASE` payments are becoming increasingly popular because they allow conditional payments, which provide benefits such as implicit cancellation of transactions that would revert. But accessing `COINBASE` is overpriced; the address is initially cold under the access list framework introduced in [EIP-2929](./eip-2929.md). -This gas cost mismatch can incentivize alternative payments besides ETH, such as [EIP-20](./eip-20.md), but ETH should be the primary means of paying for transactions on Ethereum. +This gas cost mismatch can incentivize alternative payments besides ETH, such as [ERC-20](./eip-20.md), but ETH should be the primary means of paying for transactions on Ethereum. ## Specification diff --git a/EIPS/eip-3668.md b/EIPS/eip-3668.md index b04d3dc51311c3..a84cf0257fb76f 100644 --- a/EIPS/eip-3668.md +++ b/EIPS/eip-3668.md @@ -1,410 +1,7 @@ --- eip: 3668 -title: "CCIP Read: Secure offchain data retrieval" -description: CCIP Read provides a mechanism to allow a contract to fetch external data. -author: Nick Johnson (@arachnid) -discussions-to: https://ethereum-magicians.org/t/durin-secure-offchain-data-retrieval/6728 -status: Final -type: Standards Track category: ERC -created: 2020-07-19 +status: Moved --- -## Abstract -Contracts wishing to support lookup of data from external sources may, instead of returning the data directly, revert using `OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData)`. Clients supporting this specification then make an RPC call to a URL from `urls`, supplying `callData`, and getting back an opaque byte string `response`. Finally, clients call the function specified by `callbackFunction` on the contract, providing `response` and `extraData`. The contract can then decode and verify the returned data using an implementation-specific method. - -This mechanism allows for offchain lookups of data in a way that is transparent to clients, and allows contract authors to implement whatever validation is necessary; in many cases this can be provided without any additional trust assumptions over and above those required if data is stored onchain. - -## Motivation -Minimising storage and transaction costs on Ethereum has driven contract authors to adopt a variety of techniques for moving data offchain, including hashing, recursive hashing (eg Merkle Trees/Tries) and L2 solutions. While each solution has unique constraints and parameters, they all share in common the fact that enough information is stored onchain to validate the externally stored data when required. - -Thus far, applications have tended to devise bespoke solutions rather than trying to define a universal standard. This is practical - although inefficient - when a single offchain data storage solution suffices, but rapidly becomes impractical in a system where multiple end-users may wish to make use of different data storage and availability solutions based on what suits their needs. - -By defining a common specification allowing smart contract to fetch data from offchain, we facilitate writing clients that are entirely agnostic to the storage solution being used, which enables new applications that can operate without knowing about the underlying storage details of the contracts they interact with. - -Examples of this include: - - Interacting with 'airdrop' contracts that store a list of recipients offchain in a merkle trie. - - Viewing token information for tokens stored on an L2 solution as if they were native L1 tokens. - - Allowing delegation of data such as ENS domains to various L2 solutions, without requiring clients to support each solution individually. - - Allowing contracts to proactively request external data to complete a call, without requiring the caller to be aware of the details of that data. - -## Specification -### Overview -Answering a query via CCIP read takes place in three steps: - - 1. Querying the contract. - 2. Querying the gateway using the URL provided in (1). - 3. Querying or sending a transaction to the contract using the data from (1) and (2). - -In step 1, a standard blockchain call operation is made to the contract. The contract reverts with an error that specifies the data to complete the call can be found offchain, and provides the url to a service that can provide the answer, along with additional contextual information required for the call in step (3). - -In step 2, the client calls the gateway service with the `callData` from the revert message in step (1). The gateway responds with an answer `response`, whose content is opaque to the client. - -In step 3, the client calls the original contract, supplying the `response` from step (2) and the `extraData` returned by the contract in step (1). The contract decodes the provided data and uses it to validate the response and act on it - by returning information to the client or by making changes in a transaction. The contract could also revert with a new error to initiate another lookup, in which case the protocol starts again at step 1. - -``` -┌──────┐ ┌────────┐ ┌─────────────┐ -│Client│ │Contract│ │Gateway @ url│ -└──┬───┘ └───┬────┘ └──────┬──────┘ - │ │ │ - │ somefunc(...) │ │ - ├─────────────────────────────────────────────────►│ │ - │ │ │ - │ revert OffchainData(sender, urls, callData, │ │ - │ callbackFunction, extraData) │ │ - │◄─────────────────────────────────────────────────┤ │ - │ │ │ - │ HTTP request (sender, callData) │ │ - ├──────────────────────────────────────────────────┼────────────►│ - │ │ │ - │ Response (result) │ │ - │◄─────────────────────────────────────────────────┼─────────────┤ - │ │ │ - │ callbackFunction(result, extraData) │ │ - ├─────────────────────────────────────────────────►│ │ - │ │ │ - │ answer │ │ - │◄─────────────────────────────────────────────────┤ │ - │ │ │ -``` - -### Contract interface - -A CCIP read enabled contract MUST revert with the following error whenever a function that requires offchain data is called: - -```solidity -error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData) -``` - -`sender` is the address of the contract that raised the error, and is used to determine if the error was thrown by the contract the client called, or 'bubbled up' from a nested call. - -`urls` specifies a list of URL templates to services (known as gateways) that implement the CCIP read protocol and can formulate an answer to the query. `urls` can be the empty list `[]`, in which case the client MUST specify the URL template. The order in which URLs are tried is up to the client, but contracts SHOULD return them in order of priority, with the most important entry first. - -Each URL may include two substitution parameters, `{sender}` and `{data}`. Before a call is made to the URL, `sender` is replaced with the lowercase 0x-prefixed hexadecimal formatted `sender` parameter, and `data` is replaced by the the 0x-prefixed hexadecimal formatted `callData` parameter. - -`callData` specifies the data to call the gateway with. This value is opaque to the client. Typically this will be ABI-encoded, but this is an implementation detail that contracts and gateways can standardise on as desired. - -`callbackFunction` is the 4-byte function selector for a function on the original contract to which a callback should be sent. - -`extraData` is additional data that is required by the callback, and MUST be retained by the client and provided unmodified to the callback function. This value is opaque to the client. - -The contract MUST also implement a callback method for decoding and validating the data returned by the gateway. The name of this method is implementation-specific, but it MUST have the signature `(bytes response, bytes extraData)`, and MUST have the same return type as the function that reverted with `OffchainLookup`. - -If the client successfully calls the gateway, the callback function specified in the `OffchainLookup` error will be invoked by the client, with `response` set to the value returned by the gateway, and `extraData` set to the value returned in the contract's `OffchainLookup` error. The contract MAY initiate another CCIP read lookup in this callback, though authors should bear in mind that the limits on number of recursive invocations will vary from client to client. - -In a call context (as opposed to a transaction), the return data from this call will be returned to the user as if it was returned by the function that was originally invoked. - -#### Example - -Suppose a contract has the following method: - -```solidity -function balanceOf(address addr) public view returns(uint balance); -``` - -Data for these queries is stored offchain in some kind of hashed data structure, the details of which are not important for this example. The contract author wants the gateway to fetch the proof information for this query and call the following function with it: - -```solidity -function balanceOfWithProof(bytes calldata response, bytes calldata extraData) public view returns(uint balance); -``` - -One example of a valid implementation of `balanceOf` would thus be: - -```solidity -function balanceOf(address addr) public view returns(uint balance) { - revert OffchainLookup( - address(this), - [url], - abi.encodeWithSelector(Gateway.getSignedBalance.selector, addr), - ContractName.balanceOfWithProof.selector, - abi.encode(addr) - ); -} -``` - -Note that in this example the contract is returning `addr` in both `callData` and `extraData`, because it is required both by the gateway (in order to look up the data) and the callback function (in order to verify it). The contract cannot simply pass it to the gateway and rely on it being returned in the response, as this would give the gateway an opportunity to respond with an answer to a different query than the one that was initially issued. - -#### Recursive calls in CCIP-aware contracts - -When a CCIP-aware contract wishes to make a call to another contract, and the possibility exists that the callee may implement CCIP read, the calling contract MUST catch all `OffchainLookup` errors thrown by the callee, and revert with a different error if the `sender` field of the error does not match the callee address. - -The contract MAY choose to replace all `OffchainLookup` errors with a different error. Doing so avoids the complexity of implementing support for nested CCIP read calls, but renders them impossible. - -Where the possibility exists that a callee implements CCIP read, a CCIP-aware contract MUST NOT allow the default solidity behaviour of bubbling up reverts from nested calls. This is to prevent the following situation: - - 1. Contract A calls non-CCIP-aware contract B. - 2. Contract B calls back to A. - 3. In the nested call, A reverts with `OffchainLookup`. - 4. Contract B does not understand CCIP read and propagates the `OffchainLookup` to its caller. - 5. Contract A also propagates the `OffchainLookup` to its caller. - -The result of this sequence of operations would be an `OffchainLookup` that looks valid to the client, as the `sender` field matches the address of the contract that was called, but does not execute correctly, as it only completes a nested invocation. - -#### Example - -The code below demonstrates one way that a contract may support nested CCIP read invocations. For simplicity this is shown using Solidity's try/catch syntax, although as of this writing it does not yet support catching custom errors. - -```solidity -contract NestedLookup { - error InvalidOperation(); - error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData); - - function a(bytes calldata data) external view returns(bytes memory) { - try target.b(data) returns (bytes memory ret) { - return ret; - } catch OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData) { - if(sender != address(target)) { - revert InvalidOperation(); - } - revert OffchainLookup( - address(this), - urls, - callData, - NestedLookup.aCallback.selector, - abi.encode(address(target), callbackFunction, extraData) - ); - } - } - - function aCallback(bytes calldata response, bytes calldata extraData) external view returns(bytes memory) { - (address inner, bytes4 innerCallbackFunction, bytes memory innerExtraData) = abi.decode(extraData, (address, bytes4, bytes)); - return abi.decode(inner.call(abi.encodeWithSelector(innerCallbackFunction, response, innerExtraData)), (bytes)); - } -} -``` - -### Gateway Interface -The URLs returned by a contract may be of any schema, but this specification only defines how clients should handle HTTPS URLs. - -Given a URL template returned in an `OffchainLookup`, the URL to query is composed by replacing `sender` with the lowercase 0x-prefixed hexadecimal formatted `sender` parameter, and replacing `data` with the the 0x-prefixed hexadecimal formatted `callData` parameter. - -For example, if a contract returns the following data in an `OffchainLookup`: - -``` -urls = ["https://example.com/gateway/{sender}/{data}.json"] -sender = "0xaabbccddeeaabbccddeeaabbccddeeaabbccddee" -callData = "0x00112233" -``` - -The request URL to query is `https://example.com/gateway/0xaabbccddeeaabbccddeeaabbccddeeaabbccddee/0x00112233.json`. - -If the URL template contains the `{data}` substitution parameter, the client MUST send a GET request after replacing the substitution parameters as described above. - -If the URL template does not contain the `{data}` substitution parameter, the client MUST send a POST request after replacing the substitution parameters as described above. The POST request MUST be sent with a Content-Type of `application/json`, and a payload matching the following schema: - -``` -{ - "type": "object", - "properties": { - "data": { - "type": "string", - "description": "0x-prefixed hex string containing the `callData` from the contract" - }, - "sender": { - "type": "string", - "description": "0x-prefixed hex string containing the `sender` parameter from the contract" - } - } -} -``` - -Compliant gateways MUST respond with a Content-Type of `application/json`, with the body adhering to the following JSON schema: -``` -{ - "type": "object", - "properties": { - "data": { - "type": "string", - "description: "0x-prefixed hex string containing the result data." - } - } -} -``` - -Unsuccessful requests MUST return the appropriate HTTP status code - for example, 404 if the `sender` address is not supported by this gateway, 400 if the `callData` is in an invalid format, 500 if the server encountered an internal error, and so forth. If the Content-Type of a 4xx or 5xx response is `application/json`, it MUST adhere to the following JSON schema: -``` -{ - "type": "object", - "properties": { - "message": { - "type": "string", - "description: "A human-readable error message." - } - } -} -``` - -#### Examples - -***GET request*** - -``` -# Client returned a URL template `https://example.com/gateway/{sender}/{data}.json` -# Request -curl -D - https://example.com/gateway/0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8/0xd5fa2b00.json - -# Successful result - HTTP/2 200 - content-type: application/json; charset=UTF-8 - ... - - {"data": "0xdeadbeefdecafbad"} - -# Error result - HTTP/2 404 - content-type: application/json; charset=UTF-8 - ... - - {"message": "Gateway address not supported."} -} -``` - -***POST request*** - -``` -# Client returned a URL template `https://example.com/gateway/{sender}.json` -# Request -curl -D - -X POST -H "Content-Type: application/json" --data '{"data":"0xd5fa2b00","sender":"0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8"}' https://example.com/gateway/0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8.json - -# Successful result - HTTP/2 200 - content-type: application/json; charset=UTF-8 - ... - - {"data": "0xdeadbeefdecafbad"} - -# Error result - HTTP/2 404 - content-type: application/json; charset=UTF-8 - ... - - {"message": "Gateway address not supported."} -} -``` - -Clients MUST support both GET and POST requests. Gateways may implement either or both as needed. - -### Client Lookup Protocol - -A client that supports CCIP read MUST make contract calls using the following process: - - 1. Set `data` to the call data to supply to the contract, and `to` to the address of the contract to call. - 2. Call the contract at address `to` function normally, supplying `data` as the input data. If the function returns a successful result, return it to the caller and stop. - 3. If the function returns an error other than `OffchainLookup`, return it to the caller in the usual fashion. - 4. Otherwise, decode the `sender`, `urls`, `callData`, `callbackFunction` and `extraData` arguments from the `OffchainLookup` error. - 5. If the `sender` field does not match the address of the contract that was called, return an error to the caller and stop. - 6. Construct a request URL by replacing `sender` with the lowercase 0x-prefixed hexadecimal formatted `sender` parameter, and replacing `data` with the the 0x-prefixed hexadecimal formatted `callData` parameter. The client may choose which URLs to try in which order, but SHOULD prioritise URLs earlier in the list over those later in the list. - 7. Make an HTTP GET request to the request URL. - 8. If the response code from step (5) is in the range 400-499, return an error to the caller and stop. - 9. If the response code from step (5) is in the range 500-599, go back to step (5) and pick a different URL, or stop if there are no further URLs to try. - 10. Otherwise, replace `data` with an ABI-encoded call to the contract function specified by the 4-byte selector `callbackFunction`, supplying the data returned from step (7) and `extraData` from step (4), and return to step (1). - -Clients MUST handle HTTP status codes appropriately, employing best practices for error reporting and retries. - -Clients MUST handle HTTP 4xx and 5xx error responses that have a content type other than application/json appropriately; they MUST NOT attempt to parse the response body as JSON. - -This protocol can result in multiple lookups being requested by the same contract. Clients MUST implement a limit on the number of lookups they permit for a single contract call, and this limit SHOULD be at least 4. - -The lookup protocol for a client is described with the following pseudocode: - -```javascript -async function httpcall(urls, to, callData) { - const args = {sender: to.toLowerCase(), data: callData.toLowerCase()}; - for(const url of urls) { - const queryUrl = url.replace(/\{([^}]*)\}/g, (match, p1) => args[p1]); - // First argument is URL to fetch, second is optional data for a POST request. - const response = await fetch(queryUrl, url.includes('{data}') ? undefined : args); - const result = await response.text(); - if(result.statusCode >= 400 && result.statusCode <= 499) { - throw new Error(data.error.message); - } - if(result.statusCode >= 200 && result.statusCode <= 299) { - return result; - } - } -} -async function durin_call(provider, to, data) { - for(let i = 0; i < 4; i++) { - try { - return await provider.call(to, data); - } catch(error) { - if(error.code !== "CALL_EXCEPTION") { - throw(error); - } - const {sender, urls, callData, callbackFunction, extraData} = error.data; - if(sender !== to) { - throw new Error("Cannot handle OffchainLookup raised inside nested call"); - } - const result = httpcall(urls, to, callData); - data = abi.encodeWithSelector(callbackFunction, result, extraData); - } - } - throw new Error("Too many CCIP read redirects"); -} -``` - -Where: - - `provider` is a provider object that facilitates Ethereum blockchain function calls. - - `to` is the address of the contract to call. - - `data` is the call data for the contract. - -If the function being called is a standard contract function, the process terminates after the original call, returning the same result as for a regular call. Otherwise, a gateway from `urls` is called with the `callData` returned by the `OffchainLookup` error, and is expected to return a valid response. The response and the `extraData` are then passed to the specified callback function. This process can be repeated if the callback function returns another `OffchainLookup` error. - -### Use of CCIP read for transactions -While the specification above is for read-only contract calls (eg, `eth_call`), it is simple to use this method for sending transactions (eg, `eth_sendTransaction` or `eth_sendRawTransaction`) that require offchain data. While 'preflighting' a transaction using `eth_estimateGas` or `eth_call`, a client that receives an `OffchainLookup` revert can follow the procedure described above in [Client lookup protocol](#client-lookup-protocol), substituting a transaction for the call in the last step. This functionality is ideal for applications such as making onchain claims supported by offchain proof data. - -### Glossary - - Client: A process, such as JavaScript executing in a web browser, or a backend service, that wishes to query a blockchain for data. The client understands how to fetch data using CCIP read. - - Contract: A smart contract existing on Ethereum or another blockchain. - - Gateway: A service that answers application-specific CCIP read queries, usually over HTTPS. - -## Rationale -### Use of `revert` to convey call information -For offchain data lookup to function as desired, clients must either have some way to know that a function depends on this specification for functionality - such as a specifier in the ABI for the function - or else there must be a way for the contract to signal to the client that data needs to be fetched from elsewhere. - -While specifying the call type in the ABI is a possible solution, this makes retrofitting existing interfaces to support offchain data awkward, and either results in contracts with the same name and arguments as the original specification, but with different return data - which will cause decoding errors for clients that do not expect this - or duplicating every function that needs support for offchain data with a different name (eg, `balanceOf -> offchainBalanceOf`). Neither solutions is particularly satisfactory. - -Using a revert, and conveying the required information in the revert data, allows any function to be retrofitted to support lookups via CCIP read so long as the client understands the specification, and so facilitates translation of existing specifications to use offchain data. - -### Passing contract address to the gateway service -`address` is passed to the gateway in order to facilitate the writing of generic gateways, thus reducing the burden on contract authors to provide their own gateway implementations. Supplying `address` allows the gateway to perform lookups to the original contract for information needed to assist with resolution, making it possible to operate one gateway for any number of contracts implementing the same interface. - -### Existence of `extraData` argument -`extraData` allows the original contract function to pass information to a subsequent invocation. Since contracts are not persistent, without this data a contract has no state from the previous invocation. Aside from allowing arbitrary contextual information to be propagated between the two calls, this also allows the contract to verify that the query the gateway answered is in fact the one the contract originally requested. - -### Use of GET and POST requests for the gateway interface -Using a GET request, with query data encoded in the URL, minimises complexity and enables entirely static implementations of gateways - in some applications a gateway can simply be an HTTP server or IPFS instance with a static set of responses in text files. - -However, URLs are limited to 2 kilobytes in size, which will impose issues for more complex uses of CCIP read. Thus, we provide for an option to use POST data. This is made at the contract's discretion (via the choice of URL template) in order to preserve the ability to have a static gateway operating exclusively using GET when desired. - -## Backwards Compatibility -Existing contracts that do not wish to use this specification are unaffected. Clients can add support for CCIP read to all contract calls without introducing any new overhead or incompatibilities. - -Contracts that require CCIP read will not function in conjunction with clients that do not implement this specification. Attempts to call these contracts from non-compliant clients will result in the contract throwing an exception that is propagaged to the user. - -## Security Considerations - -### Gateway Response Data Validation -In order to prevent a malicious gateway from causing unintended side-effects or faulty results, contracts MUST include sufficient information in the `extraData` argument to allow them to verify the relevance and validity of the gateway's response. For example, if the contract is requesting information based on an `address` supplied to the original call, it MUST include that address in the `extraData` so that the callback can verify the gateway is not providing the answer to a different query. - -Contracts must also implement sufficient validation of the data returned by the gateway to ensure it is valid. The validation required is application-specific and cannot be specified on a global basis. Examples would include verifying a Merkle proof of inclusion for an L2 or other Merkleized state, or verifying a signature by a trusted signer over the response data. - -### Client Extra Data Validation -In order to prevent a malicious client from causing unintended effects when making transactions using CCIP read, contracts MUST implement appropriate checks on the `extraData` returned to them in the callback. Any sanity/permission checks performed on input data for the initial call MUST be repeated on the data passed through the `extraData` field in the callback. For example, if a transaction should only be executable by an authorised account, that authorisation check MUST be done in the callback; it is not sufficient to perform it with the initial call and embed the authorised address in the `extraData`. - -### HTTP requests and fingerprinting attacks -Because CCIP read can cause a user's browser to make HTTP requests to an address controlled by the contract, there is the potential for this to be used to identify users - for example, to associate their wallet address with their IP address. - -The impact of this is application-specific; fingerprinting a user when they resolve an ENS domain may have little privacy impact, as the attacker will not learn the user's wallet address, only the fact that the user is resolving a given ENS name from a given IP address - information they can also learn from running a DNS server. On the other hand, fingerprinting a user when they attempt a transaction to transfer an NFT may give an attacker everything they need to identify the IP address of a user's wallet. - -To minimise the security impact of this, we make the following recommendations: - - 1. Client libraries should provide clients with a hook to override CCIP read calls - either by rewriting them to use a proxy service, or by denying them entirely. This mechanism or another should be written so as to easily facilitate adding domains to allowlists or blocklists. - 2. Client libraries should disable CCIP read for transactions (but not for calls) by default, and require the caller to explicitly enable this functionality. Enablement should be possible both on a per-contract, per-domain, or global basis. - 3. App authors should not supply a 'from' address for contract calls ('view' operations) where the call could execute untrusted code (that is, code not authored or trusted by the application author). As a precuationary principle it is safest to not supply this parameter at all unless the author is certain that no attacker-determined smart contract code will be executed. - 4. Wallet authors that are responsible for fetching user information - for example, by querying token contracts - should either ensure CCIP read is disabled for transactions, and that no contract calls are made with a 'from' address supplied, or operate a proxy on their users' behalf, rewriting all CCIP read calls to take place via the proxy, or both. - -We encourage client library authors and wallet authors not to disable CCIP read by default, as many applications can be transparently enhanced with this functionality, which is quite safe if the above precautions are observed. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3668.md diff --git a/EIPS/eip-3670.md b/EIPS/eip-3670.md index 469450dc38183a..23c2a4f3ab0f36 100644 --- a/EIPS/eip-3670.md +++ b/EIPS/eip-3670.md @@ -25,9 +25,7 @@ validity into consensus, so that it becomes easier to reason about bytecode. Moreover, EVM implementations may require fewer paths to decide which instruction is valid in the current execution context. -If it will be desired to introduce new instructions without bumping EOF version, having undefined -instructions already deployed would mean such contracts potentially can be broken (since some -instructions are changing their behaviour). Rejecting to deploy undefined instructions allows +If there's a desire to introduce new instructions without bumping the EOF version, having undefined instructions already deployed could potentially break such contracts, as some instructions might change their behavior. Rejecting to deploy undefined instructions allows introducing new instructions with or without bumping the EOF version. ### EOF1 forward compatibility @@ -40,12 +38,10 @@ The EOF1 format provides following forward compatibility properties: ## Specification -*Remark:* We rely on the notation of *initcode*, *code* and *creation* as defined by [EIP-3540](./eip-3540.md). +This feature is introduced on the same block EIP-3540 is enabled, therefore every EOF1-compatible bytecode MUST be validated according to these rules. -This feature is introduced on the very same block EIP-3540 is enabled, therefore every EOF1-compatible bytecode MUST be validated according to these rules. - -1. Previously deprecated instructions `CALLCODE` (0xf2) and `SELFDESTRUCT` (0xff) are invalid and their opcodes are undefined. -2. At contract creation time *instructions validation* is performed on both *initcode* and *code*. The code is invalid if any of the checks below fails. For each instruction: +1. Previously deprecated instructions `CALLCODE` (0xf2) and `SELFDESTRUCT` (0xff), as well as instructions deprecated in EIP-3540, are invalid and their opcodes are undefined. (**NOTE** there are more instructions deprecated and rejected in EOF, as specced out by separate EIPs) +2. At contract creation time *code validation* is performed on each code section of the EOF container. The code is invalid if any of the checks below fails. For each instruction: 1. Check if the opcode is defined. The `INVALID` (0xfe) is considered defined. 2. Check if all instructions' immediate bytes are present in the code (code does not end in the middle of instruction). @@ -67,45 +63,45 @@ This change poses no risk to backwards compatibility, as it is introduced at the ### Contract creation -Each case should be tested for creation transaction, `CREATE` and `CREATE2`. - -- Invalid initcode -- Valid initcode returning invalid code -- Valid initcode returning valid code +Each case should be tested by submitting an EOF container to EOF contract creation (as specced out in a separate EIP). Each case should be tested with code placed in code sections at different indices. ### Valid codes - EOF code containing `INVALID` - EOF code with data section containing bytes that are undefined instructions -- Legacy code containing undefined instruction -- Legacy code ending with incomplete PUSH instruction ### Invalid codes -- EOF code containing undefined instruction +- EOF code containing an undefined instruction - EOF code ending with incomplete `PUSH` instruction - - This can include `PUSH` instruction unreachable by execution, e.g. after `STOP` ## Reference Implementation ```python -# The ranges below are as specified in the Yellow Paper. +# The ranges below are as specified by Execution Specs for Shanghai. # Note: range(s, e) excludes e, hence the +1 -valid_opcodes = [ +shanghai_opcodes = [ *range(0x00, 0x0b + 1), *range(0x10, 0x1d + 1), 0x20, *range(0x30, 0x3f + 1), *range(0x40, 0x48 + 1), *range(0x50, 0x5b + 1), + 0x5f, *range(0x60, 0x6f + 1), *range(0x70, 0x7f + 1), *range(0x80, 0x8f + 1), *range(0x90, 0x9f + 1), *range(0xa0, 0xa4 + 1), # Note: 0xfe is considered assigned. - 0xf0, 0xf1, 0xf3, 0xf4, 0xf5, 0xfa, 0xfd, 0xfe + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xfa, 0xfd, 0xfe, 0xff +] + +# Drop the opcodes deprecated and rejected in here and in EIP-3540 +rejected_in_eof = [ + 0x38, 0x39, 0x3b, 0x3c, 0x3f, 0x5a, 0xf1, 0xf2, 0xf4, 0xfa, 0xff ] +valid_opcodes = [op for op in shanghai_opcodes not in rejected_in_eof] immediate_sizes = 256 * [0] immediate_sizes[0x60:0x7f + 1] = range(1, 32 + 1) # PUSH1..PUSH32 diff --git a/EIPS/eip-3690.md b/EIPS/eip-3690.md index 99aee94a9d4c21..40ebc7b8858fe4 100644 --- a/EIPS/eip-3690.md +++ b/EIPS/eip-3690.md @@ -51,7 +51,7 @@ This feature is introduced on the very same block [EIP-3540](./eip-3540.md) is e ### Validation rules -> This section extends contact creation validation rules (as defined in EIP-3540). +> This section extends contract creation validation rules (as defined in EIP-3540). 4. The `jumpdests` section MUST be present if and only if the `code` section contains `JUMP` or `JUMPI` opcodes. 5. If the `jumpdests` section is present it MUST directly precede the `code` section. In this case a valid EOF bytecode will have the form of `format, magic, version, [jumpdests_section_header], code_section_header, [data_section_header], 0, [jumpdests_section_contents], code_section_contents, [data_section_contents]`. diff --git a/EIPS/eip-3722.md b/EIPS/eip-3722.md index 1b17795bc5269e..37c188bc0c1475 100644 --- a/EIPS/eip-3722.md +++ b/EIPS/eip-3722.md @@ -1,197 +1,7 @@ --- eip: 3722 -title: Poster -description: A ridiculously simple general purpose social media smart contract. -author: Auryn Macmillan (@auryn-macmillan) -discussions-to: https://ethereum-magicians.org/t/eip-poster-a-ridiculously-simple-general-purpose-social-media-smart-contract/6751 -status: Stagnant -type: Standards Track category: ERC -created: 2021-07-31 +status: Moved --- -# Poster - -## Abstract -A ridiculously simple general purpose social media smart contract. -It takes two strings (`content` and `tag`) as parameters and emits those strings, along with msg.sender, as an event. That's it. -The EIP also includes a proposed standard json format for a Twitter-like application, where each `post()` call can include multiple posts and/or operations. The assumption being that application state will be constructed off-chain via some indexer. - -## Motivation -Poster is intended to be used as a base layer for decentralized social media. It can be deployed to the same address (via the singleton factory) on just about any EVM compatible network. Any Ethereum account can make posts to the deployment of Poster on its local network. - -## Specification - -### Contract - -```solidity -contract Poster { - - event NewPost(address indexed user, string content, string indexed tag); - - function post(string calldata content, string calldata tag) public { - emit NewPost(msg.sender, content, tag); - } -} -``` - -### ABI -```json -[ - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "user", - "type": "address" - }, - { - "indexed": false, - "internalType": "string", - "name": "content", - "type": "string" - }, - { - "indexed": true, - "internalType": "string", - "name": "tag", - "type": "string" - } - ], - "name": "NewPost", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "content", - "type": "string" - }, - { - "internalType": "string", - "name": "tag", - "type": "string" - } - ], - "name": "post", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] -``` - -### Standard json format for Twitter-like posts - -```json -{ - "content": [ - { - "type": "microblog", - "text": "this is the first post in a thread" - }, - { - "type": "microblog", - "text": "this is the second post in a thread", - "replyTo": "this[0]" - }, - { - "type": "microblog", - "text": "this is a reply to some other post", - "replyTo": "some_post_id" - }, - { - "type": "microblog", - "text": "this is a post with an image", - "image": "ipfs://ipfs_hash" - }, - { - "type": "microblog", - "text": "this post replaces a previously posted post", - "edit": "some_post_id" - }, - { - "type": "delete", - "target": "some_post_id" - }, - { - "type": "like", - "target": "some_post_id" - }, - { - "type": "repost", - "target": "some_post_id" - }, - { - "type": "follow", - "target": "some_account" - }, - { - "type": "unfollow", - "target": "some_account" - }, - { - "type": "block", - "target": "some_account" - }, - { - "type": "report", - "target": "some_account or some_post_id" - }, - { - "type": "permissions", - "account": "", - "permissions": { - "post": true, - "delete": true, - "like": true, - "follow": true, - "block": true, - "report": true, - "permissions": true - } - }, - { - "type": "microblog", - "text": "This is a post from an account with permissions to post on behalf of another account.", - "from": "" - } - ] -} - -``` - -## Rationale -There was some discussion around whether or not an post ID should also be emitted, whether the content should be a string or bytes, and whether or not anything at all should actually be emitted. - -We decided not to emit an ID, since it meant adding state or complexity to the contract and there is a fairly common pattern of assigning IDs on the indexer layer based on transactionHash + logIndex. - -We decided to emit a string, rather than bytes, simply because that would make content human readable on many existing interfaces, like Etherscan for example. This did, unfortunately, eliminate some of the benefit that we might have gotten from a more compact encoding scheme like CBOR, rather than JSON. But this also would not have satisfied the human readable criteria. - -While there would have been some gas savings if we decided against emitting anything at all, it would have redically increased the node requirements to index posts. As such, we decided it was worth the extra gas to actually emit the content. - -## Reference Implementation - -Poster has been deployed at `0x000000000000cd17345801aa8147b8D3950260FF` on multiple networks using the [Singleton Factory](https://eips.ethereum.org/EIPS/eip-2470). If it is not yet deployed on your chosen network, you can use the Singleton Factory to deploy an instance of Poster at the same address on just about any EVM compatible network using these parameters: - -> **initCode:** `0x608060405234801561001057600080fd5b506101f6806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80630ae1b13d14610030575b600080fd5b61004361003e3660046100fa565b610045565b005b8181604051610055929190610163565b60405180910390203373ffffffffffffffffffffffffffffffffffffffff167f6c7f3182d7e4cb876251f9ae1489975fdbbf15d9f35d393f2ac9b1ff57cec69f86866040516100a5929190610173565b60405180910390a350505050565b60008083601f8401126100c4578182fd5b50813567ffffffffffffffff8111156100db578182fd5b6020830191508360208285010111156100f357600080fd5b9250929050565b6000806000806040858703121561010f578384fd5b843567ffffffffffffffff80821115610126578586fd5b610132888389016100b3565b9096509450602087013591508082111561014a578384fd5b50610157878288016100b3565b95989497509550505050565b6000828483379101908152919050565b60006020825282602083015282846040840137818301604090810191909152601f9092017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016010191905056fea2646970667358221220ee0377bd266748c5dbaf0a3f15ebd97be153932f2d14d460d9dd4271fee541b564736f6c63430008000033` -> -> **salt:** `0x9245db59943806d06245bc7847b3efb2c899d11b621a0f01bb02fd730e33aed2` - -When verifying on the source code on a block explorer, make sure to set the optimizer to `yes` and the runs to `10000000`. - -The source code is available in the [Poster contract repo](https://github.com/ETHPoster/contract/blob/master/contracts/Poster.sol). - - -## Security Considerations -Given the ridiculously simple implementation of Poster, there does not appear to be any real security concerns at the contract level. - -At the application level, clients should confirm that posts including a `"from"` field that differs from `msg.sender` have been authorized by the `"from"` address via a `"permissions"` post, otherwise they should be considerred invalid or a post from `msg.sender`. - -Clients should also be sure to sanitize post data. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3722.md diff --git a/EIPS/eip-3754.md b/EIPS/eip-3754.md index bc4dcdcf2a1267..c0260b4922d694 100644 --- a/EIPS/eip-3754.md +++ b/EIPS/eip-3754.md @@ -1,74 +1,7 @@ --- eip: 3754 -title: A Vanilla Non-Fungible Token Standard -description: NFTs for representing abstract ownership -author: Simon Tian (@simontianx) -discussions-to: https://github.com/ethereum/EIPs/issues/3753 -status: Stagnant -type: Standards Track category: ERC -created: 2021-08-21 +status: Moved --- -## Abstract -In this standard, a non-fungible token stands as atomic existence and encourages -layers of abstraction built on top of it. Ideal for representing concepts like -rights, a form of abstract ownership. Such right can take the form of NFT options, -oracle membership, virtual coupons, etc., and can then be made liquid because of -this tokenization. - -## Motivation -Non-fungible tokens are popularized by the [ERC-721](./eip-721.md) NFT standard -for representing "ownership over digital or physical assets". Over the course of -development, reputable NFT projects are about crypto-assets, digital collectibles, -etc. The proposed standard aims to single out a special type of NFTs that are -ideal for representing abstract ownership such as rights. Examples include the -right of making a function call to a smart contract, an NFT option that gives -the owner the right, but not obligation, to purchase an ERC-721 NFT, and the prepaid -membership (time-dependent right) of accessing to data feeds provided by oracles -without having to pay the required token fees. An on-chain subscription business -model can then be made available by this standard. The conceptual clarity of an -NFT is hence improved by this standard. - -## Specification -``` -interface IERC3754 { - event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); - event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); - event ApprovalForAll(address indexed owner, address indexed operator, bool approved); - - function balanceOf(address owner) external view returns (uint256); - function ownerOf(uint256 tokenId) external view returns (address); - function approve(address to, uint256 tokenId) external; - function getApproved(uint256 tokenId) external view returns (address); - function setApprovalForAll(address operator, bool approved) external; - function isApprovedForAll(address owner, address operator) external view returns (bool); - function transferFrom(address from, address to, uint256 tokenId) external; - function safeTransferFrom(address from, address to, uint256 tokenId) external; - function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external; -} -``` - -## Rationale -The NFTs defined in the [ERC-721](./eip-721.md) standard are already largely -accepted and known as representing ownership of digital assets, and the NFTs by -this standard aim to be accepted and known as representing abstract ownership. -This is achieved by allowing and encouraging layers of abstract utilities built -on top of them. Ownership of such NFTs is equivalent with having the rights to -perform functions assigned to such tokens. Transfer of such rights is also made -easier because of this tokenization. To further distinguish this standard -from [ERC-721](./eip-721.md), data fields and functions related to `URI` are -excluded. - -## Backwards Compatibility -There is no further backwards compatibility required. - -## Reference Implementation -https://github.com/simontianx/ERC3754 - -## Security Considerations -The security is enhanced from ERC721, given tokens are minted without having to -provide `URI`s. Errors in dealing with `URI`s can be avoided. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3754.md diff --git a/EIPS/eip-3770.md b/EIPS/eip-3770.md index dd7c4b3addfd0f..ab8a0be4e426a3 100644 --- a/EIPS/eip-3770.md +++ b/EIPS/eip-3770.md @@ -1,60 +1,7 @@ --- eip: 3770 -title: Chain-specific addresses -description: A standard for displaying CAIP-10 account identifiers in a human readable format -author: Lukas Schor (@lukasschor), Richard Meissner (@rmeissner), Pedro Gomes (@pedrouid), ligi -discussions-to: https://ethereum-magicians.org/t/chain-specific-addresses/6449 -status: Draft -type: Standards Track category: ERC -created: 2021-08-26 +status: Moved --- -## Abstract -This EIP introduced a new address standard to be adapted by wallets and dApps to display chain-specific addresses by mapping human-readable names to [CAIP-3](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-3.md) blockchain IDs. - -## Motivation -The need for this EIP emerges from the increasing adoption of non-Ethereum Mainnet chains that use the Ethereum Virtual Machine (EVM). In this context, addresses become ambiguous, as the same address may refer to an EOA on chain X or a smart contract on chain Y. This will eventually lead to Ethereum users losing funds due to human error. For example, users sending funds to a smart contract wallet address which was not deployed on a particular chain. - -[CAIP-10](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-10.md) introduces an account identifier that encodes a [CAIP-2](https://github.com/ChainAgnostic/CAIPs/blob/master/CAIPs/caip-2.md) blockchain ID as part of the address. For EVM-based chains, these blockchain IDs are defined in CAIP-3 and leverage [EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) chainIDs. However, CAIP-10 targets developers, not end-users. These account identifiers are not meant to be displayed to users in dApps or wallets, and they were optimized for developer interoperability, rather than human readability. - -To solve the initial problem of user-facing addresses being ambiguous in a multichain context, we need to extend CAIP-10 with a user-facing format of displaying these account identifiers. - -## Specification -This EIP extends CAIP-10 with a standard for mapping EVM-based blockchain IDs (CAIP-3) to a human-readable blockchain short name, as defined in [ethereum-lists/chains](https://github.com/ethereum-lists/chains). - -### Syntax -A chain-specific address is prefixed with a chain shortName, separated with a colon sign (:). - -Chain-specific address = "`shortName`" "`:`" "`address`" -- `shortName` = STRING -- `address` = STRING - -### Semantics -`shortName` is mandatory and MUST be a valid short name from [ethereum-lists/chains](https://github.com/ethereum-lists/chains) - -`address` is mandatory and MUST be a EIP-55 compatible hexadecimal address - -### Examples -![Chain-specific addresses](../assets/eip-3770/examples.png "Examples of chain-specific addresses") - -### Resolution Method -Chain-specific addresses are resolved to CAIP-10 account identifiers using [ethereum-lists/chains](https://github.com/ethereum-lists/chains): - -| EIP-3770 chain-specific address | CAIP-10 account identifier | -| ------------- |:-------------:| -| eth:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe | eip155:1:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe| -| ovm:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe | eip155:10:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe | -| poly:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe | eip155:137:0x0DA0C3e52C977Ed3cBc641fF02DD271c3ED55aFe | - -## Rationale -CAIP-10 account identifiers are not suitable for user-facing addresses that are chain-specific as they are non-human-readable. However, CAIP-10 identifiers are still the preferred option for development purposes, as they are ecosystem-agnostic and work best with chain-splits. As a result, this EIP aims to bridge the benefits of human-readable chain identifiers with the benefits of CAIP-10. - -## Backwards Compatibility -Ethereum addresses without the chain specifier will continue to require additional context to understand which chain the address refers to. - -## Security Considerations -The [ethereum-lists/chains](https://github.com/ethereum-lists/chains) curators must consider how similar looking chain short names can be used to confuse users. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3770.md diff --git a/EIPS/eip-3772.md b/EIPS/eip-3772.md index 566964c6a48291..3692470f74261b 100644 --- a/EIPS/eip-3772.md +++ b/EIPS/eip-3772.md @@ -1,278 +1,7 @@ --- eip: 3772 -title: Compressed Integers -description: Using lossy compression on uint256 to improve gas costs, ideally by a factor up to 4x. -author: Soham Zemse (@zemse) -discussions-to: https://github.com/ethereum/EIPs/issues/3772 -status: Stagnant -type: Standards Track category: ERC -created: 2021-08-27 +status: Moved --- -## Abstract - -This document specifies compression of `uint256` to smaller data structures like `uint64`, `uint96`, `uint128`, for optimizing costs for storage. The smaller data structure (represented as `cintx`) is divided into two parts, in the first one we store `significant` bits and in the other number of left `shift`s needed on the significant bits to decompress. This document also includes two specifications for decompression due to the nature of compression being lossy, i.e. it causes underflow. - -## Motivation - -- Storage is costly, each storage slot costs almost $0.8 to initialize and $0.2 to update (20 gwei, 2000 ETHUSD). -- Usually, we store money amounts in `uint256` which takes up one entire slot. -- If it's DAI value, the range we work with most is 0.001 DAI to 1T DAI (or 1012). If it's ETH value, the range we work with most is 0.000001 ETH to 1B ETH. Similarly, any token of any scale has a reasonable range of 1015 amounts that we care/work with. -- However, uint256 type allows us to represent $10-18 to $1058, and most of it is a waste. In technical terms, we have the probability distribution for values larger than $1015 and smaller than $10-3 as negligible (i.e. P[val > 1015] ≈ 0 and P[val < 10-3] ≈ 0). -- Number of bits required to represent 1015 values = log2(1015) = 50 bits. So just 50 bits (instead of 256) are reasonably enough to represent a practical range of money, causing a very negligible difference. - -## Specification - -In this specification, the structure for representing a compressed value is represented using `cintx`, where x is the number of bits taken by the entire compressed value. On the implementation level, an `uintx` can be used for storing a `cintx` value. - -### Compression - -#### uint256 into cint64 (up to cint120) - -The rightmost, or least significant, 8 bits in `cintx` are reserved for storing the shift and the rest available bits are used to store the significant bits starting from the first `1` bit in `uintx`. - -```solidity -struct cint64 { uint56 significant; uint8 shift; } - -// ... - -struct cint120 { uint112 significant; uint8 shift; } -``` - -#### uint256 into cint128 (up to cint248) - -The rightmost, or least significant, 7 bits in `cintx` are reserved for storing the shift and the rest available bits are used to store the significant bits starting from the first one bit in `uintx`. - -> In the following code example, `uint7` is used just for representation purposes only, but it should be noted that uints in Solidity are in multiples of 8. - -```solidity -struct cint128 { uint121 significant; uint7 shift; } - -// ... - -struct cint248 { uint241 significant; uint7 shift; } -``` - -Examples: - -``` -Example: -uint256 value: 2**100, binary repr: 1000000...(hundred zeros) -cint64 { significant: 10000000...(55 zeros), shift: 00101101 (45 in decimal)} - -Example: -uint256 value: 2**100-1, binary repr: 111111...(hundred ones) -cint64 { significant: 11111111...(56 ones), shift: 00101100 (44 in decimal) } -``` - -### Decompression - -Two decompression methods are defined: a normal `decompress` and a `decompressRoundingUp`. - -```solidity -library CInt64 { - // packs the uint256 amount into a cint64 - function compress(uint256) internal returns (cint64) {} - - // unpacks cint64, by shifting the significant bits left by shift - function decompress(cint64) internal returns (uint256) {} - - // unpacks cint64, by shifting the significant bits left by shift - // and having 1s in the shift bits - function decompressRoundingUp(cint64) internal returns (uint256) {} -} -``` - -#### Normal Decompression - -The `significant` bits in the `cintx` are moved to a `uint256` space and shifted left by `shift`. - -> NOTE: In the following example, cint16 is used for visual demonstration purposes. But it should be noted that it is definitely not safe for storing money amounts because its significant bits capacity is 8, while at least 50 bits are required for storing money amounts. - -``` -Example: -cint16{significant:11010111, shift:00000011} -decompressed uint256: 11010111000 // shifted left by 3 - -Example: -cint64 { significant: 11111111...(56 ones), shift: 00101100 (44 in decimal) } -decompressed uint256: 1111...(56 ones)0000...(44 zeros) -``` - -#### Decompression along with rounding up - -The `significant` bits in the `cintx` are moved to a `uint256` space and shifted left by `shift` and the least significant `shift` bits are `1`s. - -``` -Example: -cint16{significant:11011110, shift:00000011} -decompressed rounded up value: 11011110111 // shifted left by 3 and 1s instead of 0s - -Example: -cint64 { significant: 11111111...(56 ones), shift: 00101100 (44 in decimal) } -decompressed uint256: 1111...(100 ones) -``` - -This specification is to be used by a new smart contract for managing its internal state so that any state mutating calls to it can be cheaper. These compressed values on a smart contract's state are something that should not be exposed to the external world (other smart contracts or clients). A smart contract should expose a decompressed value if needed. - -## Rationale - -- The `significant` bits are stored in the most significant part of `cintx` while `shift` bits in the least significant part, to help prevent obvious dev mistakes. For e.g. a number smaller than 256-1 its compressed `cint64` value would be itself if the arrangement were to be opposite than specified. If a developer forgets to uncompress a value before using it, this case would still pass if the compressed value is the same as decompressed value. -- It should be noted that using `cint64` doesn't render gas savings automatically. The solidity compiler needs to pack more data into the same storage slot. -- Also the packing and unpacking adds some small cost too. -- Though this design can also be seen as a binary floating point representation, however using floating point numbers on EVM is not in the scope of this ERC. The primary goal of floating point numbers is to be able to represent a wider range in an available number of bits, while the goal of compression in this ERC is to keep as much precision as possible. Hence, it specifies for the use of minimum exponent/shift bits (i.e 8 up to `uint120` and 7 up to `uint248`). - -```solidity -// uses 3 slots -struct UserData1 { - uint64 amountCompressed; - bytes32 hash; - address beneficiary; -} - -// uses 2 slots -struct UserData2 { - uint64 amountCompressed; - address beneficiary; - bytes32 hash; -} -``` - -## Backwards Compatibility - -There are no known backward-incompatible issues. - -## Reference Implementation - -On the implementation level `uint64` may be used directly, or with custom types introduced in 0.8.9. - -```soldity -function compress(uint256 full) public pure returns (uint64 cint) { - uint8 bits = mostSignificantBitPosition(full); - if (bits <= 55) { - cint = uint64(full) << 8; - } else { - bits -= 55; - cint = (uint64(full >> bits) << 8) + bits; - } -} - -function decompress(uint64 cint) public pure returns (uint256 full) { - uint8 bits = uint8(cint % (1 << 9)); - full = uint256(cint >> 8) << bits; -} - -function decompressRoundingUp(uint64 cint) public pure returns (uint256 full) { - uint8 bits = uint8(cint % (1 << 9)); - full = uint256(cint >> 8) << bits + ((1 << bits) - 1); -} -``` - -The above gist has `library CInt64` that contains demonstrative logic for compression, decompression, and arithmetic for `cint64`. The gist also has an example contract that uses the library for demonstration purposes. - -The CInt64 format is intended only for storage, while dev should convert it to uint256 form using suitable logic (decompress or decompressRoundingUp) to perform any arithmetic on it. - -## Security Considerations - -The following security considerations are discussed: - -1. Effects due to lossy compression - - Error estimation for `cint64` - - Handling the error -2. Losing precision due to incorrect use of `cintx` -3. Compressing something other than money `uint256`s. - -### 1. Effects due to lossy compression - -When a value is compressed, it causes underflow, i.e. some less significant bits are sacrificed. This results in a `cintx` value whose decompressed value is less than or equal to the actual `uint256` value. - -```solidity -uint a = 2**100 - 1; // 100 # of 1s in binary format -uint c = a.compress().decompress(); - -a > c; // true -a - (2**(100 - 56) - 1) == c; // true - -// Visual example: -// before: 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 -// after: 1111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000 -``` - -#### Error estimation for cint64 - -Let's consider we have a `value` of the order 2m (less than 2m and greater than or equal to 2m-1). - -For all values such that 2m - 1 - (2m-56 - 1) <= `value` <= 2m - 1, the compressed value `cvalue` is 2m - 1 - (2m-56 - 1). - -The maximum error is 2m-56 - 1, approximating it to decimal: 10n-17 (log2(56) is 17). Here `n` is number of decimal digits + 1. - -For e.g. compressing a value of the order $1,000,000,000,000 (or 1T or 1012) to `cint64`, the maximum error turns out to be 1012+1-17 = $10-4 = $0.0001. This means the precision after 4 decimal places is lost, or we can say that the uncompressed value is at maximum $0.0001 smaller. Similarly, if someone is storing $1,000,000 into `cint64`, the uncompressed value would be at maximum $0.0000000001 smaller. In comparison, the storage costs are almost $0.8 to initialize and $0.2 to update (20 gwei, 2000 ETHUSD). - -#### Handling the error - -Note that compression makes the value slightly smaller (underflow). But we also have another operation that also does that. In integer math, the division is a lossy operation (causing underflow). For instance, - -```solidity -10000001 / 2 == 5000000 // true -``` - -The result of the division operation is not always exact, but it's smaller than the actual value, in some cases as in the above example. Though, most engineers try to reduce this effect by doing all the divisions at the end. - -``` -1001 / 2 * 301 == 150500 // true -1001 * 301 / 2 == 150650 // true -``` - -The division operation has been in use in the wild, and plenty of lossy integer divisions have taken place, causing DeFi users to get very very slightly less withdrawal amounts, which they don't even notice. If been careful, then the risk is very negligible. Compression is similar, in the sense that it is also a division by 2shift. If been careful with this too, the effects are minimized. - -In general, one should follow the rule: - -1. When a smart contract has to transfer a compressed amount to a user, they should use a rounded down value (by using `amount.decompress()`). -2. When a smart contract has to transferFrom a compressed amount from a user to itself, i.e charging for some bill, they should use a rounded up value (by using `amount.decompressUp()`). - -The above ensures that smart contract does not loose money due to the compression, it is the user who receives less funds or pays more funds. The extent of rounding is something that is negligible enough for the user. Also just to mention, this rounding up and down pattern is observed in many projects including UniswapV3. - -### 2. Losing precision due to incorrect use of `cintx` - -This is an example where dev errors while using compression can be a problem. - -Usual user amounts mostly have an max entropy of 50, i.e. 1015 (or 250) values in use, that is the reason why we find uint56 enough for storing significant bits. However, let's see an example: - -```solidity -uint64 sharesC = // reading compressed value from storage; -uint64 price = // CALL; -uint64 amountC = sharesC.cmuldiv(price, PRICE_UNIT); -user.transfer(amountC.uncompress()); -``` - -The above code results in a serious precision loss. `sharesC` has an entropy of 50, as well as `priceC` also has an entropy of 50. When we multiply them, we get a value that contains entropies of both, and hence, an entropy of 100. After multiplication is done, `cmul` compresses the value, which drops the entropy of `amountC` to 56 (as we have uint56 there to store significant bits). - -To prevent entropy/precision from dropping, we get out from compression. - -```solidity -uint64 sharesC = shares.compress(); -uint64 priceC = price.compress(); -uint256 amount = sharesC.uncompress() * price / PRICE_UNIT; -user.transfer(amount); -``` - -Compression is only useful when writing to storage while doing arithmetic with them should be done very carefully. - -### 3. Compressing something other than money `uint256`s. - -Compressed Integers is intended to only compress money amount. Technically there are about 1077 values that a `uint256` can store but most of those values have a flat distribution i.e. the probability is 0 or extremely negligible. (What is a probability that a user would be depositing 1000T DAI or 1T ETH to a contract? In normal circumstances it doesn't happen, unless someone has full access to the mint function). Only the amounts that people work with have a non-zero distribution ($0.001 DAI to $1T or 1015 to 1030 in uint256). 50 bits are enough to represent this information, just to round it we use 56 bits for precision. - -Using the same method for compressing something else which have a completely different probability distribution will likely result in a problem. It's best to just not compress if you're not sure about the distribution of values your `uint256` is going to take. And also, for things you think you are sure about using compression for, it's better to give more thought if compression can result in edge cases (e.g. in previous multiplication example). - -### 4. Compressing Stable vs Volatile money amounts - -Since we have a dynamic `uint8 shift` value that can move around. So even if you wanted to represent 1 Million SHIBA INU tokens or 0.0002 WBTC (both $10 as of this writing), cint64 will pick its top 56 significant bits which will take care of the value representation. - -It can be a problem for volatile tokens if the coin is extremely volatile wrt user's native currency. Imagine a very unlikely case where a coin goes 256x up (price went up by 1016 lol). In such cases `uint56` might not be enough as even its least significant bit is very valuable. If such insanely volatile tokens are to be stored, you should store more significant bits, i.e. using `cint96` or `cint128`. - -`cint64` has 56 bits for storing significant, when only 50 were required. Hence there are 6 extra bits, which means that it is fine if the $ value of the cryptocurrency stored in cint64 increases by 26 or 64x. If the value goes down it's not a problem. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-3772.md diff --git a/EIPS/eip-3779.md b/EIPS/eip-3779.md index f8a4e1d754cdc5..e8c02082a69dfe 100644 --- a/EIPS/eip-3779.md +++ b/EIPS/eip-3779.md @@ -42,7 +42,7 @@ The relative jumps of [EIP-4200](./eip-4200) and the simple subroutines of [EIP- > `RJUMPI` _offset_ * Jumps if the top of stack is non-zero. > `RJUMPSUB` offset -* Pushes _IP+1_ on the return stack and jumps to _IP+offest_. +* Pushes _IP+1_ on the return stack and jumps to _IP+offset_. > `RETURNSUB` * Jumps to the address popped off the return stack. diff --git a/EIPS/eip-3788.md b/EIPS/eip-3788.md index 6d27c0d91ff307..b5e343e8d0a90e 100644 --- a/EIPS/eip-3788.md +++ b/EIPS/eip-3788.md @@ -7,7 +7,7 @@ discussions-to: https://ethereum-magicians.org/t/discussion-to-eip-3788-strict-e status: Stagnant type: Standards Track category: Core -created: 2021-09-2 +created: 2021-09-02 requires: 155 --- @@ -18,7 +18,7 @@ Reject transactions that do not explicitly have the same chainId as the node's c ## Motivation Per [EIP-155](./eip-155.md) a transaction with a `chainId = 0` is considered to be a valid -transaction. This was a feature to offer developers the ability to sumbit replayable transactions +transaction. This was a feature to offer developers the ability to submit replayable transactions across different chains. With the rise of evm compatible chains, many of which use forks, or packages from popular Ethereum clients, we are putting user funds at risk. This is because most wallet interfaces do not expose the chainId to the user, meaning they typically do not have insight diff --git a/EIPS/eip-3855.md b/EIPS/eip-3855.md index 9e1e0ab372fcaa..42034250ae8dd4 100644 --- a/EIPS/eip-3855.md +++ b/EIPS/eip-3855.md @@ -4,7 +4,7 @@ title: PUSH0 instruction description: Introduce a new instruction which pushes the constant value 0 onto the stack author: Alex Beregszaszi (@axic), Hugo De la cruz (@hugo-dc), Paweł Bylica (@chfast) discussions-to: https://ethereum-magicians.org/t/eip-3855-push0-instruction/7014 -status: Review +status: Final type: Standards Track category: Core created: 2021-02-19 @@ -29,7 +29,7 @@ The main motivations for this change include: To put the "waste" into perspective, across existing accounts 340,557,331 bytes are wasted on `PUSH1 00` instructions, which means 68,111,466,200 gas was spent to deploy them. In practice a lot of these accounts share identical bytecode with others, so their total stored size in clients is lower, however the deploy time cost must have been paid nevertheless. -An example for 2) is changing the behaviour of `RETURNDATASIZE` such that it may not be guaranteed to be zero at the beginning of the call frame. This was proposed as a way to chain transactions (i.e. EIP-2733). +An example for 2) is changing the behaviour of `RETURNDATASIZE` such that it may not be guaranteed to be zero at the beginning of the call frame. ## Specification diff --git a/EIPS/eip-3860.md b/EIPS/eip-3860.md index 51fb6003054b88..5f8151e19ad1c9 100644 --- a/EIPS/eip-3860.md +++ b/EIPS/eip-3860.md @@ -4,7 +4,7 @@ title: Limit and meter initcode description: Limit the maximum size of initcode to 49152 and apply extra gas cost of 2 for every 32-byte chunk of initcode author: Martin Holst Swende (@holiman), Paweł Bylica (@chfast), Alex Beregszaszi (@axic), Andrei Maiboroda (@gumb0) discussions-to: https://ethereum-magicians.org/t/eip-3860-limit-and-meter-initcode/7018 -status: Review +status: Final type: Standards Track category: Core created: 2021-07-16 @@ -36,7 +36,7 @@ Furthermore, the lack of a limit has caused lengthy discussions for some EVM pro We are motivated by three reasons: 1. Ensuring `initcode` is fairly charged (most importantly cost is proportional to `initcode`'s length) to minimize the risks for the future. -2. To have a cost system which is extendable in the future (i.e. for proposals like [EIP-3670](./eip-3670.md)). +2. To have a cost system which is extendable in the future. 3. To simplify EVM engines by the explicit limits (code size, code offsets (`PC`), and jump offsets fit 16-bits). ## Specification diff --git a/EIPS/eip-4200.md b/EIPS/eip-4200.md index 19497a60abcc80..b452cf8a47e5b5 100644 --- a/EIPS/eip-4200.md +++ b/EIPS/eip-4200.md @@ -37,9 +37,9 @@ The main benefit of these instruction is reduced gas cost (both at deploy and ex We introduce three new instructions on the same block number [EIP-3540](./eip-3540.md) is activated on: -1. `RJUMP` (0x5c) - relative jump -2. `RJUMPI` (0x5d) - conditional relative jump -3. `RJUMPV` (0x5e) - relative jump via jump table +1. `RJUMP` (0xe0) - relative jump +2. `RJUMPI` (0xe1) - conditional relative jump +3. `RJUMPV` (0xe2) - relative jump via jump table If the code is legacy bytecode, all of these instructions result in an *exceptional halt*. (*Note: This means no change to behaviour.*) @@ -47,11 +47,11 @@ If the code is valid EOF1: 1. `RJUMP relative_offset` sets the `PC` to `PC_post_instruction + relative_offset`. 2. `RJUMPI relative_offset` pops a value (`condition`) from the stack, and sets the `PC` to `PC_post_instruction + ((condition == 0) ? 0 : relative_offset)`. -3. `RJUMPV count relative_offset+` pops a value (`case`) from the stack, and sets the `PC` to `PC_post_instruction + ((case >= count) ? 0 : relative_offset[case])`. +3. `RJUMPV max_index relative_offset+` pops a value (`case`) from the stack, and sets the `PC` to `PC_post_instruction + ((case > max_index) ? 0 : relative_offset[case])`. The immediate argument `relative_offset` is encoded as a 16-bit **signed** (two's-complement) big-endian value. Under `PC_post_instruction` we mean the `PC` position after the entire immediate value. -The immediate encoding of `RJUMPV` is more special: the 8-bit `count` value determines the number of `relative_offset` values following. Validation algorithm of [EIP-3670](./eip-3670.md) is extended to verify that `count >= 1`. The encoding of `RJUMPV` must have at least one `relative_offset` and thus it will take at minimum 4 bytes. Furthermore, the `case >= count` condition falling through means that in many use cases one would place the *default* path following the `RJUMPV` instruction. An interesting feature is that `RJUMPV 1 relative_offset` is an inverted-`RJUMPI`, which can be used in many cases instead of `ISZERO RJUMPI relative_offset`. +The immediate encoding of `RJUMPV` is more special: the unsigned 8-bit `max_index` value determines the maximum index in the jump table. The number of `relative_offset` values following is `max_index+1`. This allows table sizes up to 256. The encoding of `RJUMPV` must have at least one `relative_offset` and thus it will take at minimum 4 bytes. Furthermore, the `case > max_index` condition falling through means that in many use cases, one would place the *default* path following the `RJUMPV` instruction. An interesting feature is that `RJUMPV 0 relative_offset` is an inverted-`RJUMPI`, which can be used in many cases instead of `ISZERO RJUMPI relative_offset`. We also extend the validation algorithm of [EIP-3670](./eip-3670.md) to verify that each `RJUMP`/`RJUMPI`/`RJUMPV` has a `relative_offset` pointing to an instruction. This means it cannot point to an immediate data of `PUSHn`/`RJUMP`/`RJUMPI`/`RJUMPV`. It cannot point outside of code bounds. It is allowed to point to a `JUMPDEST`, but is not required to. @@ -126,16 +126,16 @@ This change poses no risk to backwards compatibility, as it is introduced at the - `relative_offset` is positive/negative/`0` - `RJUMP`/`RJUMPI`/`RJUMPV` with instruction other than `JUMPDEST` as target - `relative_offset` is positive/negative/`0` -- `RJUMPV` with various valid table sizes from 1 to 255 +- `RJUMPV` with various valid table sizes from 1 to 256 +- `RJUMP` as a final instruction in code section #### Invalid cases - `RJUMP`/`RJUMPI`/`RJUMPV` with truncated immediate -- `RJUMP`/`RJUMPI`/`RJUMPV` as a final instruction in code section +- `RJUMPI`/`RJUMPV` as a final instruction in code section - `RJUMP`/`RJUMPI`/`RJUMPV` target outside of code section bounds - `RJUMP`/`RJUMPI`/`RJUMPV` target push data - `RJUMP`/`RJUMPI`/`RJUMPV` target another `RJUMP`/`RJUMPI`/`RJUMPV` immediate argument -- `RJUMPV` with table size 0 ### Execution @@ -146,111 +146,15 @@ This change poses no risk to backwards compatibility, as it is introduced at the - `relative_offset` is positive/negative/`0` - `condition` equals `0` - `condition` does not equal `0` -- `RJUMPV 1 relative_offset` +- `RJUMPV 0 relative_offset` - `case` equals `0` - `case` does not equal `0` - `RJUMPV` with table containing positive, negative, `0` offsets - `case` equals `0` - `case` does not equal `0` - - `case` outside of table bounds (`case >= count`, fallback case) + - `case` outside of table bounds (`case > max_index`, fallback case) - `case` > 255 -## Reference Implementation - -```python -# The ranges below are as specified in the Yellow Paper. -# Note: range(s, e) excludes e, hence the +1 -valid_opcodes = [ - *range(0x00, 0x0b + 1), - *range(0x10, 0x1d + 1), - 0x20, - *range(0x30, 0x3f + 1), - *range(0x40, 0x48 + 1), - *range(0x50, 0x5e + 1), - *range(0x60, 0x6f + 1), - *range(0x70, 0x7f + 1), - *range(0x80, 0x8f + 1), - *range(0x90, 0x9f + 1), - *range(0xa0, 0xa4 + 1), - # Note: 0xfe is considered assigned. - *range(0xf0, 0xf5 + 1), 0xfa, 0xfd, 0xfe, 0xff -] - -# STOP, RETURN, REVERT, INVALID, SELFDESTRUCT -terminating_opcodes = [ 0x00, 0xf3, 0xfd, 0xfe, 0xff ] - -immediate_sizes = 256 * [0] -immediate_sizes[0x5c] = 2 # RJUMP -immediate_sizes[0x5d] = 2 # RJUMPI -for opcode in range(0x60, 0x7f + 1): # PUSH1..PUSH32 - immediate_sizes[opcode] = opcode - 0x60 + 1 - -# Raises ValidationException on invalid code -def validate_code(code: bytes): - # Note that EOF1 already asserts this with the code section requirements - assert len(code) > 0 - - opcode = 0 - pos = 0 - rjumpdests = set() - immediates = set() - while pos < len(code): - # Ensure the opcode is valid - opcode = code[pos] - pos += 1 - if not opcode in valid_opcodes: - raise ValidationException("undefined instruction") - - pc_post_instruction = pos + immediate_sizes[opcode] - - if opcode == 0x5c or opcode == 0x5d: - if pos + 2 > len(code): - raise ValidationException("truncated relative jump offset") - offset = int.from_bytes(code[pos:pos+2], byteorder = "big", signed = True) - - rjumpdest = pc_post_instruction + offset - if rjumpdest < 0 or rjumpdest >= len(code): - raise ValidationException("relative jump destination out of bounds") - - rjumpdests.add(rjumpdest) - elif opcode == 0x5e: - if pos + 1 > len(code): - raise ValidationException("truncated jump table") - jump_table_size = code[pos] - if jump_table_size == 0: - raise ValidationException("empty jump table") - - pc_post_instruction = pos + 1 + 2 * jump_table_size - if pc_post_instruction > len(code): - raise ValidationException("truncated jump table") - - for offset_pos in range(pos + 1, pc_post_instruction, 2): - offset = int.from_bytes(code[offset_pos:offset_pos+2], byteorder = "big", signed = True) - - rjumpdest = pc_post_instruction + offset - if rjumpdest < 0 or rjumpdest >= len(code): - raise ValidationException("relative jump destination out of bounds") - rjumpdests.add(rjumpdest) - - - # Save immediate value positions - immediates.update(range(pos, pc_post_instruction)) - # Skip immediates - pos = pc_post_instruction - - # Ensure last opcode's immediate doesn't go over code end - if pos != len(code): - raise ValidationException("truncated immediate") - - # opcode is the *last opcode* - if not opcode in terminating_opcodes: - raise ValidationException("no terminating instruction") - - # Ensure relative jump destinations don't target immediates - if not rjumpdests.isdisjoint(immediates): - raise ValidationException("relative jump destination targets immediate") -``` - ## Security Considerations TBA diff --git a/EIPS/eip-4337.md b/EIPS/eip-4337.md index 0d669ab8e78ede..37b25643cd879b 100644 --- a/EIPS/eip-4337.md +++ b/EIPS/eip-4337.md @@ -1,928 +1,7 @@ --- eip: 4337 -title: Account Abstraction Using Alt Mempool -description: An account abstraction proposal which completely avoids consensus-layer protocol changes, instead relying on higher-layer infrastructure. -author: Vitalik Buterin (@vbuterin), Yoav Weiss (@yoavw), Kristof Gazso (@kristofgazso), Namra Patel (@namrapatel), Dror Tirosh (@drortirosh), Shahaf Nacson (@shahafn), Tjaden Hess (@tjade273) -discussions-to: https://ethereum-magicians.org/t/erc-4337-account-abstraction-via-entry-point-contract-specification/7160 -status: Draft -type: Standards Track category: ERC -created: 2021-09-29 +status: Moved --- -## Abstract - -An account abstraction proposal which completely avoids the need for consensus-layer protocol changes. Instead of adding new protocol features and changing the bottom-layer transaction type, this proposal instead introduces a higher-layer pseudo-transaction object called a `UserOperation`. Users send `UserOperation` objects into a separate mempool. A special class of actor called bundlers (either block builders, or users that can send transactions to block builders through a bundle marketplace) package up a set of these objects into a transaction making a `handleOps` call to a special contract, and that transaction then gets included in a block. - -## Motivation - -See also `https://ethereum-magicians.org/t/implementing-account-abstraction-as-part-of-eth1-x/4020` and the links therein for historical work and motivation, and [EIP-2938](./eip-2938.md) for a consensus layer proposal for implementing the same goal. - -This proposal takes a different approach, avoiding any adjustments to the consensus layer. It seeks to achieve the following goals: - -* **Achieve the key goal of account abstraction**: allow users to use smart contract wallets containing arbitrary verification logic instead of EOAs as their primary account. Completely remove any need at all for users to also have EOAs (as status quo SC wallets and [EIP-3074](./eip-3074.md) both require) -* **Decentralization** - * Allow any bundler (think: block builder) to participate in the process of including account-abstracted user operations - * Work with all activity happening over a public mempool; users do not need to know the direct communication addresses (eg. IP, onion) of any specific actors - * Avoid trust assumptions on bundlers -* **Do not require any Ethereum consensus changes**: Ethereum consensus layer development is focusing on the merge and later on scalability-oriented features, and there may not be any opportunity for further protocol changes for a long time. Hence, to increase the chance of faster adoption, this proposal avoids Ethereum consensus changes. -* **Try to support other use cases** - * Privacy-preserving applications - * Atomic multi-operations (similar goal to [EIP-3074](./eip-3074.md)) - * Pay tx fees with [EIP-20](./eip-20.md) tokens, allow developers to pay fees for their users, and [EIP-3074](./eip-3074.md)-like **sponsored transaction** use cases more generally - * Support aggregated signature (e.g. BLS) - -## Specification - -### Definitions - -* **UserOperation** - a structure that describes a transaction to be sent on behalf of a user. To avoid confusion, it is not named "transaction". - * Like a transaction, it contains "sender", "to", "calldata", "maxFeePerGas", "maxPriorityFee", "signature", "nonce" - * unlike a transaction, it contains several other fields, described below - * also, the "nonce" and "signature" fields usage is not defined by the protocol, but by each account implementation -* **Sender** - the account contract sending a user operation. -* **EntryPoint** - a singleton contract to execute bundles of UserOperations. Bundlers/Clients whitelist the supported entrypoint. -* **Bundler** - a node (block builder) that bundles multiple UserOperations and create an EntryPoint.handleOps() transaction. Note that not all block-builders on the network are required to be bundlers -* **Aggregator** - a helper contract trusted by accounts to validate an aggregated signature. Bundlers/Clients whitelist the supported aggregators. - - -To avoid Ethereum consensus changes, we do not attempt to create new transaction types for account-abstracted transactions. Instead, users package up the action they want their account to take in an ABI-encoded struct called a `UserOperation`: - -| Field | Type | Description -| - | - | - | -| `sender` | `address` | The account making the operation | -| `nonce` | `uint256` | Anti-replay parameter; also used as the salt for first-time account creation | -| `initCode` | `bytes` | The initCode of the account (needed if and only if the account is not yet on-chain and needs to be created) | -| `callData` | `bytes` | The data to pass to the `sender` during the main execution call | -| `callGasLimit` | `uint256` | The amount of gas to allocate the main execution call | -| `verificationGasLimit` | `uint256` | The amount of gas to allocate for the verification step | -| `preVerificationGas` | `uint256` | The amount of gas to pay for to compensate the bundler for pre-verification execution and calldata | -| `maxFeePerGas` | `uint256` | Maximum fee per gas (similar to [EIP-1559](./eip-1559.md) `max_fee_per_gas`) | -| `maxPriorityFeePerGas` | `uint256` | Maximum priority fee per gas (similar to EIP-1559 `max_priority_fee_per_gas`) | -| `paymasterAndData` | `bytes` | Address of paymaster sponsoring the transaction, followed by extra data to send to the paymaster (empty for self-sponsored transaction) | -| `signature` | `bytes` | Data passed into the account along with the nonce during the verification step | - -Users send `UserOperation` objects to a dedicated user operation mempool. A specialized class of actors called **bundlers** (either block builders running special-purpose code, or users that can relay transactions to block builders eg. through a bundle marketplace such as Flashbots that can guarantee next-block-or-never inclusion) listen in on the user operation mempool, and create **bundle transactions**. A bundle transaction packages up multiple `UserOperation` objects into a single `handleOps` call to a pre-published global **entry point contract**. - -To prevent replay attacks (both cross-chain and multiple `EntryPoint` implementations), the `signature` should depend on `chainid` and the `EntryPoint` address. - -The core interface of the entry point contract is as follows: - -```solidity -function handleOps(UserOperation[] calldata ops, address payable beneficiary); - -function handleAggregatedOps( - UserOpsPerAggregator[] calldata opsPerAggregator, - address payable beneficiary -); - - -struct UserOpsPerAggregator { - UserOperation[] userOps; - IAggregator aggregator; - bytes signature; -} -function simulateValidation(UserOperation calldata userOp); - -error ValidationResult(ReturnInfo returnInfo, - StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo); - -error ValidationResultWithAggregation(ReturnInfo returnInfo, - StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo, - AggregatorStakeInfo aggregatorInfo); - -struct ReturnInfo { - uint256 preOpGas; - uint256 prefund; - bool sigFailed; - uint64 validAfter; - uint64 validUntil; - bytes paymasterContext; -} - -struct StakeInfo { - uint256 stake; - uint256 unstakeDelaySec; -} - -struct AggregatorStakeInfo { - address actualAggregator; - StakeInfo stakeInfo; -} -``` - -The core interface required for an account to have is: - -```solidity -interface IAccount { - function validateUserOp - (UserOperation calldata userOp, bytes32 userOpHash, address aggregator, uint256 missingAccountFunds) - external returns (uint256 sigTimeRange); -} -``` - -The account - -* MUST validate the caller is a trusted EntryPoint -* The userOpHash is a hash over the userOp (except signature), entryPoint and chainId -* If the account does not support signature aggregation, it MUST validate the signature is a valid signature of the `userOpHash`, and - SHOULD return SIG_VALIDATION_FAILED (and not revert) on signature mismatch. Any other error should revert. -* MUST pay the entryPoint (caller) at least the "missingAccountFunds" (which might be zero, in case current account's deposit is high enough) -* The account MAY pay more than this minimum, to cover future transactions (it can always issue `withdrawTo` to retrieve it) -* The `aggregator` SHOULD be ignored for accounts that don't use an aggregator -* The return value is packed of sigFailure, validUntil and validAfter timestamps. - * `sigFailure` is 1 byte value of "1" the signature check failed (should not revert on signature failure, to support estimate) - * `validUntil` is 8-byte timestamp value, or zero for "infinite". The UserOp is valid only up to this time. - * `validAfter` is 8-byte timestamp. The UserOp is valid only after this time. - -An account that works with aggregated signature should have the interface: - -```solidity -interface IAggregatedAccount is IAccount { - - function getAggregator() view returns (address); -} -``` - -* **getAggregator()** returns the aggregator this account supports. -* **validateUserOp()** (inherited from IAccount interface) MUST verify the `aggregator` parameter is valid and the same as `getAggregator` -* The account should also support aggregator-specific getter (e.g. `getAggregationInfo()`). - This method should export the account's public-key to the aggregator, and possibly more info - (note that it is not called directly by the entryPoint) -* validateUserOp MAY ignore the signature field - -The core interface required by an aggregator is: - -```solidity -interface IAggregator { - - function validateUserOpSignature(UserOperation calldata userOp) - external view returns (bytes memory sigForUserOp); - - function aggregateSignatures(UserOperation[] calldata userOps) external view returns (bytes memory aggregatesSignature); - - function validateSignatures(UserOperation[] calldata userOps, bytes calldata signature) view external; -} -``` - -* If an account uses an aggregator (returns it with getAggregator()), then its address is returned by `simulateValidation()` reverting with `ValidationResultWithAggregator` instead of `ValidationResult` -* To accept the UserOp, the bundler must call **validateUserOpSignature()** to validate the userOp's signature. -* **aggregateSignatures()** must aggregate all UserOp signature into a single value. -* Note that the above methods are helper method for the bundler. The bundler MAY use a native library to perform the same validation and aggregation logic. -* **validateSignatures()** MUST validate the aggregated signature matches for all UserOperations in the array, and revert otherwise. - This method is called on-chain by `handleOps()` - -#### Using signature aggregators - -An account signify it uses signature aggregation by exposing the aggregator's address in the `getAggregator()` method. -During `simulateValidation`, this aggregator is returned (in the `ValidationResultWithAggregator`) - -The bundler should first accept the aggregator (validate its stake info and that it is not throttled/banned) -Then it MUST verify the userOp using `aggregator.validateUserOpSignature()` - -Signature aggregator SHOULD stake just like a paymaster, unless it is exempt due to not accessing global storage - see [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) for details. Bundlers MAY throttle down and ban aggregators in case they take too much -resources (or revert) when the above methods are called in view mode, or if the signature aggregation fails. - -### Required entry point contract functionality - -There are 2 separate entry point methods: `handleOps` and `handleAggregatedOps` - -* `handleOps` handle userOps of accounts that don't require any signature aggregator. -* `handleAggregatedOps` can handle a batch that contains userOps of multiple aggregators (and also requests without any aggregator) -* `handleAggregatedOps` performs the same logic below as `handleOps`, but it must transfer the correct aggregator to each userOp, and also must call `validateSignatures` on each aggregator after doing all the per-account validation. -The entry point's `handleOps` function must perform the following steps (we first describe the simpler non-paymaster case). It must make two loops, the **verification loop** and the **execution loop**. In the verification loop, the `handleOps` call must perform the following steps for each `UserOperation`: - -* **Create the account if it does not yet exist**, using the initcode provided in the `UserOperation`. If the account does not exist, _and_ the initcode is empty, or does not deploy a contract at the "sender" address, the call must fail. -* **Call `validateUserOp` on the account**, passing in the `UserOperation`, the required fee and aggregator (if there is one). The account should verify the operation's signature, and pay the fee if the account considers the operation valid. If any `validateUserOp` call fails, `handleOps` must skip execution of at least that operation, and may revert entirely. -* Validate the account's deposit in the entryPoint is high enough to cover the max possible cost (cover the already-done verification and max execution gas) - -In the execution loop, the `handleOps` call must perform the following steps for each `UserOperation`: - -* **Call the account with the `UserOperation`'s calldata**. It's up to the account to choose how to parse the calldata; an expected workflow is for the account to have an `execute` function that parses the remaining calldata as a series of one or more calls that the account should make. - -![](../assets/eip-4337/image1.png) - -Before accepting a `UserOperation`, bundlers should use an RPC method to locally call the `simulateValidation` function of the entry point, to verify that the signature is correct and the operation actually pays fees; see the [Simulation section below](#simulation) for details. -A node/bundler SHOULD drop (not add to the mempool) a `UserOperation` that fails the validation - -### Extension: paymasters - -We extend the entry point logic to support **paymasters** that can sponsor transactions for other users. This feature can be used to allow application developers to subsidize fees for their users, allow users to pay fees with [EIP-20](./eip-20.md) tokens and many other use cases. When the paymaster is not equal to the zero address, the entry point implements a different flow: - -![](../assets/eip-4337/image2.png) - -During the verification loop, in addition to calling `validateUserOp`, the `handleOps` execution also must check that the paymaster has enough ETH deposited with the entry point to pay for the operation, and then call `validatePaymasterUserOp` on the paymaster to verify that the paymaster is willing to pay for the operation. Note that in this case, the `validateUserOp` is called with a `missingAccountFunds` of 0 to reflect that the account's deposit is not used for payment for this userOp. - -If the paymaster's validatePaymasterUserOp returns a "context", then `handleOps` must call `postOp` on the paymaster after making the main execution call. It must guarantee the execution of `postOp`, by making the main execution inside an inner call context, and if the inner call context reverts attempting to call `postOp` again in an outer call context. - -Maliciously crafted paymasters _can_ DoS the system. To prevent this, we use a reputation system. paymaster must either limit its storage usage, or have a stake. see the [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) for details. - -The paymaster interface is as follows: - -```c++ - function validatePaymasterUserOp - (UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost) - external returns (bytes memory context, uint256 sigTimeRange); - -function postOp - (PostOpMode mode, bytes calldata context, uint256 actualGasCost) - external; - -enum PostOpMode { - opSucceeded, // user op succeeded - opReverted, // user op reverted. still has to pay for gas. - postOpReverted // user op succeeded, but caused postOp to revert -} -``` - - -```c++ -// add a paymaster stake (must be called by the paymaster) -function addStake(uint32 _unstakeDelaySec) external payable - -// unlock the stake (must wait unstakeDelay before can withdraw) -function unlockStake() external - -// withdraw the unlocked stake -function withdrawStake(address payable withdrawAddress) external -``` - -The paymaster must also have a deposit, which the entry point will charge UserOperation costs from. -The deposit (for paying gas fees) is separate from the stake (which is locked). - -The entry point must implement the following interface to allow paymasters (and optionally accounts) manage their deposit: - -```c++ -// return the deposit of an account -function balanceOf(address account) public view returns (uint256) - -// add to the deposit of the given account -function depositTo(address account) public payable - -// withdraw from the deposit -function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external -``` - -### Client behavior upon receiving a UserOperation - -When a client receives a `UserOperation`, it must first run some basic sanity checks, namely that: - -* Either the `sender` is an existing contract, or the `initCode` is not empty (but not both) -* If `initCode` is not empty, parse its first 20 bytes as a factory address. Record whether the factory is staked, in case the later simulation indicates that it needs to be. If the factory accesses global state, it must be staked - see [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) for details. -* The `verificationGasLimit` is sufficiently low (`<= MAX_VERIFICATION_GAS`) and the `preVerificationGas` is sufficiently high (enough to pay for the calldata gas cost of serializing the `UserOperation` plus `PRE_VERIFICATION_OVERHEAD_GAS`) -* The `paymasterAndData` is either empty, or start with the **paymaster** address, which is a contract that (i) currently has nonempty code on chain, (ii) has a sufficient deposit to pay for the UserOperation, and (iii) is not currently banned. During simulation, the paymaster's stake is also checked, depending on its storage usage - see [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) for details. -* The callgas is at least the cost of a `CALL` with non-zero value. -* The `maxFeePerGas` and `maxPriorityFeePerGas` are above a configurable minimum value that the client is willing to accept. At the minimum, they are sufficiently high to be included with the current `block.basefee`. -* The sender doesn't have another `UserOperation` already present in the pool (or it replaces an existing entry with the same sender and nonce, with a higher `maxPriorityFeePerGas` and an equally increased `maxFeePerGas`). Only one `UserOperation` per sender may be included in a single batch. A sender is exempt from this rule and may have multiple `UserOperations` in the pool and in a batch if it is staked (see [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) below), but this exception is of limited use to normal accounts. - -If the `UserOperation` object passes these sanity checks, the client must next run the first op simulation, and if the simulation succeeds, the client must add the op to the pool. A second simulation must also happen during bundling to make sure the UserOperation is still valid. - -### Simulation - -#### Simulation Rationale - -In order to add a UserOperation into the mempool (and later to add it into a bundle) we need to "simulate" it to make sure it is valid, and that it is capable of paying for its own execution. -In addition, we need to verify that the same will hold true when executed on-chain. -For this purpose, a UserOperation is not allowed to access any information that might change between simulation and execution, such as current block time, number, hash etc. -In addition, a UserOperation is only allowed to access data related to this sender address: Multiple UserOperations should not access the same storage, so that it is impossible to invalidate a large number of UserOperations with a single state change. -There are 3 special contracts that interact with the account: the factory (initCode) that deploys the contract, the paymaster that can pay for the gas, and signature aggregator (described later) -Each of these contracts is also restricted in its storage access, to make sure UserOperation validations are isolated. - -#### Specification: - -To simulate a `UserOperation` validation, the client makes a view call to `simulateValidation(userop)` - -This method always revert with `ValidationResult` as successful response. -If the call reverts with other error, the client rejects this `userOp`. - -The simulated call performs the full validation, by calling: - -1. If `initCode` is present, create the account. -2. `account.validateUserOp`. -3. if specified a paymaster: `paymaster.validatePaymasterUserOp`. - -Either `validateUserOp` or `validatePaymasterUserOp` may return a "validAfter" and "validUntil" timestamps, which is the time-range that this UserOperation is valid on-chain. -The simulateValidation call returns this range. -A node MAY drop a UserOperation if it expires too soon (e.g. wouldn't make it to the next block) - -The operations differ in their opcode banning policy. -In order to distinguish between them, there is a call to the NUMBER opcode (`block.number`), used as a delimiter between the 3 functions. -While simulating `userOp` validation, the client should make sure that: - -1. May not invokes any **forbidden opcodes** -2. Must not use GAS opcode (unless followed immediately by one of { `CALL`, `DELEGATECALL`, `CALLCODE`, `STATICCALL` }.) -3. Storage access is limited as follows: - 1. self storage (of factory/paymaster, respectively) is allowed, but only if self entity is staked - 2. account storage access is allowed (see Storage access by Slots, below), - 3. in any case, may not use storage used by another UserOp `sender` in the same bundle (that is, paymaster and factory are not allowed as senders) -4. Limitation on "CALL" opcodes (`CALL`, `DELEGATECALL`, `CALLCODE`, `STATICCALL`): - 1. must not use value (except from account to the entrypoint) - 2. must not revert with out-of-gas - 3. destination address must have code (EXTCODESIZE>0) - 4. cannot call EntryPoint's `handleOps` method (to avoid recursion) -5. `EXTCODEHASH` of every address accessed (by any opcode) does not change between first and second simulations of the op. -6. `EXTCODEHASH`, `EXTCODELENGTH`, `EXTCODECOPY` may not access address with no code. -7. If `op.initcode.length != 0` , allow only one `CREATE2` opcode call (in the first (deployment) block), otherwise forbid `CREATE2`. - -#### Storage associated with an address - -We define storage slots as "associated with an address" as all the slots that uniquely related on this address, and cannot be related with any other address. -In solidity, this includes all storage of the contract itself, and any storage of other contracts that use this contract address as a mapping key. - -An address `A` is associated with: - -1. Slots of contract `A` address itself. -2. Slot `A` on any other address. -3. Slots of type `keccak256(A || X) + n` on any other address. (to cover `mapping(address => value)`, which is usually used for balance in EIP-20 tokens). - `n` is an offset value up to 128, to allow accessing fields in the format `mapping(address => struct)` - - -#### Alternative Mempools - -The simulation rules above are strict and prevent the ability of paymasters and signature aggregators to grief the system. -However, there might be use-cases where specific paymasters (and signature aggregators) can be validated -(through manual auditing) and verified that they cannot cause any problem, while still require relaxing of the opcode rules. -A bundler cannot simply "whitelist" request from a specific paymaster: if that paymaster is not accepted by all -bundlers, then its support will be sporadic at best. -Instead, we introduce the term "alternate mempool". -UserOperations that use whitelisted paymasters (or signature aggregators) are put into a separate mempool. -Only bundlers that support this whitelist will use UserOperations from this mempool. -These UserOperations can be bundled together with UserOperations from the main mempool - -### Bundling - -During bundling, the client should: - -* Exclude UserOps that access any sender address of another UserOp in the same batch. -* Exclude UserOps that access any address created by another UserOp validation in the same batch (via a factory). -* For each paymaster used in the batch, keep track of the balance while adding UserOps. Ensure that it has sufficient deposit to pay for all the UserOps that use it. -* Sort UserOps by aggregator, to create the lists of UserOps-per-aggregator. -* For each aggregator, run the aggregator-specific code to create aggregated signature, and update the UserOps - -After creating the batch, before including the transaction in a block, the client should: - -* Run `eth_estimateGas` with maximum possible gas, to verify the entire `handleOps` batch transaction, and use the estimated gas for the actual transaction execution. -* If the call reverted, check the `FailedOp` event. A `FailedOp` during `handleOps` simulation is an unexpected event since it was supposed to be caught by the single-UserOperation simulation. Remove the failed op that caused the revert from the batch and drop from the mempool. Other ops from the same paymaster should be removed from the current batch, but kept in the mempool. Repeat until `eth_estimateGas` succeeds. - -In practice, restrictions (2) and (3) basically mean that the only external accesses that the account and the paymaster can make are reading code of other contracts if their code is guaranteed to be immutable (eg. this is useful for calling or delegatecalling to libraries). - -If any of the three conditions is violated, the client should reject the `op`. If both calls succeed (or, if `op.paymaster == ZERO_ADDRESS` and the first call succeeds)without violating the three conditions, the client should accept the op. On a bundler node, the storage keys accessed by both calls must be saved as the `accessList` of the `UserOperation` - -When a bundler includes a bundle in a block it must ensure that earlier transactions in the block don't make any UserOperation fail. It should either use access lists to prevent conflicts, or place the bundle as the first transaction in the block. - -#### Forbidden opcodes - -The forbidden opcodes are to be forbidden when `depth > 2` (i.e. when it is the factory, account, paymaster, or other contracts called by them that are being executed). They are: `GASPRICE`, `GASLIMIT`, `DIFFICULTY`, `TIMESTAMP`, `BASEFEE`, `BLOCKHASH`, `NUMBER`, `SELFBALANCE`, `BALANCE`, `ORIGIN`, `GAS`, `CREATE`, `COINBASE`, `SELFDESTRUCT`. They should only be forbidden during verification, not execution. These opcodes are forbidden because their outputs may differ between simulation and execution, so simulation of calls using these opcodes does not reliably tell what would happen if these calls are later done on-chain. - -Exceptions to the forbidden opcodes: - -1. A single `CREATE2` is allowed if `op.initcode.length != 0` and must result in the deployment of a previously-undeployed `UserOperation.sender`. -2. `GAS` is allowed if followed immediately by one of { `CALL`, `DELEGATECALL`, `CALLCODE`, `STATICCALL` }. - (that is, making calls is allowed, using `gasleft()` or `gas` opcode directly is forbidden) - -### Reputation scoring and throttling/banning for global entities - -#### Reputation Rationale. - -UserOperation's storage access rules prevent them from interfere with each other. -But "global" entities - paymasters, factories and aggregators are accessed by multiple UserOperations, and thus might invalidate multiple previously-valid UserOperations. - -To prevent abuse, we throttle down (or completely ban for a period of time) an entity that causes invalidation of large number of UserOperations in the mempool. -To prevent such entities from "sybil-attack", we require them to stake with the system, and thus make such DoS attack very expensive. -Note that this stake is never slashed, and can be withdrawn any time (after unstake delay) - -Unstaked entities are allowed, under the rules below. - -When staked, an entity is also allowed to use its own associated storage, in addition to sender's associated storage. - -The stake value is not enforced on-chain, but specifically by each node while simulating a transaction. -The stake is expected to be above MIN_STAKE_VALUE, and unstake delay above MIN_UNSTAKE_DELAY -The value of MIN_UNSTAKE_DELAY is 84600 (one day) -The value of MIN_STAKE_VALUE is determined per chain, and specified in the "bundler specification test suite" - -#### Un-staked entities - -Under the following special conditions, unstaked entities still can be used: - -- An entity that doesn't use any storage at all, or only the senders's storage (not the entity's storage - that does require a stake) -- If the UserOp doesn't create a new account (that is initCode is empty), then the entity may also use [storage associated with the sender](#storage-associated-with-an-address)) -- A paymaster that has a “postOp()” method (that is, validatePaymasterUserOp returns “context”) must be staked - -#### Specification. - -In the following specification, "entity" is either address that is explicitly referenced by the UserOperation: sender, factory, paymaster and aggregator. -Clients maintain two mappings with a value for staked entities: - -* `opsSeen: Map[Address, int]` -* `opsIncluded: Map[Address, int]` - -If an entity doesn't use storage at all, or only reference storage associated with the "sender" (see [Storage associated with an address](#storage-associated-with-an-address)), then it is considered "OK", without using the rules below. - -When the client learns of a new staked entity, it sets `opsSeen[paymaster] = 0` and `opsIncluded[paymaster] = 0` . - -The client sets `opsSeen[entity] +=1` each time it adds an op with that `entity` to the `UserOperationPool`, and the client sets `opsIncluded[entity] += 1` each time an op that was in the `UserOperationPool` is included on-chain. - -Every hour, the client sets `opsSeen[entity] -= opsSeen[entity] // 24` and `opsIncluded[entity] -= opsIncluded[entity] // 24` for all entities (so both values are 24-hour exponential moving averages). - -We define the **status** of an entity as follows: - -```python -OK, THROTTLED, BANNED = 0, 1, 2 - -def status(paymaster: Address, - opsSeen: Map[Address, int], - opsIncluded: Map[Address, int]): - if paymaster not in opsSeen: - return OK - min_expected_included = opsSeen[paymaster] // MIN_INCLUSION_RATE_DENOMINATOR - if min_expected_included <= opsIncluded[paymaster] + THROTTLING_SLACK: - return OK - elif min_expected_included <= opsIncluded[paymaster] + BAN_SLACK: - return THROTTLED - else: - return BANNED -``` - -Stated in simpler terms, we expect at least `1 / MIN_INCLUSION_RATE_DENOMINATOR` of all ops seen on the network to get included. If an entity falls too far behind this minimum, it gets **throttled** (meaning, the client does not accept ops from that paymaster if there is already an op with that entity, and an op only stays in the pool for 10 blocks), If the entity falls even further behind, it gets **banned**. Throttling and banning naturally decay over time because of the exponential-moving-average rule. - -**Non-bundling clients and bundlers should use different settings for the above params**: - -| Param | Client setting | Bundler setting | -| - | - | - | -| `MIN_INCLUSION_RATE_DENOMINATOR` | 100 | 10 | -| `THROTTLING_SLACK` | 10 | 10 | -| `BAN_SLACK` | 50 | 50 | - -To help make sense of these params, note that a malicious paymaster can at most cause the network (only the p2p network, not the blockchain) to process `BAN_SLACK * MIN_INCLUSION_RATE_DENOMINATOR / 24` non-paying ops per hour. - -## Rationale - -The main challenge with a purely smart contract wallet based account abstraction system is DoS safety: how can a block builder including an operation make sure that it will actually pay fees, without having to first execute the entire operation? Requiring the block builder to execute the entire operation opens a DoS attack vector, as an attacker could easily send many operations that pretend to pay a fee but then revert at the last moment after a long execution. Similarly, to prevent attackers from cheaply clogging the mempool, nodes in the P2P network need to check if an operation will pay a fee before they are willing to forward it. - -In this proposal, we expect accounts to have a `validateUserOp` method that takes as input a `UserOperation`, and verify the signature and pay the fee. This method is required to be almost-pure: it is only allowed to access the storage of the account itself, cannot use environment opcodes (eg. `TIMESTAMP`), and can only edit the storage of the account, and can also send out ETH (needed to pay the entry point). The method is gas-limited by the `verificationGasLimit` of the `UserOperation`; nodes can choose to reject operations whose `verificationGasLimit` is too high. These restrictions allow block builders and network nodes to simulate the verification step locally, and be confident that the result will match the result when the operation actually gets included into a block. - -The entry point-based approach allows for a clean separation between verification and execution, and keeps accounts' logic simple. The alternative would be to require accounts to follow a template where they first self-call to verify and then self-call to execute (so that the execution is sandboxed and cannot cause the fee payment to revert); template-based approaches were rejected due to being harder to implement, as existing code compilation and verification tooling is not designed around template verification. - -### Paymasters - -Paymasters facilitate transaction sponsorship, allowing third-party-designed mechanisms to pay for transactions. Many of these mechanisms _could_ be done by having the paymaster wrap a `UserOperation` with their own, but there are some important fundamental limitations to that approach: - -* No possibility for "passive" paymasters (eg. that accept fees in some EIP-20 token at an exchange rate pulled from an on-chain DEX) -* Paymasters run the risk of getting griefed, as users could send ops that appear to pay the paymaster but then change their behavior after a block - -The paymaster scheme allows a contract to passively pay on users' behalf under arbitrary conditions. It even allows EIP-20 token paymasters to secure a guarantee that they would only need to pay if the user pays them: the paymaster contract can check that there is sufficient approved EIP-20 balance in the `validatePaymasterUserOp` method, and then extract it with `transferFrom` in the `postOp` call; if the op itself transfers out or de-approves too much of the EIP-20s, the inner `postOp` will fail and revert the execution and the outer `postOp` can extract payment (note that because of storage access restrictions the EIP-20 would need to be a wrapper defined within the paymaster itself). - -### First-time account creation - -It is an important design goal of this proposal to replicate the key property of EOAs that users do not need to perform some custom action or rely on an existing user to create their wallet; they can simply generate an address locally and immediately start accepting funds. - -The wallet creation itself is done by a "factory" contract, with wallet-specific data. -The factory is expected to use CREATE2 (not CREATE) to create the wallet, so that the order of creation of wallets doesn't interfere with the generated addresses. -The `initCode` field (if non-zero length) is parsed as a 20-byte address, followed by "calldata" to pass to this address. -This method call is expected to create a wallet and return its address. -If the factory does use CREATE2 or some other deterministic method to create the wallet, it's expected to return the wallet address even if the wallet has already been created. This is to make it easier for clients to query the address without knowing if the wallet has already been deployed, by simulating a call to `entryPoint.getSenderAddress()`, which calls the factory under the hood. -When `initCode` is specified, if either the `sender` address points to an existing contract, or (after calling the initCode) the `sender` address still does not exist, -then the operation is aborted. -The `initCode` MUST NOT be called directly from the entryPoint, but from another address. -The contract created by this factory method should accept a call to `validateUserOp` to validate the UserOp's signature. -For security reasons, it is important that the generated contract address will depend on the initial signature. -This way, even if someone can create a wallet at that address, he can't set different credentials to control it. -The factory has to be staked if it accesses global storage - see [reputation, throttling and banning section](#reputation-scoring-and-throttlingbanning-for-global-entities) for details. - -NOTE: In order for the wallet to determine the "counterfactual" address of the wallet (prior its creation), -it should make a static call to the `entryPoint.getSenderAddress()` - -### Entry point upgrading - -Accounts are encouraged to be DELEGATECALL forwarding contracts for gas efficiency and to allow account upgradability. The account code is expected to hard-code the entry point into their code for gas efficiency. If a new entry point is introduced, whether to add new functionality, improve gas efficiency, or fix a critical security bug, users can self-call to replace their account's code address with a new code address containing code that points to a new entry point. During an upgrade process, it's expected that two mempools will run in parallel. - -### RPC methods (eth namespace) - -#### * eth_sendUserOperation - -eth_sendUserOperation submits a User Operation object to the User Operation pool of the client. The client MUST validate the UserOperation, and return a result accordingly. - -The result `SHOULD` be set to the **userOpHash** if and only if the request passed simulation and was accepted in the client's User Operation pool. If the validation, simulation, or User Operation pool inclusion fails, `result` `SHOULD NOT` be returned. Rather, the client `SHOULD` return the failure reason. - -##### Parameters: - -1. **UserOperation** a full user-operation struct. All fields MUST be set as hex values. empty `bytes` block (e.g. empty `initCode`) MUST be set to `"0x"` -2. **EntryPoint** the entrypoint address the request should be sent through. this MUST be one of the entry points returned by the `supportedEntryPoints` rpc call. - -##### Return value: - -* If the UserOperation is valid, the client MUST return the calculated **userOpHash** for it -* in case of failure, MUST return an `error` result object, with `code` and `message`. The error code and message SHOULD be set as follows: - * **code: -32602** - invalid UserOperation struct/fields - * **code: -32500** - transaction rejected by entryPoint's simulateValidation, during wallet creation or validation - * The `message` field MUST be set to the FailedOp's "`AAxx`" error message from the EntryPoint - * **code: -32501** - transaction rejected by paymaster's validatePaymasterUserOp - * The `message` field SHOULD be set to the revert message from the paymaster - * The `data` field MUST contain a `paymaster` value - * **code: -32502** - transaction rejected because of opcode validation - * **code: -32503** - UserOperation out of time-range: either wallet or paymaster returned a time-range, and it is already expired (or will expire soon) - * The `data` field SHOULD contain the `validUntil` and `validAfter` values - * The `data` field SHOULD contain a `paymaster` value, if this error was triggered by the paymaster - * **code: -32504** - transaction rejected because paymaster (or signature aggregator) is throttled/banned - * The `data` field SHOULD contain a `paymaster` or `aggregator` value, depending on the failed entity - * **code: -32505** - transaction rejected because paymaster (or signature aggregator) stake or unstake-delay is too low - * The `data` field SHOULD contain a `paymaster` or `aggregator` value, depending on the failed entity - * The `data` field SHOULD contain a `minimumStake` and `minimumUnstakeDelay` - * **code: -32506** - transaction rejected because wallet specified unsupported signature aggregator - * The `data` field SHOULD contain an `aggregator` value - -##### Example: - -Request: - -```json= -{ - "jsonrpc": "2.0", - "id": 1, - "method": "eth_sendUserOperation", - "params": [ - { - sender, // address - nonce, // uint256 - initCode, // bytes - callData, // bytes - callGasLimit, // uint256 - verificationGasLimit, // uint256 - preVerificationGas, // uint256 - maxFeePerGas, // uint256 - maxPriorityFeePerGas, // uint256 - paymasterAndData, // bytes - signature // bytes - }, - entryPoint // address - ] -} - -``` - -Response: - -``` -{ - "jsonrpc": "2.0", - "id": 1, - "result": "0x1234...5678" -} -``` - -##### Example failure responses: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "message": "AA21 didn't pay prefund", - "code": -32500 - } -} -``` - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "message": "paymaster stake too low", - "data": { - "paymaster": "0x123456789012345678901234567890123456790", - "minimumStake": "0xde0b6b3a7640000", - "minimumUnstakeDelay": "0x15180" - }, - "code": -32504 - } -} -``` - - -#### * eth_estimateUserOperationGas - -Estimate the gas values for a UserOperation. -Given UserOperation optionally without gas limits and gas prices, return the needed gas limits. -The signature field is ignored by the wallet, so that the operation will not require user's approval. -Still, it might require putting a "semi-valid" signature (e.g. a signature in the right length) - -**Parameters**: same as `eth_sendUserOperation` - gas limits (and prices) parameters are optional, but are used if specified. - `maxFeePerGas` and `maxPriorityFeePerGas` default to zero, so no payment is required by neither account nor paymaster. - -**Return Values:** - -* **preVerificationGas** gas overhead of this UserOperation -* **verificationGasLimit** actual gas used by the validation of this UserOperation -* **callGasLimit** value used by inner account execution - -##### Error Codes: - -Same as `eth_sendUserOperation` -This operation may also return an error if the inner call to the account contract reverts. - -#### * eth_getUserOperationByHash - -Return a UserOperation based on a hash (userOpHash) returned by `eth_sendUserOperation` - -**Parameters** - -* **hash** a userOpHash value returned by `eth_sendUserOperation` - -**Return value**: - -`null` in case the UserOperation is not yet included in a block, or a full UserOperation, with the addition of `entryPoint`, `blockNumber`, `blockHash` and `transactionHash` - -#### * eth_getUserOperationReceipt - -Return a UserOperation receipt based on a hash (userOpHash) returned by `eth_sendUserOperation` - -**Parameters** - -* **hash** a userOpHash value returned by `eth_sendUserOperation` - -**Return value**: - -`null` in case the UserOperation is not yet included in a block, or: - -* **userOpHash** the request hash -* **entryPoint** -* **sender** -* **nonce** -* **paymaster** the paymaster used for this userOp (or empty) -* **actualGasCost** - actual amount paid (by account or paymaster) for this UserOperation -* **actualGasUsed** - total gas used by this UserOperation (including preVerification, creation, validation and execution) -* **success** boolean - did this execution completed without revert -* **reason** in case of revert, this is the revert reason -* **logs** the logs generated by this UserOperation (not including logs of other UserOperations in the same bundle) -* **receipt** the TransactionReceipt object. - Note that the returned TransactionReceipt is for the entire bundle, not only for this UserOperation. - -#### * eth_supportedEntryPoints - -Returns an array of the entryPoint addresses supported by the client. The first element of the array `SHOULD` be the entryPoint addressed preferred by the client. - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "eth_supportedEntryPoints", - "params": [] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": [ - "0xcd01C8aa8995A59eB7B2627E69b40e0524B5ecf8", - "0x7A0A0d159218E6a2f407B99173A2b12A6DDfC2a6" - ] -} -``` - -#### * eth_chainId - -Returns [EIP-155](./eip-155.md) Chain ID. - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "eth_chainId", - "params": [] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": "0x1" -} -``` - -### RPC methods (debug Namespace) - -This api must only be available on testing mode and is required by the compatibility test suite. In production, any `debug_*` rpc calls should be blocked. - -#### * debug_bundler_clearState - -Clears the bundler mempool and reputation data of paymasters/accounts/factories/aggregators. - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_clearState", - "params": [] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": "ok" -} -``` - -#### * debug_bundler_dumpMempool - -Dumps the current UserOperations mempool - -**Parameters:** - -* **EntryPoint** the entrypoint used by eth_sendUserOperation - -**Returns:** - -`array` - Array of UserOperations currently in the mempool. - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_dumpMempool", - "params": ["0x1306b01bC3e4AD202612D3843387e94737673F53"] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": [ - { - sender, // address - nonce, // uint256 - initCode, // bytes - callData, // bytes - callGasLimit, // uint256 - verificationGasLimit, // uint256 - preVerificationGas, // uint256 - maxFeePerGas, // uint256 - maxPriorityFeePerGas, // uint256 - paymasterAndData, // bytes - signature // bytes - } - ] -} -``` - -#### * debug_bundler_sendBundleNow - -Forces the bundler to build and execute a bundle from the mempool as `handleOps()` transaction. - -Returns: `transactionHash` - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_sendBundleNow", - "params": [] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": "0xdead9e43632ac70c46b4003434058b18db0ad809617bd29f3448d46ca9085576" -} -``` - -#### * debug_bundler_setBundlingMode - -Sets bundling mode. - -After setting mode to "manual", an explicit call to debug_bundler_sendBundleNow is required to send a bundle. - -##### parameters: - -`mode` - 'manual' | 'auto' - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_setBundlingMode", - "params": ["manual"] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": "ok" -} -``` - -#### * debug_bundler_setReputation - -Sets reputation of given addresses. parameters: - -**Parameters:** - -* An array of reputation entries to add/replace, with the fields: - - * `address` - The address to set the reputation for. - * `opsSeen` - number of times a user operations with that entity was seen and added to the mempool - * `opsIncluded` - number of times a user operations that uses this entity was included on-chain - * `status` - (string) The status of the address in the bundler 'ok' | 'throttled' | 'banned'. - -* **EntryPoint** the entrypoint used by eth_sendUserOperation - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_setReputation", - "params": [ - [ - { - "address": "0x7A0A0d159218E6a2f407B99173A2b12A6DDfC2a6", - "opsSeen": 20, - "opsIncluded": 13 - } - ], - "0x1306b01bC3e4AD202612D3843387e94737673F53" - ] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": "ok" -} -``` - - -#### * debug_bundler_dumpReputation - -Returns the reputation data of all observed addresses. -Returns an array of reputation objects, each with the fields described above in `debug_bundler_setReputation` with the - - -**Parameters:** - -* **EntryPoint** the entrypoint used by eth_sendUserOperation - -**Return value:** - -An array of reputation entries with the fields: - -* `address` - The address to set the reputation for. -* `opsSeen` - number of times a user operations with that entity was seen and added to the mempool -* `opsIncluded` - number of times a user operations that uses this entity was included on-chain -* `status` - (string) The status of the address in the bundler 'ok' | 'throttled' | 'banned'. - -```json= -# Request -{ - "jsonrpc": "2.0", - "id": 1, - "method": "debug_bundler_dumpReputation", - "params": ["0x1306b01bC3e4AD202612D3843387e94737673F53"] -} - -# Response -{ - "jsonrpc": "2.0", - "id": 1, - "result": [ - { "address": "0x7A0A0d159218E6a2f407B99173A2b12A6DDfC2a6", - "opsSeen": 20, - "opsIncluded": 19, - "status": "ok" - } - ] -} -``` - -## Backwards Compatibility - -This EIP does not change the consensus layer, so there are no backwards compatibility issues for Ethereum as a whole. Unfortunately it is not easily compatible with pre-[EIP-4337](./eip-4337.md) accounts, because those accounts do not have a `validateUserOp` function. If the account has a function for authorizing a trusted op submitter, then this could be fixed by creating an [EIP-4337](./eip-4337.md) compatible account that re-implements the verification logic as a wrapper and setting it to be the original account's trusted op submitter. - -## Reference Implementation - -See `https://github.com/eth-infinitism/account-abstraction/tree/main/contracts` - -## Security Considerations - -The entry point contract will need to be very heavily audited and formally verified, because it will serve as a central trust point for _all_ [EIP-4337](./eip-4337.md). In total, this architecture reduces auditing and formal verification load for the ecosystem, because the amount of work that individual _accounts_ have to do becomes much smaller (they need only verify the `validateUserOp` function and its "check signature, increment nonce and pay fees" logic) and check that other functions are `msg.sender == ENTRY_POINT` gated (perhaps also allowing `msg.sender == self`), but it is nevertheless the case that this is done precisely by concentrating security risk in the entry point contract that needs to be verified to be very robust. - -Verification would need to cover two primary claims (not including claims needed to protect paymasters, and claims needed to establish p2p-level DoS resistance): - -* **Safety against arbitrary hijacking**: The entry point only calls an account generically if `validateUserOp` to that specific account has passed (and with `op.calldata` equal to the generic call's calldata) -* **Safety against fee draining**: If the entry point calls `validateUserOp` and passes, it also must make the generic call with calldata equal to `op.calldata` - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4337.md diff --git a/EIPS/eip-4341.md b/EIPS/eip-4341.md index 6bc8c21655a56c..1f0417528a9494 100644 --- a/EIPS/eip-4341.md +++ b/EIPS/eip-4341.md @@ -1,124 +1,7 @@ --- eip: 4341 -title: Ordered NFT Batch Standard -description: The ordering information of multiple NFTs is retained and managed -author: Simon Tian (@simontianx) -discussions-to: https://github.com/ethereum/EIPs/issues/3782 -status: Stagnant -type: Standards Track category: ERC -created: 2021-10-01 +status: Moved --- -## Abstract -This standard introduces a smart contract interface that can represent a batch -of non-fungible tokens of which the ordering information shall be retained and -managed. Such information is particularly useful if `tokenId`s are encoded with -the sets of `unicodes` for logographic characters and emojis. As a result, NFTs -can be utilized as carriers of meanings. - -## Motivation -Non-fungible tokens are widely accepted as carriers of crypto-assets, hence in both -[ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md), the ordering information of -multiple NFTs is discarded. However, as proposed in [EIP-3754](./eip-3754.md), -non-fungible tokens are thought of as basic units on a blockchain and can carry -abstract meanings with unicoded `tokenId`s. Transferring such tokens is transmitting -an ordered sequence of unicodes, thus effectively transmitting phrases or meanings -on a blockchain. - -A **[logograph](https://en.wikipedia.org/wiki/Logogram)** is a written character -that represents a word or morpheme, examples include _hanzi_ in Mandarin, _kanji_ -in Japanese, _hanja_ in Korean, and etc. A [unicode](https://en.wikipedia.org/wiki/Unicode) -is an information technology standard for the consistent encoding, representation, and -handling of texts. - -It is natural to combine the two to create unicoded NFTs to represent logographic -characters. Since a rich amount of meanings can be transmitted in just a few -characters in such languages, it is technically practical and valuable to create -a standard for it. Emojis are similar with logographs and can be included as well. -For non-logographic languages such as English, although the same standard can be -applied, it is tedious to represent each letter with an NFT, hence the gain is -hardly justifiable. - -A motivating example is instead of sending the two Chinese characters of the -Great Wall `长城`, two NFTs with IDs `#38271` and `#22478` respectively can be -transferred in a batch. The two IDs are corresponding to the decimal unicode of -the two characters. The receiving end decodes the IDs and retrieves the original -characters. A key point is the ordering information matters in this scenario -since the tuples `(38271, 22478)` and `(22478, 38271)` can be decoded as -`长城` and `城长`, respectively, and both are legitimate words in the Chinese -language. This illustrates the key difference between this standard and [ERC-1155](./eip-1155.md). - -Besides, in the eastern Asian culture, characters are sometimes considered or -practically used as gifts in holidays such as Spring Feastival, etc. -`(24685, 21916, 21457, 36001)` `恭喜发财` can be used literally as a gift to -express the best wishes for financial prosperity. It is therefore cuturally -natural to transfer tokens to express meanings with this standard. - -Also in logographic language systems, ancient teachings are usually written in -concise ways such that a handful of characters can unfold a rich amount of -meanings. Modern people now get a reliable technical means to pass down their -words, poems and proverbs to the future generations by sending tokens. - -Other practical and interesting applications include Chinese chess, wedding -vows, family generation quotes and sayings, funeral commendation words, prayers, -anecdotes and etc. - -## Specification -``` -pragma solidity ^0.8.0; - -/** - @title EIP-4341 Multi Ordered NFT Standard - @dev See https://eips.ethereum.org/EIPS/eip-4341 - */ -interface ERC4341 /* is ERC165 */ { - event Transfer(address indexed from, address indexed to, uint256 id, uint256 amount); - - event TransferBatch(address indexed from, address indexed to, uint256[] ids, uint256[] amounts); - - event ApprovalForAll(address indexed owner, address indexed operator, bool approved); - - function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; - - function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; - - function safePhraseTransferFrom(address from, address to, uint256[] calldata phrase, bytes calldata data) external; - - function balanceOf(address owner, uint256 id) external view returns (uint256); - - function balanceOfPhrase(address owner) external view returns (uint256); - - function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory); - - function retrievePhrase(address owner, uint256 phraseId) external view returns (uint256[] memory); - - function setApprovalForAll(address operator, bool approved) external; - - function isApprovedForAll(address owner, address operator) external view returns (bool); -} -``` - -## Rationale -In [ERC-1155](./eip-1155.md) and [ERC-721](./eip-721.md), NFTs are used to represent -crypto-assets, and in this standard together with [EIP-3754](./eip-3754.md), NFTs -are equipped with utilities. In this standard, the ordering information of a batch -of NFTs is retained and managed through a construct `phrase`. - -### Phrase -A `phrase` is usually made of a handful of basic characters or an orderred sequence -of unicodes and is able to keep the ordering information in a batch of tokens. -Technically, it is stored in an array of unsigned integers, and is not supposed -to be disseminated. A phrase does not increase or decrease the amount of any NFT -in anyway. A phrase cannot be transferred, however, it can be retrieved and -decoded to restore the original sequence of unicodes. The phrase information -is kept in storage and hence additional storage than [ERC-1155](./eip-1155.md) is required. - -## Backwards Compatibility -[EIP-3754](./eip-3754.md) is the pre-requisite to this standard. - -## Reference Implementation -https://github.com/simontianx/ERC4341 - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4341.md diff --git a/EIPS/eip-4353.md b/EIPS/eip-4353.md index b0b4a3e0db12c0..0d79c1e41536b4 100644 --- a/EIPS/eip-4353.md +++ b/EIPS/eip-4353.md @@ -1,230 +1,7 @@ --- eip: 4353 -title: Interface for Staked Tokens in NFTs -description: This interface enables access to publicly viewable staking data of an NFT. -author: Rex Creed (@aug2uag), Dane Scarborough -discussions-to: https://ethereum-magicians.org/t/eip-4353-viewing-staked-tokens-in-nft/7234 -status: Stagnant -type: Standards Track category: ERC -created: 2021-10-08 -requires: 165 +status: Moved --- -## Abstract -[EIP-721](./eip-721.md) tokens can be deposited or staked in NFTs for a variety of reasons including escrow, rewards, benefits, and others. There is currently no means of retrieving the number of tokens staked and/or bound to an NFT. This proposal outlines a standard that may be implemented by all wallets and marketplaces easily to correctly retrieve the staked token amount of an NFT. - -## Motivation -Without staked token data, the actual amount of staked tokens cannot be conveyed from token owners to other users, and cannot be displayed in wallets, marketplaces, or block explorers. The ability to identify and verify an exogenous value derived from the staking process may be critical to the aims of an NFT holder. - -## Specification -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.0; - -/** - * @dev Interface of the ERC4353 standard, as defined in the - * https://eips.ethereum.org/EIPS/eip-4353. - * - * Implementers can declare support of contract interfaces, which can then be - * queried by others. - * - * Note: The ERC-165 identifier for this interface is 0x3a3d855f. - * - */ -interface IERC721Staked { - - /** - * @dev Returns uint256 amount of on-chain tokens staked to the NFT. - * - * @dev Wallets and marketplaces would need to call this for displaying - * the amount of tokens staked and/or bound to the NFT. - */ - function stakedAmount(uint256 tokenId) external view returns (uint256); - -} -``` - -### Suggested flow: - -#### Constructor/deployment -* Creator - the owner of an NFT with its own rules for depositing tokens at and/or after the minting of a token. -* Token Amount - the current amount of on-chain [EIP-20](./eip-20.md) or derived tokens bound to an NFT from one or more deposits. -* Withdraw Mechanism - rules based approach for withdrawing staked tokens and making sure to update the balance of the staked tokens. - -### Staking at mint and locking tokens in NFT -The suggested and intended implementation of this standard is to stake tokens at the time of minting an NFT, and not implementing any outbound transfer of tokens outside of `burn`. Therefore, only to stake at minting and withdraw only at burning. - -#### NFT displayed in wallet or marketplace -A wallet or marketplace checks if an NFT has publicly staked tokens available for display - if so, call `stakedAmount(tokenId)` to get the current amount of tokens staked and/or bound to the NFT. - -The logical code looks something like this and inspired by William Entriken: - -```solidity -// contracts/Token.sol -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -/** - * @title Token - * @dev Very simple ERC721 example with stake interface example. - * Note this implementation enforces recommended procedure: - * 1) stake at mint - * 2) withdraw at burn - */ -contract ERC721Staked is ERC721URIStorage, Ownable { - /// @dev track original minter of tokenId - mapping (uint256 => address payable) private payees; - /// @dev map tokens to stored staked token value - mapping (uint256 => uint256) private tokenValue; - - /// @dev metadata - constructor() ERC721 ( - "Staked NFT", - "SNFT" - ){} - - /// @dev mints a new NFT - /// @param _to address that will own the minted NFT - /// @param _tokenId id the NFT - /// @param _uri metadata - function mint( - address payable _to, - uint256 _tokenId, - string calldata _uri - ) - external - payable - onlyOwner - { - _mint(_to, _tokenId); - _setTokenURI(_tokenId, _uri); - payees[_tokenId] = _to; - tokenValue[_tokenId] = msg.value; - } - - /// @dev staked interface - /// @param _tokenId id of the NFT - /// @return _value staked value - function stakedAmount( - uint256 _tokenId - ) external view returns (uint256 _value) { - _value = tokenValue[_tokenId]; - return _value; - } - - /// @dev removes NFT & transfers crypto to minter - /// @param _tokenId the NFT we want to remove - function burn( - uint256 _tokenId - ) - external - onlyOwner - { - super._burn(_tokenId); - payees[_tokenId].transfer(tokenValue[_tokenId]); - tokenValue[_tokenId] = 0; - } - -} -``` - -## Rationale -This standard is completely agnostic to how tokens are deposited or handled by the NFT. It is, therefore, the choice and responsibility of the author to encode and communicate the encoding of their tokenomics to purchasees of their token and/or to make their contracts viewable by purchasees. - -Although the intention of this standard is for tokens staked at mint and withdrawable only upon burn, the interface may be modified for dynamic withdrawing and depositing of tokens especially under DeFi application settings. In its current form, the contract logic may be the determining factor whether a deviation from the standard exists. - -## Backward Compatibility -TBD - -## Test Cases -```js -const { expect } = require("chai"); -const { ethers, waffle } = require("hardhat"); -const provider = waffle.provider; - -describe("StakedNFT", function () { - let _id = 1234567890; - let value = '1.5'; - let Token; - let Interface; - let owner; - let addr1; - let addr2; - - beforeEach(async function () { - Token = await ethers.getContractFactory("ERC721Staked"); - [owner, addr1, ...addr2] = await ethers.getSigners(); - Interface = await Token.deploy(); - }); - - describe("Staked NFT", function () { - it("Should set the right owner", async function () { - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar') - expect(await Interface.ownerOf(_id)).to.equal(addr1.address); - }); - - it("Should not have staked balance without value", async function () { - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar') - expect(await Interface.stakedAmount(_id)).to.equal( - ethers.utils.parseEther('0')); - }); - - it("Should set and return the staked amount", async function () { - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar', - {value: ethers.utils.parseEther(value)}) - expect(await Interface.stakedAmount(_id)).to.equal( - ethers.utils.parseEther(value)); - }); - - it("Should decrease owner eth balance on mint (deposit)", async function () { - let balance1 = await provider.getBalance(owner.address); - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar', - {value: ethers.utils.parseEther(value)}) - let balance2 = await provider.getBalance(owner.address); - let diff = parseFloat(ethers.utils.formatEther( - balance1.sub(balance2))).toFixed(1); - expect(diff === value); - }); - - it("Should add to payee's eth balance on burn (withdraw)", async function () { - let balance1 = await provider.getBalance(addr1.address); - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar', - {value: ethers.utils.parseEther(value)}) - await Interface.burn(_id); - let balance2 = await provider.getBalance(addr1.address); - let diff = parseFloat(ethers.utils.formatEther( - balance2.sub(balance1))).toFixed(1); - expect(diff === value); - }); - - it("Should update balance after transfer", async function () { - let mint = await Interface.mint( - addr1.address, _id, 'http://foobar', - {value: ethers.utils.parseEther(value)}) - await Interface.burn(_id); - expect(await Interface.stakedAmount(_id)).to.equal( - ethers.utils.parseEther('0')); - }); - }); -}); -``` - -## Security Considerations -The purpose of this standard is to simply and publicly identify whether an NFT claims to have staked tokens. - -Staked claims will be unreliable without a locking mechanism enforced, for example, if staked tokens can only be transferred at burn. Otherwise, tokens may be deposited and/or withdrawn at any time via arbitrary methods. Also, contracts that may allow arbitrary transfers without updating the correct balance will result in potential issues. A strict rules-based approach should be taken with these edge cases in mind. - -A dedicated service may exist to verify the claims of a token by analyzing transactions on the explorer. In this manner, verification may be automated to ensure a token's claims are valid. The logical extension of this method may be to extend the interface and support flagging erroneous claims, all the while maintaining a simple goal of validating and verifying a staked amount exists to benefit the operator experience. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4353.md diff --git a/EIPS/eip-4361.md b/EIPS/eip-4361.md index 80370473c9f751..02043a16b4dabe 100644 --- a/EIPS/eip-4361.md +++ b/EIPS/eip-4361.md @@ -1,289 +1,7 @@ --- eip: 4361 -title: Sign-In with Ethereum -description: Off-chain authentication for Ethereum accounts to establish sessions. -author: Wayne Chang (@wyc), Gregory Rocco (@obstropolos), Brantly Millegan (@brantlymillegan), Nick Johnson (@Arachnid) -discussions-to: https://ethereum-magicians.org/t/eip-4361-sign-in-with-ethereum/7263 -status: Stagnant -type: Standards Track category: ERC -created: 2021-10-11 -requires: 55, 137, 155, 191, 1271, 1328 +status: Moved --- -## Abstract -Sign-In with Ethereum describes how Ethereum accounts authenticate with off-chain services by signing a standard message format parameterized by scope, session details, and security mechanisms (e.g., a nonce). The goals of this specification are to provide a self-custodied alternative to centralized identity providers, improve interoperability across off-chain services for Ethereum-based authentication, and provide wallet vendors a consistent machine-readable message format to achieve improved user experiences and consent management. - -## Motivation -When signing in to popular non-blockchain services today, users will typically use identity providers (IdPs) that are centralized entities with ultimate control over users' identifiers, for example, large internet companies and email providers. Incentives are often misaligned between these parties. Sign-In with Ethereum offers a new self-custodial option for users who wish to assume more control and responsibility over their own digital identity. - -Already, many services support workflows to authenticate Ethereum accounts using message signing, such as to establish a cookie-based web session which can manage privileged metadata about the authenticating address. This is an opportunity to standardize the sign-in workflow and improve interoperability across existing services, while also providing wallet vendors a reliable method to identify signing requests as Sign-In with Ethereum requests for improved UX. - -## Specification -Sign-In with Ethereum works as follows: - -1. The wallet presents the user with a structured plaintext message or equivalent interface for signing with the [EIP-191](./eip-191.md) signed data format. Before signing, the `message` is prefixed with `\x19Ethereum Signed Message:\n` as defined in [EIP-191](./eip-191.md). -The `message` MUST incorporate an Ethereum `address`, `domain` requesting the signing, `version` of the message, a chain identifier `chain-id`, `uri` for scoping, `nonce` acceptable to the relying party, and `issued-at` timestamp. -2. The signature is then presented to the relying party, which checks the signature's validity and message content. -3. Additional fields, including `expiration-time`, `not-before`, `request-id`, `statement`, and `resources` MAY be incorporated as part of the sign-in process. -4. The relying party MAY further fetch data associated with the Ethereum address, such as from the Ethereum blockchain (e.g., ENS, account balances, [EIP-20](./eip-20.md)/[EIP-721](./eip-721.md)/[EIP-1155](./eip-1155.md) asset ownership), or other data sources that might or might not be permissioned. - - -### Example message -``` -service.invalid wants you to sign in with your Ethereum account: -0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 - -I accept the ServiceOrg Terms of Service: https://service.invalid/tos - -URI: https://service.invalid/login -Version: 1 -Chain ID: 1 -Nonce: 32891756 -Issued At: 2021-09-30T16:25:24Z -Resources: -- ipfs://bafybeiemxf5abjwjbikoz4mc3a3dla6ual3jsgpdr4cjr3oz3evfyavhwq/ -- https://example.com/my-web2-claim.json -``` - -### Informal Message Template -A Bash-like informal template of the full message is presented below for readability and ease of understanding. Field descriptions are provided in the following section. A full ABNF description is provided in the section thereafter. -``` -${domain} wants you to sign in with your Ethereum account: -${address} - -${statement} - -URI: ${uri} -Version: ${version} -Chain ID: ${chain-id} -Nonce: ${nonce} -Issued At: ${issued-at} -Expiration Time: ${expiration-time} -Not Before: ${not-before} -Request ID: ${request-id} -Resources: -- ${resources[0]} -- ${resources[1]} -... -- ${resources[n]} -``` -### Message Field Descriptions -- `domain` is the RFC 3986 authority that is requesting the signing. -- `address` is the Ethereum address performing the signing conformant to capitalization encoded checksum specified in [EIP-55](./eip-55.md) where applicable. -- `statement` (optional) is a human-readable ASCII assertion that the user will sign, and it must not contain `'\n'` (the byte `0x0a`). -- `uri` is an RFC 3986 URI referring to the resource that is the subject of the signing (as in the _subject of a claim_). -- `version` is the current version of the `message`, which MUST be `1` for this specification. -- `chain-id` is the [EIP-155](./eip-155.md) Chain ID to which the session is bound, and the network where Contract Accounts MUST be resolved. -- `nonce` is a randomized token typically chosen by the relying party and used to prevent replay attacks, at least 8 alphanumeric characters. -- `issued-at` is the ISO 8601 datetime string of the current time. -- `expiration-time` (optional) is the ISO 8601 datetime string that, if present, indicates when the signed authentication message is no longer valid. -- `not-before` (optional) is the ISO 8601 datetime string that, if present, indicates when the signed authentication message will become valid. -- `request-id` (optional) is an system-specific identifier that may be used to uniquely refer to the sign-in request. -- `resources` (optional) is a list of information or references to information the user wishes to have resolved as part of authentication by the relying party. They are expressed as RFC 3986 URIs separated by `"\n- "` where `\n` is the byte `0x0a`. - -### ABNF Message Format - -The `message` MUST conform with the following Augmented Backus–Naur Form (ABNF, RFC 5234) expression (note that `%s` denotes case sensitivity for a string term, as per RFC 7405). - -```abnf -sign-in-with-ethereum = - domain %s" wants you to sign in with your Ethereum account:" LF - address LF - LF - [ statement LF ] - LF - %s"URI: " uri LF - %s"Version: " version LF - %s"Chain ID: " chain-id LF - %s"Nonce: " nonce LF - %s"Issued At: " issued-at - [ LF %s"Expiration Time: " expiration-time ] - [ LF %s"Not Before: " not-before ] - [ LF %s"Request ID: " request-id ] - [ LF %s"Resources:" - resources ] - -domain = authority - ; From RFC 3986: - ; authority = [ userinfo "@" ] host [ ":" port ] - ; See RFC 3986 for the fully contextualized - ; definition of "authority". - -address = "0x" 40*40HEXDIG - ; Must also conform to captilization - ; checksum encoding specified in EIP-55 - ; where applicable (EOAs). - -statement = *( reserved / unreserved / " " ) - ; See RFC 3986 for the definition - ; of "reserved" and "unreserved". - ; The purpose is to exclude LF (line break). - -uri = URI - ; See RFC 3986 for the definition of "URI". - -version = "1" - -chain-id = 1*DIGIT - ; See EIP-155 for valid CHAIN_IDs. - -nonce = 8*( ALPHA / DIGIT ) - ; See RFC 5234 for the definition - ; of "ALPHA" and "DIGIT". - -issued-at = date-time -expiration-time = date-time -not-before = date-time - ; See RFC 3339 (ISO 8601) for the - ; definition of "date-time". - -request-id = *pchar - ; See RFC 3986 for the definition of "pchar". - -resources = *( LF resource ) - -resource = "- " URI -``` - -#### Signing and Verifying with Ethereum Accounts -- For Externally Owned Accounts (EOAs), the verification method specified in [EIP-191](./eip-191.md) MUST be used. -- For Contract Accounts, - - The verification method specified in [EIP-1271](./eip-1271.md) SHOULD be used, and if it is not, the implementer MUST clearly define the verification method to attain security and interoperability for both wallets and relying parties. - - When performing [EIP-1271](./eip-1271.md) signature verification, the contract performing the verification MUST be resolved from the specified `chain-id`. - - Implementers SHOULD take into consideration that [EIP-1271](./eip-1271.md) implementations are not required to be pure functions, and can return different results for the same inputs depending on blockchain state. This can affect the security model and session validation rules. For example, a service with [EIP-1271](./eip-1271.md) signing enabled could rely on webhooks to receive notifications when state affecting the results is changed. When it receives a notification, it invalidates any matching sessions. - -### Resolving Ethereum Name Service (ENS) Data -- The relying party or wallet MAY additionally perform resolution of ENS data, as this can improve the user experience by displaying human-friendly information that is related to the `address`. Resolvable ENS data include: - - The [primary ENS name](./eip-181.md). - - The [ENS avatar](./eip-634.md). - - Any other resolvable resources specified in the ENS documentation. -- If resolution of ENS data is performed, implementers SHOULD take precautions to preserve user privacy and consent, as their `address` could be forwarded to third party services as part of the resolution process. - -### Relying Party Implementer Steps - -#### Verifying a signed `message` -- The message MUST be checked for conformance to the ABNF above, checked against expected term values after parsing, and its signature MUST be verified. - -#### Creating sessions -- Sessions MUST be bound to the `address` and not to further resolved resources that can change. - -#### Interpreting and resolving `resources` -- The listed `resources` MUST be RFC 3986 URIs, but their interpretation is out of scope of this specification. -- Implementers SHOULD ensure that that URIs are human-friendly when expressed in plaintext form. - -### Wallet Implementer Steps - -#### Verifying `message` -- The full `message` MUST be checked for conformance to the ABNF above. -- Wallet implementers SHOULD warn users if the substring `"wants you to sign in - with your Ethereum account"` appears anywhere in an [EIP-191](./eip-191.md) message signing - request unless the message fully conforms to the format defined in this specification. - -#### Verifying `domain` binding -- Wallet implementers MUST prevent phishing attacks by matching on the `domain` term when processing a signing request. For example, when processing the message beginning with `"service.invalid wants you to sign in..."`, the wallet checks that the request actually originated from `service.invalid`. -- The domain SHOULD be read from a trusted data source such as the browser window or over WalletConnect ([EIP-1328](./eip-1328.md)) sessions for comparison against the signing message contents. - -#### Creating Sign-In with Ethereum interfaces -- Wallet implementers MUST display to the user the following terms from the Sign-In with Ethereum signing request by default and prior to signing, if they are present: `domain`, `address`, `statement`, and `resources`. Other present terms MUST also be made available to the user prior to signing either by default or through an extended interface. -- Wallet implementers displaying a plaintext `message` to the user SHOULD require the user to scroll to the bottom of the text area prior to signing. -- Wallet implementers MAY construct a custom Sign-In With Ethereum user interface by parsing the ABNF terms into data elements for use in the interface. The display rules above still apply to custom interfaces. - -#### Supporting internationalization (i18n) -- After successfully parsing the message into ABNF terms, translation MAY happen at the UX level per human language. - -## Rationale - -### Requirements -Write a specification for how Sign-In with Ethereum should work. The specification should be simple and generally follow existing practices. Avoid feature bloat, particularly the inclusion of lesser-used projects who see getting into the specification as a means of gaining adoption. The core specification should be decentralized, open, non-proprietary, and have long-term viability. It should have no dependence on a centralized server except for the servers already being run by the application that the user is signing in to. The basic specification should include: Ethereum accounts used for authentication, ENS names for usernames (via reverse resolution), and data from the ENS name’s text records for additional profile information (e.g. avatar, social media handles, etc). - -Additional functional requirements: -1. The user must be presented a human-understandable interface prior to signing, mostly free of machine-targeted artifacts such as JSON blobs, hex codes (aside from the Ethereum address), and baseXX-encoded strings. -2. The application server must be able to implement fully usable support for its end without forcing a change in the wallets. -3. There must be a simple and straightforward upgrade path for both applications and wallets already using Ethereum account-based signing for authentication. -4. There must be facilities and guidelines for adequate mitigation of Man-in-the-Middle (MITM) attacks, replay attacks, and malicious signing requests. - -### Design Goals -1. Human-Friendly -2. Simple to Implement -3. Secure -4. Machine Readable -5. Extensible - -### Technical Decisions -- Why [EIP-191](./eip-191.md) (Signed Data Standard) over [EIP-712](./eip-712.md) (Ethereum typed structured data hashing and signing) - - [EIP-191](./eip-191.md) is already broadly supported across wallets UX, while [EIP-712](./eip-712.md) support for friendly user display is pending. **(1, 2, 3, 4)** - - [EIP-191](./eip-191.md) is simple to implement using a pre-set prefix prior to signing, while [EIP-712](./eip-712.md) is more complex to implement requiring the further implementations of a bespoke Solidity-inspired type system, RLP-based encoding format, and custom keccak-based hashing scheme. **(2)** - - [EIP-191](./eip-191.md) produces more human-readable messages, while [EIP-712](./eip-712.md) creates signing outputs for machine consumption, with most wallets not displaying the payload to be signed in a manner friendly to humans. **(1)**![](../assets/eip-4361/signing.png) - - - [EIP-712](./eip-712.md) has the advantage of on-chain representation and on-chain verifiability, such as for their use in metatransactions, but this feature is not relevant for the specification's scope. **(2)** -- Why not use JWTs? Wallets don't support JWTs. The keccak hash function is not assigned by IANA for use as a JOSE algorithm. **(2, 3)** -- Why not use YAML or YAML with exceptions? YAML is loose compared to ABNF, which can readily express character set limiting, required ordering, and strict whitespacing. **(2, 3)** - -### Out of Scope -The following concerns are out of scope for this version of the specification to define: -- Additional authentication not based on Ethereum addresses. -- Authorization to server resources. -- Interpretation of the URIs in the `resources` term as claims or other resources. -- The specific mechanisms to ensure domain-binding. -- The specific mechanisms to generate nonces and evaluation of their appropriateness. -- Protocols for use without TLS connections. - -### Considerations for Forwards Compatibility -The following items are considered for future support in either through an iteration of this specification or new work items using this specification as a dependency. -- Possible support for Decentralized Identifiers and Verifiable Credentials. -- Possible cross-chain support. -- Possible SIOPv2 support. -- Possible future support for [EIP-712](./eip-712.md). -- Version interpretation rules, e.g., sign with minor revision greater than understood, but not greater major version. - -## Backwards Compatibility -- Most wallet implementations already support [EIP-191](./eip-191.md), so this is used as a base pattern with additional features. -- Requirements were gathered from existing implementations of similar sign-in workflows, including statements to allow the user to accept a Terms of Service, nonces for replay protection, and inclusion of the Ethereum address itself in the message. - -## Reference Implementation -A reference implementation is available [here](../assets/eip-4361/example.js). - -## Security Considerations - -#### Identifier reuse -- Towards perfect privacy, it would be ideal to use a new uncorrelated identifier (e.g., Ethereum address) per digital interaction, selectively disclosing the information required and no more. -- This concern is less relevant to certain user demographics who are likely to be early adopters of this specification, such as those who manage an Ethereum address and/or ENS names intentionally associated with their public presence. These users often prefer identifier reuse to maintain a single correlated identity across many services. -- This consideration will become increasingly important with mainstream adoption. There are several ways to move towards this model, such as using HD wallets, signed delegations, and zero-knowledge proofs. However, these approaches are out of scope for this specification and better suited for follow-on specifications. - -#### Key management -- Sign-In with Ethereum gives users control through their keys. This is additional responsibility that mainstream users may not be accustomed to accepting, and key management is a hard problem especially for individuals. For example, there is no "forgot password" button as centralized identity providers commonly implement. -- Early adopters of this specification are likely to be already adept at key management, so this consideration becomes more relevant with mainstream adoption. -- Certain wallets can use smart contracts and multisigs to provide an enhanced user experiences with respect to key usage and key recovery, and these can be supported via [EIP-1271](./eip-1271.md) signing. - -#### Wallet and relying party combined security -- Both the wallet and relying party have to implement this specification for improved security to the end user. Specifically, the wallet MUST confirm that the message is for the correct `domain` or provide the user means to do so manually (such as instructions to visually confirming the correct domain in a TLS-protected website prior to connecting via QR code or deeplink), otherwise the user is subject to phishing attacks. - -#### Minimizing wallet and server interaction -- In some implementions of wallet sign-in workflows, the server first sends parameters of the `message` to the wallet. Others generate the message for signing entirely in the client side (e.g., dapps). The latter approach without initial server interaction SHOULD be preferred when there is a user privacy advantage by minimizing wallet-server interaction. Often, the backend server first produces a `nonce` to prevent replay attacks, which it verifies after signing. Privacy-preserving alternatives are suggested in the next section on preventing replay attacks. -- Before the wallet presents the message signing request to the user, it MAY consult the server for the proper contents of the message to be signed, such as an acceptable `nonce` or requested set of `resources`. When communicating to the server, the wallet SHOULD take precautions to protect user privacy by mitigating user information revealed as much as possible. -- Prior to signing, the wallet MAY consult the user for preferences, such as the selection of one `address` out of many, or a preferred ENS name out of many. - -#### Preventing replay attacks -- A `nonce` SHOULD be selected per session initiation with enough entropy to prevent replay attacks, a man-in-the-middle attack in which an attacker is able to capture the user's signature and resend it to establish a new session for themselves. -- Implementers MAY consider using privacy-preserving yet widely-available `nonce` values, such as one derived from a recent Ethereum block hash or a recent Unix timestamp. - -#### Verification of domain binding -- Wallets MUST check that the `domain` matches the actual signing request source. -- This value SHOULD be checked against a trusted data source such as the browser window or over another protocol. - -#### Channel security -- For web-based applications, all communications SHOULD use HTTPS to prevent man-in-the-middle attacks on the message signing. -- When using protocols other than HTTPS, all communications SHOULD be protected with proper techniques to maintain confidentiality, data integrity, and sender/receiver authenticity. - -#### Session invalidation -There are several cases where an implementer SHOULD check for state changes as they relate to sessions. - -- If an [EIP-1271](./eip-1271.md) implementation or dependent data changes the signature computation, the server SHOULD invalidate sessions appropriately. -- If any resources specified in `resources` change, the server SHOULD invalidate sessions appropriately. However, the interpretation of `resources` is out of scope of this specification. - -#### Maximum lengths for ABNF terms -- While this specification does not contain normative requirements around maximum string lengths, implementers SHOULD choose maximum lengths for terms that strike a balance across the prevention of denial of service attacks, support for arbitrary use cases, and user readability. - -## Copyright Waiver -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4361.md diff --git a/EIPS/eip-4393.md b/EIPS/eip-4393.md index 5ecd4f11f029d0..2f9b3257d678eb 100644 --- a/EIPS/eip-4393.md +++ b/EIPS/eip-4393.md @@ -1,363 +1,7 @@ --- eip: 4393 -title: Micropayments for NFTs and Multi Tokens -description: An interface for tip tokens that allows tipping to holders of NFTs and multi tokens -author: Jules Lai (@julesl23) -discussions-to: https://ethereum-magicians.org/t/eip-proposal-micropayments-standard-for-nfts-and-multi-tokens/7366 -status: Draft -type: Standards Track category: ERC -created: 2021-10-24 -requires: 165, 721, 1155 +status: Moved --- -## Abstract - -This standard outlines a smart contract interface for tipping to non-fungible and multi tokens. Holders of the tokens are able to withdraw the tips as [EIP-20](./eip-20.md) rewards. - -For the purpose of this EIP, a micropayment is termed as a financial transaction that involves usually a small sum of money called "tips" that are sent to specific [EIP-721](./eip-721.md) NFTs and [EIP-1155](./eip-1155.md) multi tokens, as rewards to their holders. A holder (also referred to as controller) is used as a more generic term for owner, as NFTs may represent non-digital assets such as services. - -## Motivation - -A cheap way to send tips to any type of NFT or multi token. This can be achieved by gas optimising the tip token contract and sending the tips in batches using the `tipBatch` function from the interface. - -To make it easy to implement into dapps a tipping service to reward the NFT and multi token holders. Allows for fairer distribution of revenue back to NFT holders from the user community. - -To make the interface as minimal as possible in order to allow adoption into many different use cases. - -Some use cases include: - -- In game purchases and other virtual goods - -- Tipping messages, posts, music and video content - -- Donations/crowdfunding - -- Distribution of royalties - -- Pay per click advertising - -- Incentivising use of services - -- Reward cards and coupons - -These can all leverage the security, immediacy and transparency of blockchain. - -## Specification - -This standard proposal outlines a generalised way to allow tipping via implementation of an `ITipToken` interface. The interface is intentionally kept to a minimum in order to allow for maximum use cases. - -Smart contracts implementing this EIP standard MUST implement all of the functions in this EIP interface. MUST also emit the events specified in the interface so that a complete state of the tip token contract can be derived from the events emitted alone. - -Smart contracts implementing this EIP standard MUST implement the [EIP-165](./eip-165.md) supportsInterface function and MUST return the constant value true if 0xE47A7022 is passed through the interfaceID argument. Note that revert in this document MAY mean a require, throw (not recommended as depreciated) or revert solidity statement with or without error messages. - -Note that, nft (or NFT in caps) in the code and as mentioned in this document, MAY also refer to an EIP-1155 fungible token. - -```solidity -interface ITipToken { - /** - @dev This emits when the tip token implementation approves the address - of an NFT for tipping. - The holders of the 'nft' are approved to receive rewards. - When an NFT Transfer event emits, this also indicates that the approved - addresses for that NFT (if any) is reset to none. - Note: the ERC-165 identifier for this interface is 0x985A3267. - */ - event ApprovalForNFT( - address[] holders, - address indexed nft, - uint256 indexed id, - bool approved - ); - - /** - @dev This emits when a user has deposited an ERC-20 compatible token to - the tip token's contract address or to an external address. - This also indicates that the deposit has been exchanged for an - amount of tip tokens - */ - event Deposit( - address indexed user, - address indexed rewardToken, - uint256 amount, - uint256 tipTokenAmount - ); - - /** - @dev This emits when a holder withdraws an amount of ERC-20 compatible - reward. This reward comes from the tip token's contract address or from - an external address, depending on the tip token implementation - */ - event WithdrawReward( - address indexed holder, - address indexed rewardToken, - uint256 amount - ); - - /** - @dev This emits when the tip token constructor or initialize method is - executed. - Importantly the ERC-20 compatible token 'rewardToken_' to use as reward - to NFT holders is set at this time and remains the same throughout the - lifetime of the tip token contract. - The 'rewardToken_' and 'tipToken_' MAY be the same. - */ - event InitializeTipToken( - address indexed tipToken_, - address indexed rewardToken_, - address owner_ - ); - - /** - @dev This emits every time a user tips an NFT holder. - Also includes the reward token address and the reward token amount that - will be held pending until the holder withdraws the reward tokens. - */ - event Tip( - address indexed user, - address[] holder, - address indexed nft, - uint256 id, - uint256 amount, - address rewardToken, - uint256[] rewardTokenAmount - ); - - /** - @notice Enable or disable approval for tipping for a single NFT held - by a holder or a multi token shared by holders - @dev MUST revert if calling nft's supportsInterface does not return - true for either IERC721 or IERC1155. - MUST revert if any of the 'holders' is the zero address. - MUST revert if 'nft' has not approved the tip token contract address as operator. - MUST emit the 'ApprovalForNFT' event to reflect approval or not approval. - @param holders The holders of the NFT (NFT controllers) - @param nft The NFT contract address - @param id The NFT token id - @param approved True if the 'holder' is approved, false to revoke approval - */ - function setApprovalForNFT( - address[] calldata holders, - address nft, - uint256 id, - bool approved - ) external; - - /** - @notice Checks if 'holder' and 'nft' with token 'id' have been approved - by setApprovalForNFT - @dev This does not check that the holder of the NFT has changed. That is - left to the implementer to detect events for change of ownership and to - take appropriate action - @param holder The holder of the NFT (NFT controller) - @param nft The NFT contract address - @param id The NFT token id - @return True if 'holder' and 'nft' with token 'id' have previously been - approved by the tip token contract - */ - function isApprovalForNFT( - address holder, - address nft, - uint256 id - ) external returns (bool); - - /** - @notice Sends tip from msg.sender to holder of a single NFT or - to shared holders of a multi token - @dev If 'nft' has not been approved for tipping, MUST revert - MUST revert if 'nft' is zero address. - MUST burn the tip 'amount' to the 'holder' and send the reward to - an account pending for the holder(s). - If 'nft' is a multi token that has multiple holders then each holder - MUST receive tip amount in proportion of their balance of multi tokens - MUST emit the 'Tip' event to reflect the amounts that msg.sender tipped - to holder(s) of 'nft'. - @param nft The NFT contract address - @param id The NFT token id - @param amount Amount of tip tokens to send to the holder of the NFT - */ - function tip( - address nft, - uint256 id, - uint256 amount - ) external; - - /** - @notice Sends a batch of tips to holders of 'nfts' for gas efficiency - @dev If NFT has not been approved for tipping, revert - MUST revert if the input arguments lengths are not all the same - MUST revert if any of the user addresses are zero - MUST revert the whole batch if there are any errors - MUST emit the 'Tip' events so that the state of the amounts sent to - each holder and for which nft and from whom, can be reconstructed. - @param users User accounts to tip from - @param nfts The NFT contract addresses whose holders to tip to - @param ids The NFT token ids that uniquely identifies the 'nfts' - @param amounts Amount of tip tokens to send to the holders of the NFTs - */ - function tipBatch( - address[] calldata users, - address[] calldata nfts, - uint256[] calldata ids, - uint256[] calldata amounts - ) external; - - /** - @notice Deposit an ERC-20 compatible token in exchange for tip tokens - @dev The price of tip tokens can be different for each deposit as - the amount of reward token sent ultimately is a ratio of the - amount of tip tokens to tip over the user's tip tokens balance available - multiplied by the user's deposit balance. - The deposited tokens can be held in the tip tokens contract account or - in an external escrow. This will depend on the tip token implementation. - Each tip token contract MUST handle only one type of ERC-20 compatible - reward for deposits. - This token address SHOULD be passed in to the tip token constructor or - initialize method. SHOULD revert if ERC-20 reward for deposits is - zero address. - MUST emit the 'Deposit' event that shows the user, deposited token details - and amount of tip tokens minted in exchange - @param user The user account - @param amount Amount of ERC-20 token to deposit in exchange for tip tokens. - This deposit is to be used later as the reward token - */ - function deposit(address user, uint256 amount) external payable; - - /** - @notice An NFT holder can withdraw their tips as an ERC-20 compatible - reward at a time of their choosing - @dev MUST revert if not enough balance pending available to withdraw. - MUST send 'amount' to msg.sender account (the holder) - MUST reduce the balance of reward tokens pending by the 'amount' withdrawn. - MUST emit the 'WithdrawReward' event to show the holder who withdrew, the reward - token address and 'amount' - @param amount Amount of ERC-20 token to withdraw as a reward - */ - function withdrawReward(uint256 amount) external payable; - - /** - @notice MUST have identical behaviour to ERC-20 balanceOf and is the amount - of tip tokens held by 'user' - @param user The user account - @return The balance of tip tokens held by user - */ - function balanceOf(address user) external view returns (uint256); - - /** - @notice The balance of deposit available to become rewards when - user sends the tips - @param user The user account - @return The remaining balance of the ERC-20 compatible token deposited - */ - function balanceDepositOf(address user) external view returns (uint256); - - /** - @notice The amount of reward token owed to 'holder' - @dev The pending tokens can come from the tip token contract account - or from an external escrow, depending on tip token implementation - @param holder The holder of NFT(s) (NFT controller) - @return The amount of reward tokens owed to the holder from tipping - */ - function rewardPendingOf(address holder) external view returns (uint256); -} -``` - -### Tipping and rewards to holders - -A user first deposits a compatible EIP-20 to the tip token contract that is then held (less any agreed fee) in escrow, in exchange for tip tokens. These tip tokens can then be sent by the user to NFTs and multi tokens (that have been approved by the tip token contract for tipping) to be redeemed for the original EIP-20 deposits on withdrawal by the holders as rewards. - -### Tip Token transfer and value calculations - -Tip token values are exchanged with EIP-20 deposits and vice-versa. It is left to the tip token implementer to decide on the price of a tip token and hence how much tip to mint in exchange for the EIP-20 deposited. One possibility is to have fixed conversion rates per geographical region so that users from poorer countries are able to send the same number of tips as those from richer nations for the same level of appreciation for content/assets etc. Hence, not skewed by average wealth when it comes to analytics to discover what NFTs are actually popular, allowing creators to have a level playing field. - -Whenever a user sends a tip, an equivalent value of deposited EIP-20 MUST be transferred to a pending account for the NFT or multi token holder, and the tip tokens sent MUST be burnt. This equivalent value is calculated using a simple formula: - -_total user balance of EIP-20 deposit _ tip amount / total user balance of tip tokens\* - -Thus adding \*free\* tips to a user's balance of tips for example, simply dilutes the overall value of each tip for that user, as collectively they still refer to the same amount of EIP-20 deposited. - -Note if the tip token contract inherits from an EIP-20, tips can be transferred from one user to another directly. The deposit amount would be already in the tip token contract (or an external escrow account) so only tip token contract's internal mapping of user account to deposit balances needs to be updated. It is RECOMMENDED that the tip amount be burnt from user A and then minted back to user B in the amount that keeps user B's average EIP-20 deposited value per tip the same, so that the value of the tip does not fluctuate in the process of tipping. - -If not inheriting from EIP-20, then minting the tip tokens MUST emit `event Transfer(address indexed from, address indexed to, uint256 value)` where sender is the zero address for a mint and to is the zero address for a burn. The Transfer event MUST be the same signature as the Transfer function in the `IERC20` interface. - -### Royalty distribution - -EIP-1155 allows for shared holders of a token id. Imagine a scenario where an article represented by an NFT was written by multiple contributors. Here, each contributor is a holder and the fractional sharing percentage between them can be represented by the balance that each holds in the EIP-1155 token id. So for two holders A and B of EIP-1155 token 1, if holder A's balance is 25 and holder B's is 75 then any tip sent to token 1 would distribute 25% of the reward pending to holder A and the remaining 75% pending to holder B. - -Here is an example implementation of ITipToken contract data structures: - -```solidity - /// Mapping from NFT/multi token to token id to holder(s) - mapping(address => mapping(uint256 => address[])) private _tokenIdToHolders; - - /// Mapping from user to user's deposit balance - mapping(address => uint256) private _depositBalances; - - /// Mapping from holder to holder's reward pending amount - mapping(address => uint256) private _rewardsPending; -``` - -This copes with EIP-721 contracts that must have unique token ids and single holders (to be compliant with the standard), and EIP-1155 contracts that can have multiple token ids and multiple holders per instance. The `tip` function implementation would then access `_tokenIdToHolders` via indices NFT/multi token address and token id to distribute to holder's or holders' `_rewardsPending`. - -For scenarios where royalties are to be distributed to holders directly, then implementation of the `tip` method of `ITipToken` contract MAY send the royalty amount straight from the user's account to the holder of a single NFT or to the shared holders of a multi token, less an optional agreed fee. In this case, the tip token type is the reward token. - -### Caveats - -To keep the `ITipToken` interface simple and general purpose, each tip token contract MUST use one EIP-20 compatible deposit type at a time. If tipping is required to support many EIP-20 deposits then each tip token contract MUST be deployed separately per EIP-20 compatible type required. Thus, if tipping is required from both ETH and BTC wrapper EIP-20 deposits then the tip token contract is deployed twice. The tip token contract's constructor is REQUIRED to pass in the address of the EIP-20 token supported for the deposits for the particular tip token contract. Or in the case for upgradeable tip token contracts, an initialize method is REQUIRED to pass in the EIP-20 token address. - -This EIP does not provide details for where the EIP-20 reward deposits are held. It MUST be available at the time a holder withdraws the rewards that they are owed. A RECOMMENDED implementation would be to keep the deposits locked in the tip token contract address. By keeping a mapping structure that records the balances pending to holders then the -deposits can remain where they are when a user tips, and only transferred out to a holder's address when a holder withdraws it as their reward. - -This standard does not specify the type of EIP-20 compatible deposits allowed. Indeed, could be tip tokens themselves. But it is RECOMMENDED that balances of the deposits be checked after transfer to find out the exact amount deposited to keep internal accounting consistent. In case, for example, the EIP-20 contract takes fees and hence reduces the actual amount deposited. - -This standard does not specify any functionality for refunds for deposits nor for tip tokens sent, it is left to the implementor to add this to their smart contract(s). The reasoning for this is to keep the interface light and not to enforce upon implementors the need for refunds but to leave that as a choice. - -### Minimising Gas Costs - -By caching tips off-chain and then batching them up to call the `tipBatch` method of the ITipToken interface then essentially the cost of initialising transactions is paid once rather than once per tip. Plus, further gas savings can be made off-chain if multiple tips sent by the same user to the same NFT token are accumulated together and sent as one entry in the batch. - -Further savings can be made by grouping users together sending to the same NFT, so that checking the validity of the NFT and whether it is an EIP-721 or EIP-1155, is performed once for each group. - -Clever ways to minimise on-chain state updating of the deposit balances for each user and the reward balances of each holder, can help further to minimise the gas costs when sending in a batch if the batch is ordered beforehand. For example, can avoid the checks if the next NFT in the batch is the same. This left to the tip token contract implementer. Whatever optimisation is applied, it MUST still allow information of which account tipped which account and for what NFT to be reconstructed from the Tip and the TipBatch events emitted. - -## Rationale - -### Simplicity - -ITipToken interface uses a minimal number of functions, in order to keep its use as general purpose as possible, whilst there being enough to guide implementation that fulfils its purpose for micropayments to NFT holders. - -### Use of NFTs - -Each NFT is a unique non-fungible token digital asset stored on the blockchain that are uniquely identified by its address and token id. It's truth burnt using cryptographic hashing on a secure blockchain means that it serves as an anchor for linking with a unique digital asset, service or other contractual agreement. Such use cases may include (but only really limited by imagination and acceptance): - -- Digital art, collectibles, music, video, licenses and certificates, event tickets, ENS names, gaming items, objects in metaverses, proof of authenticity of physical items, service agreements etc. - -This mechanism allows consumers of the NFT a secure way to easily tip and reward the NFT holder. - -### New Business Models - -To take the music use case for example. Traditionally since the industry transitioned from audio distributed on physical medium such as CDs, to an online digital distribution model via streaming, the music industry has been controlled by oligopolies that served to help in the transition. They operate a fixed subscription model and from that they set the amount of royalty distribution to content creators; such as the singers, musicians etc. Using tip tokens represent an additional way for fans of music to reward the content creators. Each song or track is represented by an NFT and fans are able to tip the song (hence the NFT) that they like, and in turn the content creators of the NFT are able to receive the EIP-20 rewards that the tips were bought for. A fan led music industry with decentralisation and tokenisation is expected to bring new revenue, and bring fans and content creators closer together. - -Across the board in other industries a similar ethos can be applied where third party controllers move to a more facilitating role rather than a monetary controlling role that exists today. - -### Guaranteed audit trail - -As the Ethereum ecosystem continues to grow, many dapps are relying on traditional databases and explorer API services to retrieve and categorize data. This EIP standard guarantees that event logs emitted by the smart contract MUST provide enough data to create an accurate record of all current tip token and EIP-20 reward balances. A database or explorer can provide indexed and categorized searches of every tip token and reward sent to NFT holders from the events emitted by any tip token contract that implements this standard. Thus, the state of the tip token contract can be reconstructed from the events emitted alone. - -## Backwards Compatibility - -A tip token contract can be fully compatible with EIP-20 specification and inherit some functions such as transfer if the tokens are allowed to be sent directly to other users. Note that balanceOf has been adopted and MUST be the number of tips held by a user's address. If inheriting from, for example, OpenZeppelin's implementation of EIP-20 token then their contract is responsible for maintaining the balance of tip token. Therefore, tip token balanceOf function SHOULD simply directly call the parent (super) contract's balanceOf function. - -What hasn't been carried over to tip token standard, is the ability for a spender of other users' tips. For the moment, this standard does not foresee a need for this. - -This EIP does not stress a need for tip token secondary markets or other use cases where identifying the tip token type with names rather than addresses might be useful, so these functions were left out of the ITipToken interface and is the remit for implementers. - -## Security Considerations - -Though it is RECOMMENDED that users' deposits are kept locked in the tip token contract or external escrow account, and SHOULD NOT be used for anything but the rewards for holders, this cannot be enforced. This standard stipulates that the rewards MUST be available for when holders withdraw their rewards from the pool of deposits. - -Before any users can tip an NFT, the holder of the NFT has to give their approval for tipping from the tip token contract. This standard stipulates that holders of the NFTs receive the rewards. It SHOULD be clear in the tip token contract code that it does so, without obfuscation to where the rewards go. Any fee charges SHOULD be made obvious to users before acceptance of their deposit. There is a risk that rogue implementers may attempt to \*hijack\* potential tip income streams for their own purposes. But additionally the number and frequency of transactions of the tipping process should make this type of fraud quicker to be found out. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4393.md diff --git a/EIPS/eip-4396.md b/EIPS/eip-4396.md index da534ddaf36a3a..533c3143355677 100644 --- a/EIPS/eip-4396.md +++ b/EIPS/eip-4396.md @@ -150,7 +150,7 @@ Under PoS, each slot has a [fixed assigned timestamp](https://github.com/ethereu ### Suppressing Base Fee Increases As discussed in the rationale, a high value for `MAX_GAS_TARGET_PERCENT` during times of many offline block proposers results in a small remaining signal space for genuine demand increases that should result in base fee increases. This in turn decreases the cost for block proposers for suppresing these base fee increases, instead forcing the fallback to a first-price priority fee auction. -While the arguments of incentive incompatibility for base fee suppression of the the base EIP-1559 case still apply here, with a decreasing cost of this individually irrational behavior the risk for overriding psychological factors becomes more significant. +While the arguments of incentive incompatibility for base fee suppression of the base EIP-1559 case still apply here, with a decreasing cost of this individually irrational behavior the risk for overriding psychological factors becomes more significant. Even in such a case the system degradation would however be graceful, as it would only temporarily suspend the base fee burn. As soon as the missing block proposers would come back online, the system would return to its ordinary EIP-1559 equilibrium. diff --git a/EIPS/eip-4400.md b/EIPS/eip-4400.md index 500ff8ff26002d..aa065c239a8db7 100644 --- a/EIPS/eip-4400.md +++ b/EIPS/eip-4400.md @@ -1,113 +1,7 @@ --- eip: 4400 -title: EIP-721 Consumable Extension -description: Interface extension for EIP-721 consumer role -author: Daniel Ivanov (@Daniel-K-Ivanov), George Spasov (@Perseverance) -discussions-to: https://ethereum-magicians.org/t/EIP-4400-EIP721consumer-extension/7371 -status: Final -type: Standards Track category: ERC -created: 2021-10-30 -requires: 165, 721 +status: Moved --- -## Abstract - -This specification defines standard functions outlining a `consumer` role for instance(s) of [EIP-721](./eip-721.md). An implementation allows reading the current `consumer` for a given NFT (`tokenId`) along with a standardized event for when an `consumer` has changed. The proposal depends on and extends the existing [EIP-721](./eip-721.md). - -## Motivation - -Many [EIP-721](./eip-721.md) contracts introduce their own custom role that grants permissions for utilising/consuming a given NFT instance. The need for that role stems from the fact that other than owning the NFT instance, there are other actions that can be performed on an NFT. For example, various metaverses use `operator` / `contributor` roles for Land (EIP-721), so that owners of the land can authorise other addresses to deploy scenes to them (f.e. commissioning a service company to develop a scene). - -It is common for NFTs to have utility other than ownership. That being said, it requires a separate standardized consumer role, allowing compatibility with user interfaces and contracts, managing those contracts. - -Having a `consumer` role will enable protocols to integrate and build on top of dApps that issue EIP-721 tokens. One example is the creation of generic/universal NFT renting marketplaces. - -Example of kinds of contracts and applications that can benefit from this standard are: -- metaverses that have land and other types of digital assets in those metaverses (scene deployment on land, renting land / characters / clothes / passes to events etc.) -- NFT-based yield-farming. Adopting the standard enables the "staker" (owner of the NFT) to have access to the utility benefits even after transferring his NFT to the staking contract - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Every contract compliant to the `EIP721Consumable` extension MUST implement the `IEIP721Consumable` interface. The **consumer extension** is OPTIONAL for EIP-721 contracts. - -```solidity -/// @title EIP-721 Consumer Role extension -/// Note: the EIP-165 identifier for this interface is 0x953c8dfa -interface IEIP721Consumable /* is EIP721 */ { - - /// @notice Emitted when `owner` changes the `consumer` of an NFT - /// The zero address for consumer indicates that there is no consumer address - /// When a Transfer event emits, this also indicates that the consumer address - /// for that NFT (if any) is set to none - event ConsumerChanged(address indexed owner, address indexed consumer, uint256 indexed tokenId); - - /// @notice Get the consumer address of an NFT - /// @dev The zero address indicates that there is no consumer - /// Throws if `_tokenId` is not a valid NFT - /// @param _tokenId The NFT to get the consumer address for - /// @return The consumer address for this NFT, or the zero address if there is none - function consumerOf(uint256 _tokenId) view external returns (address); - - /// @notice Change or reaffirm the consumer address for an NFT - /// @dev The zero address indicates there is no consumer address - /// Throws unless `msg.sender` is the current NFT owner, an authorised - /// operator of the current owner or approved address - /// Throws if `_tokenId` is not valid NFT - /// @param _consumer The new consumer of the NFT - function changeConsumer(address _consumer, uint256 _tokenId) external; -} -``` - -Every contract implementing the `EIP721Consumable` extension is free to define the permissions of a `consumer` (e.g. what are consumers allowed to do within their system) with only one exception - consumers MUST NOT be considered owners, authorised operators or approved addresses as per the EIP-721 specification. Thus, they MUST NOT be able to execute transfers & approvals. - -The `consumerOf(uint256 _tokenId)` function MAY be implemented as `pure` or `view`. - -The `changeConsumer(address _consumer, uint256 _tokenId)` function MAY be implemented as `public` or `external`. - -The `ConsumerChanged` event MUST be emitted when a consumer is changed. - -On every `transfer`, the consumer MUST be changed to a default address. It is RECOMMENDED for implementors to use `address(0)` as that default address. - -The `supportsInterface` method MUST return `true` when called with `0x953c8dfa`. - -## Rationale - -Key factors influencing the standard: - -- Keeping the number of functions in the interfaces to a minimum to prevent contract bloat -- Simplicity -- Gas Efficiency -- Not reusing or overloading other already existing roles (e.g. owners, operators, approved addresses) - -### Name - -The chosen name resonates with the purpose of its existence. Consumers can be considered entities that utilise the token instances, without necessarily having ownership rights to it. - -The other name for the role that was considered was `operator`, however it is already defined and used within the `EIP-721` standard. - -### Restriction on the Permissions - -There are numerous use-cases where a distinct role for NFTs is required that MUST NOT have owner permissions. A contract that implements the consumer role and grants ownership permissions to the consumer renders this standard pointless. - -## Backwards Compatibility - -This standard is compatible with current EIP-721 standards. There are no other standards that define a similar role for NFTs and the name (`consumer`) is not used by other EIP-721 related standards. - -## Test Cases - -Test cases are available in the reference implementation [here](../assets/eip-4400/test/erc721-consumable.ts). - -## Reference Implementation - -The reference implementation can be found [here](../assets/eip-4400/contracts/ERC721Consumable.sol). - -## Security Considerations - -Implementors of the `EIP721Consumable` standard must consider thoroughly the permissions they give to `consumers`. Even if they implement the standard correctly and do not allow transfer/burning of NFTs, they might still provide permissions to the `consumers` that they might not want to provide otherwise and should be restricted to `owners` only. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4400.md diff --git a/EIPS/eip-4430.md b/EIPS/eip-4430.md index 48dc234bc00564..e8a6481a1cf3f5 100644 --- a/EIPS/eip-4430.md +++ b/EIPS/eip-4430.md @@ -1,145 +1,7 @@ --- eip: 4430 -title: Described Transactions -description: A technique for contracts to provide a human-readable description of a transaction's side-effects. -author: Richard Moore (@ricmoo), Nick Johnson (@arachnid) -discussions-to: https://ethereum-magicians.org/t/discussion-eip-4430-described-transactions/8762 -status: Stagnant -type: Standards Track category: ERC -created: 2021-11-07 +status: Moved --- -## Abstract - -Use a contract method to provide *virtual functions* which can generate -a human-readable description at the same time as the machine-readable -bytecode, allowing the user to agree to the human-readable component -in a UI while the machine can execute the bytecode once accepted. - - -## Motivation - -When using an Ethereum Wallet (e.g. MetaMask, Clef, Hardware Wallets) -users must accept a transaction before it can be submitted (or the user -may decline). - -Due to the complexity of Ethereum transactions, wallets are very limited -in their ability to provide insight into the effects of a transaction -that the user is approving; outside special-cased support for common -transactions such as ERC20 transfers, this often amounts to asking the -user to sign an opaque blob of binary data. - -This EIP presents a method for dapp developers to enable a more comfortable -user experience by providing wallets with a means to generate a better -description about what the contract claims will happen. - -It does not address malicious contracts which wish to lie, it only addresses -honest contracts that want to make their user's life better. We believe -that this is a reasonable security model, as transaction descriptions can be -audited at the same time as contract code, allowing auditors and code -reviewers to check that transaction descriptions are accurate as part of -their review. - - -## Specification - -The **description** (a string) and the matching **execcode** (bytecode) -are generated simultaneously by evaluating the method on a contract: - -```solidity -function eipXXXDescribe(bytes inputs, bytes32 reserved) view returns (string description, bytes execcode) -``` - -The human-readable **description** can be shown in any client which supports -user interaction for approval, while the **execcode** is the data that -should be included in a transaction to the contract to perform that operation. - -The method must be executable in a static context, (i.e. any side effects, -such as logX, sstore, etc.), including through indirect calls may be ignored. - -During evaluation, the `ADDRESS` (i.e. `to`), `CALLER` (i.e. `from`), `VALUE`, -and `GASPRICE` must be the same as the values for the transaction being -described, so that the code generating the description can rely on them. - -When executing the bytecode, best efforts should be made to ensure `BLOCKHASH`, -`NUMBER`, `TIMESTAMP` and `DIFFICULTY` match the `"latest"` block. The -`COINBASE` should be the zero address. - -The method may revert, in which case the signing must be aborted. - - -## Rationale - -### Meta Description - -There have been many attempts to solve this problem, many of which attempt -to examine the encoded transaction data or message data directly. - -In many cases, the information that would be necessary for a meaningful -description is not present in the final encoded transaction data or message -data. - -Instead this EIP uses an indirect description of the data. - -For example, the `commit(bytes32)` method of ENS places a commitment -**hash** on-chain. The hash contains the **blinded** name and address; -since the name is blinded, the encoded data (i.e. the hash) no longer -contains the original values and is insufficient to access the necessary -values to be included in a description. - -By instead describing the commitment indirectly (with the original information -intact: NAME, ADDRESS and SECRET) a meaningful description can be computed -(e.g. "commit to NAME for ADDRESS (with SECRET)") and the matching data can -be computed (i.e. `commit(hash(name, owner, secret))`). - -This technique of blinded data will become much more popular with L2 -solutions, which use blinding not necessarily for privacy, but for -compression. - -### Entangling the Contract Address - -To prevent signed data being used across contracts, the contract address -is entanlged into both the transaction implicitly via the `to` field. - - -### Alternatives - -- NatSpec and company are a class of more complex languages that attempt to describe the encoded data directly. Because of the language complexity they often end up being quite large requiring entire runtime environments with ample processing power and memory, as well as additional sandboxing to reduce security concerns. One goal of this is to reduce the complexity to something that could execute on hardware wallets and other simple wallets. These also describe the data directly, which in many cases (such as blinded data), cannot adequately describe the data at all - -- Custom Languages; due to the complexity of Ethereum transactions, any language used would require a lot of expressiveness and re-inventing the wheel. The EVM already exists (it may not be ideal), but it is there and can handle everything necessary. - -- Format Strings (e.g. Trustless Signing UI Protocol; format strings can only operate on the class of regular languages, which in many cases is insufficient to describe an Ethereum transaction. This was an issue quite often during early attempts at solving this problem. - -- The signTypedData [EIP-712](./eip-712.md) has many parallels to what this EIP aims to solve - - -## Backwards Compatibility - -This does not affect backwards compatibility. - - -## Reference Implementation - -I will add deployed examples by address and chain ID. - - -## Security Considerations - -### Escaping Text - -Wallets must be careful when displaying text provided by contracts and proper -efforts must be taken to sanitize it, for example, be sure to consider: - -- HTML could be embedded to attempt to trick web-based wallets into executing code using the script tag (possibly uploading any private keys to a server) -- In general, extreme care must be used when rendering HTML; consider the ENS names `not-ricmoo.eth` or ` ricmoo.eth`, which if rendered without care would appear as `ricmoo.eth`, which it is not -- Other marks which require escaping could be included, such as quotes (`"`), formatting (`\n` (new line), `\f` (form feed), `\t` (tab), any of many non-standard whitespaces), back-slassh (`\`) -- UTF-8 has had bugs in the past which could allow arbitrary code execution and crashing renderers; consider using the UTF-8 replacement character (or *something*) for code-points outside common planes or common sub-sets within planes -- Homoglyphs attacks -- Right-to-left mark may affect rendering -- Many other things, deplnding on your environment - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4430.md diff --git a/EIPS/eip-4494.md b/EIPS/eip-4494.md index 8da81a96865548..520bdfdceb4fb0 100644 --- a/EIPS/eip-4494.md +++ b/EIPS/eip-4494.md @@ -1,207 +1,7 @@ --- eip: 4494 -title: Permit for ERC-721 NFTs -description: ERC-712-singed approvals for ERC-721 NFTs -author: Simon Fremaux (@dievardump), William Schwab (@wschwab) -discussions-to: https://ethereum-magicians.org/t/eip-extending-erc2612-style-permits-to-erc721-nfts/7519/2 -status: Draft -type: Standards Track category: ERC -created: 2021-11-25 -requires: 165, 712, 721 +status: Moved --- -## Abstract -The "Permit" approval flow outlined in [ERC-2612](./eip-2612.md) has proven a very valuable advancement in UX by creating gasless approvals for ERC20 tokens. This EIP extends the pattern to ERC-721 NFTs. This EIP borrows heavily from ERC-2612. - -This requires a separate EIP due to the difference in structure between ERC-20 and ERC-721 tokens. While ERC-20 permits use value (the amount of the ERC-20 token being approved) and a nonce based on the owner's address, ERC-721 permits focus on the `tokenId` of the NFT and increment nonce based on the transfers of the NFT. - -## Motivation -The permit structure outlined in [ERC-2612](./eip-2612.md) allows for a signed message (structured as outlined in [ERC-712](./eip-712.md)) to be used in order to create an approval. Whereas the normal approval-based pull flow generally involves two transactions, one to approve a contract and a second for the contract to pull the asset, which is poor UX and often confuses new users, a permit-style flow only requires signing a message and a transaction. Additional information can be found in [ERC-2612](./eip-2612.md). - -[ERC-2612](./eip-2612.md) only outlines a permit architecture for ERC-20 tokens. This ERC proposes an architecture for ERC-721 NFTs, which also contain an approve architecture that would benefit from a signed message-based approval flow. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Three new functions MUST be added to [ERC-721](./eip-721.md): -```solidity -pragma solidity 0.8.10; - -import "./IERC165.sol"; - -/// -/// @dev Interface for token permits for ERC-721 -/// -interface IERC4494 is IERC165 { - /// ERC165 bytes to add to interface array - set in parent contract - /// - /// _INTERFACE_ID_ERC4494 = 0x5604e225 - - /// @notice Function to approve by way of owner signature - /// @param spender the address to approve - /// @param tokenId the index of the NFT to approve the spender on - /// @param deadline a timestamp expiry for the permit - /// @param sig a traditional or EIP-2098 signature - function permit(address spender, uint256 tokenId, uint256 deadline, bytes memory sig) external; - /// @notice Returns the nonce of an NFT - useful for creating permits - /// @param tokenId the index of the NFT to get the nonce of - /// @return the uint256 representation of the nonce - function nonces(uint256 tokenId) external view returns(uint256); - /// @notice Returns the domain separator used in the encoding of the signature for permits, as defined by EIP-712 - /// @return the bytes32 domain separator - function DOMAIN_SEPARATOR() external view returns(bytes32); -} -``` -The semantics of which are as follows: - -For all addresses `spender`, `uint256`s `tokenId`, `deadline`, and `nonce`, and `bytes` `sig`, a call to `permit(spender, tokenId, deadline, sig)` MUST set `spender` as approved on `tokenId` as long as the owner of `tokenId` remains in possession of it, and MUST emit a corresponding `Approval` event, if and only if the following conditions are met: - -* the current blocktime is less than or equal to `deadline` -* the owner of the `tokenId` is not the zero address -* `nonces[tokenId]` is equal to `nonce` -* `sig` is a valid `secp256k1` or [EIP-2098](./eip-2098.md) signature from owner of the `tokenId`: -``` -keccak256(abi.encodePacked( - hex"1901", - DOMAIN_SEPARATOR, - keccak256(abi.encode( - keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"), - spender, - tokenId, - nonce, - deadline)) -)); -``` -where `DOMAIN_SEPARATOR` MUST be defined according to [EIP-712](./eip-712.md). The `DOMAIN_SEPARATOR` should be unique to the contract and chain to prevent replay attacks from other domains, and satisfy the requirements of EIP-712, but is otherwise unconstrained. A common choice for `DOMAIN_SEPARATOR` is: -``` -DOMAIN_SEPARATOR = keccak256( - abi.encode( - keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), - keccak256(bytes(name)), - keccak256(bytes(version)), - chainid, - address(this) -)); -``` -In other words, the message is the following ERC-712 typed structure: -```json -{ - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Permit": [ - { - "name": "spender", - "type": "address" - }, - { - "name": "tokenId", - "type": "uint256" - }, - { - "name": "nonce", - "type": "uint256" - }, - { - "name": "deadline", - "type": "uint256" - } - ], - "primaryType": "Permit", - "domain": { - "name": erc721name, - "version": version, - "chainId": chainid, - "verifyingContract": tokenAddress - }, - "message": { - "spender": spender, - "value": value, - "nonce": nonce, - "deadline": deadline - } -}} -``` -In addition: -* the `nonce` of a particular `tokenId` (`nonces[tokenId]`) MUST be incremented upon any transfer of the `tokenId` -* the `permit` function MUST check that the signer is not the zero address - -Note that nowhere in this definition do we refer to `msg.sender`. The caller of the `permit` function can be any address. - -This EIP requires [EIP-165](./eip-165.md). EIP165 is already required in [ERC-721](./eip-721.md), but is further necessary here in order to register the interface of this EIP. Doing so will allow easy verification if an NFT contract has implemented this EIP or not, enabling them to interact accordingly. The interface of this EIP (as defined in EIP-165) is `0x5604e225`. Contracts implementing this EIP MUST have the `supportsInterface` function return `true` when called with `0x5604e225`. - -## Rationale -The `permit` function is sufficient for enabling a `safeTransferFrom` transaction to be made without the need for an additional transaction. - -The format avoids any calls to unknown code. - -The `nonces` mapping is given for replay protection. - -A common use case of permit has a relayer submit a Permit on behalf of the owner. In this scenario, the relaying party is essentially given a free option to submit or withhold the Permit. If this is a cause of concern, the owner can limit the time a Permit is valid for by setting deadline to a value in the near future. The deadline argument can be set to uint(-1) to create Permits that effectively never expire. - -ERC-712 typed messages are included because of its use in [ERC-2612](./eip-2612.md), which in turn cites widespread adoption in many wallet providers. - -While ERC-2612 focuses on the value being approved, this EIP focuses on the `tokenId` of the NFT being approved via `permit`. This enables a flexibility that cannot be achieved with ERC-20 (or even [ERC-1155](./eip-1155.md)) tokens, enabling a single owner to give multiple permits on the same NFT. This is possible since each ERC-721 token is discrete (oftentimes referred to as non-fungible), which allows assertion that this token is still in the possession of the `owner` simply and conclusively. - -Whereas ERC-2612 splits signatures into their `v,r,s` components, this EIP opts to instead take a `bytes` array of variable length in order to support [EIP-2098](./eip-2098) signatures (64 bytes), which cannot be easily separated or reconstructed from `r,s,v` components (65 bytes). - -## Backwards Compatibility -There are already some ERC-721 contracts implementing a `permit`-style architecture, most notably Uniswap v3. - -Their implementation differs from the specification here in that: - * the `permit` architecture is based on `owner` - * the `nonce` is incremented at the time the `permit` is created - * the `permit` function must be called by the NFT owner, who is set as the `owner` - * the signature is split into `r,s,v` instead of `bytes` - - Rationale for differing on design decisions is detailed above. - -## Test Cases - -Basic test cases for the reference implementation can be found [here](https://github.com/dievardump/erc721-with-permits/tree/main/test). - -In general, test suites should assert at least the following about any implementation of this EIP: -* the nonce is incremented after each transfer -* `permit` approves the `spender` on the correct `tokenId` -* the permit cannot be used after the NFT is transferred -* an expired permit cannot be used - -## Reference Implementation - -A reference implementation has been set up [here](https://github.com/dievardump/erc721-with-permits). - -## Security Considerations - -Extra care should be taken when creating transfer functions in which `permit` and a transfer function can be used in one function to make sure that invalid permits cannot be used in any way. This is especially relevant for automated NFT platforms, in which a careless implementation can result in the compromise of a number of user assets. - -The remaining considerations have been copied from [ERC-2612](./eip-2612.md) with minor adaptation, and are equally relevant here: - -Though the signer of a `Permit` may have a certain party in mind to submit their transaction, another party can always front run this transaction and call `permit` before the intended party. The end result is the same for the `Permit` signer, however. - -Since the ecrecover precompile fails silently and just returns the zero address as `signer` when given malformed messages, it is important to ensure `ownerOf(tokenId) != address(0)` to avoid `permit` from creating an approval to any `tokenId` which does not have an approval set. - -Signed `Permit` messages are censorable. The relaying party can always choose to not submit the `Permit` after having received it, withholding the option to submit it. The `deadline` parameter is one mitigation to this. If the signing party holds ETH they can also just submit the `Permit` themselves, which can render previously signed `Permit`s invalid. - -The standard [ERC-20 race condition for approvals](https://swcregistry.io/docs/SWC-114) applies to `permit` as well. - -If the `DOMAIN_SEPARATOR` contains the `chainId` and is defined at contract deployment instead of reconstructed for every signature, there is a risk of possible replay attacks between chains in the event of a future chain split. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4494.md diff --git a/EIPS/eip-4519.md b/EIPS/eip-4519.md index b1743323f289e4..75822b42b22c49 100644 --- a/EIPS/eip-4519.md +++ b/EIPS/eip-4519.md @@ -1,225 +1,7 @@ --- eip: 4519 -title: Non-Fungible Tokens Tied to Physical Assets -description: Interface for non-fungible tokens representing physical assets that can generate or recover their own accounts and obey users. -author: Javier Arcenegui (@Hardblock-IMSE-CNM), Rosario Arjona (@RosarioArjona), Roberto Román , Iluminada Baturone (@lumi2018) -discussions-to: https://ethereum-magicians.org/t/new-proposal-of-smart-non-fungible-token/7677 -status: Final -type: Standards Track category: ERC -created: 2021-12-03 -requires: 165, 721 +status: Moved --- -## Abstract - -This EIP standardizes an interface for non-fungible tokens representing physical assets, such as Internet of Things (IoT) devices. These NFTs are tied to physical assets and can verify the authenticity of the tie. They can include an Ethereum address of the physical asset, permitting physical assets to sign messages and transactions. Physical assets can operate with an operating mode defined by its corresponding NFT. - -## Motivation - -This standard was developed because [EIP-721](./eip-721.md) only tracks ownership (not usage rights) and does not track the Ethereum addresses of the asset. The popularity of smart assets, such as IoT devices, is increasing. To permit secure and traceable management, these NFTs can be used to establish secure communication channels between the physical asset, its owner, and its user. - -## Specification - -The attributes `addressAsset` and `addressUser` are, respectively, the Ethereum addresses of the physical asset and the user. They are optional attributes but at least one of them should be used in an NFT. In the case of using only the attribute `addressUser`, two states define if the token is assigned or not to a user. `Figure 1` shows these states in a flow chart. When a token is created, transferred or unassigned, the token state is set to `notAssigned`. If the token is assigned to a valid user, the state is set to `userAssigned`. - -![Figure 1 : Flow chart of the token states with `addressUser` defined (and `addressAsset` undefined)](../assets/eip-4519/images/Figure1.jpg) - -In the case of defining the attribute `addressAsset` but not the attribute `addressUser`, two states define if the token is waiting for authentication with the owner or if the authentication has finished successfully. `Figure 2` shows these states in a flow chart. When a token is created or transferred to a new owner, then the token changes its state to `waitingForOwner`. In this state, the token is waiting for the mutual authentication between the asset and the owner. Once authentication is finished successfully, the token changes its state to `engagedWithOwner`. - -![Figure 2 : Flow chart of the token states with `addressAsset` defined (and `addressUser` undefined)](../assets/eip-4519/images/Figure2.jpg) - -Finally, if both the attributes `addressAsset` and `addressUser` are defined, the states of the NFT define if the asset has been engaged or not with the owner or the user (`waitingForOwner`, `engagedWithOwner`, `waitingForUser` and `engagedWithUser`). The flow chart in `Figure 3` shows all the possible state changes. The states related to the owner are the same as in `Figure 2`. The difference is that, at the state `engagedWithOwner`, the token can be assigned to a user. If a user is assigned (the token being at states `engagedWithOwner`, `waitingForUser` or `engagedWithUser`), then the token changes its state to `waitingForUser`. Once the asset and the user authenticate each other, the state of the token is set to `engagedWithUser`, and the user is able to use the asset. - - ![Figure 3 : Flow chart of the token states with `addressUser` and `addressUser` defined](../assets/eip-4519/images/Figure3.jpg) - -In order to complete the ownership transfer of a token, the new owner must carry out a mutual authentication process with the asset, which is off-chain with the asset and on-chain with the token, by using their Ethereum addresses. Similarly, a new user must carry out a mutual authentication process with the asset to complete a use transfer. NFTs define how the authentication processes start and finish. These authentication processes allow deriving fresh session cryptographic keys for secure communication between assets and owners, and between assets and users. Therefore, the trustworthiness of the assets can be traced even if new owners and users manage them. - -When the NFT is created or when the ownership is transferred, the token state is `waitingForOwner`. The asset sets its operating mode to `waitingForOwner`. The owner generates a pair of keys using the elliptic curve secp256k1 and the primitive element P used on this curve: a secret key SKO_A and a Public Key PKO_A, so that PKO_A = SKO_A * P. To generate the shared key between the owner and the asset, KO, the public key of the asset, PKA, is employed as follows: - -KO = PKA * SKO_A - -Using the function `startOwnerEngagement`, PKO_A is saved as the attribute `dataEngagement` and the hash of KO as the attribute `hashK_OA`. The owner sends request engagement to the asset, and the asset calculates: - -KA = SKA * PKO_A - -If everything is correctly done, KO and KA are the same since: - -KO = PKA * SKO_A = (SKA * P) * SKO_A = SKA * (SKO_A * P) = SKA * PKO_A - -Using the function `ownerEngagement`, the asset sends the hash of KA, and if it is the same as the data in `hashK_OA`, then the state of the token changes to `engagedWithOwner` and the event `OwnerEngaged` are sent. Once the asset receives the event, it changes its operation mode to `engagedWithOwner`. This process is shown in `Figure 4`. From this moment, the asset can be managed by the owner and they can communicate in a secure way using the shared key. - - ![Figure 4: Steps in a successful owner and asset mutual authentication process](../assets/eip-4519/images/Figure4.jpg) - -If the asset consults Ethereum and the state of its NFT is `waitingForUser`, the asset (assuming it is an electronic physical asset) sets its operating mode to `waitingForUser`. Then, a mutual authentication process is carried out with the user, as already done with the owner. The user sends the transaction associated with the function `startUserEngagement`. As in `startOwnerEngagement`, this function saves the public key generated by the user, PKU_A, as the attribute `dataEngagement` and the hash of KU = PKA * SKU_A as the attribute `hashK_UA` in the NFT. - -The user sends request engagement and the asset calculates: - -KA = SKA * PKU_A - -If everything is correctly done, KU and KA are the same since: - -KU = PKA * SKU_A = (SKA * P) * SKU_A = SKA * (SKU_A * P) = SKA * PKU_A - -Using the function `userEngagement`, the asset sends the hash of KA obtained and if it is the same as the data in `hashK_UA`, then the state of the token changes to `engagedWithUser` and the event `UserEngaged` is sent. Once the asset receives the event, it changes its operation mode to `engagedWithUser`. This process is shown in `Figure 5`. From this moment, the asset can be managed by the user and they can communicate in a secure way using the shared key. - - ![Figure 5: Steps in a successful user and asset mutual authentication process](../assets/eip-4519/images/Figure5.jpg) - -Since the establishment of a shared secret key is very important for a secure communication, NFTs include the attributes -`hashK_OA`, `hashK_UA` and `dataEngagement`. The first two attributes define, respectively, the hash of the secret key shared between the asset and its owner and between the asset and its user. Assets, owners and users should check they are using the correct shared secret keys. The attribute `dataEngagement` defines the public data needed for the agreement. - -```solidity -pragma solidity ^0.8.0; - /// @title EIP-4519 NFT: Extension of EIP-721 Non-Fungible Token Standard. -/// Note: the EIP-165 identifier for this interface is 0x8a68abe3 - interface EIP-4519 NFT is EIP721/*,EIP165*/{ - /// @dev This emits when the NFT is assigned as utility of a new user. - /// This event emits when the user of the token changes. - /// (`_addressUser` == 0) when no user is assigned. - event UserAssigned(uint256 indexed tokenId, address indexed _addressUser); - - /// @dev This emits when user and asset finish mutual authentication process successfully. - /// This event emits when both the user and the asset prove they share a secure communication channel. - event UserEngaged(uint256 indexed tokenId); - - /// @dev This emits when owner and asset finish mutual authentication process successfully. - /// This event emits when both the owner and the asset prove they share a secure communication channel. - event OwnerEngaged(uint256 indexed tokenId); - - /// @dev This emits when it is checked that the timeout has expired. - /// This event emits when the timestamp of the EIP-4519 NFT is not updated in timeout. - event TimeoutAlarm(uint256 indexed tokenId); - /// @notice This function defines how the NFT is assigned as utility of a new user (if "addressUser" is defined). - /// @dev Only the owner of the EIP-4519 NFT can assign a user. If "addressAsset" is defined, then the state of the token must be - /// "engagedWithOwner","waitingForUser" or "engagedWithUser" and this function changes the state of the token defined by "_tokenId" to - /// "waitingForUser". If "addressAsset" is not defined, the state is set to "userAssigned". In both cases, this function sets the parameter - /// "addressUser" to "_addressUser". - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @param _addressUser is the address of the new user. - function setUser(uint256 _tokenId, address _addressUser) external payable; - /// @notice This function defines the initialization of the mutual authentication process between the owner and the asset. - /// @dev Only the owner of the token can start this authentication process if "addressAsset" is defined and the state of the token is "waitingForOwner". - /// The function does not change the state of the token and saves "_dataEngagement" - /// and "_hashK_OA" in the parameters of the token. - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @param _dataEngagement is the public data proposed by the owner for the agreement of the shared key. - /// @param _hashK_OA is the hash of the secret proposed by the owner to share with the asset. - function startOwnerEngagement(uint256 _tokenId, uint256 _dataEngagement, uint256 _hashK_OA) external payable; - - /// @notice This function completes the mutual authentication process between the owner and the asset. - /// @dev Only the asset tied to the token can finish this authentication process provided that the state of the token is - /// "waitingForOwner" and dataEngagement is different from 0. This function compares hashK_OA saved in - /// the token with hashK_A. If they are equal then the state of the token changes to "engagedWithOwner", dataEngagement is set to 0, - /// and the event "OwnerEngaged" is emitted. - /// @param _hashK_A is the hash of the secret generated by the asset to share with the owner. - function ownerEngagement(uint256 _hashK_A) external payable; - - /// @notice This function defines the initialization of the mutual authentication process between the user and the asset. - /// @dev Only the user of the token can start this authentication process if "addressAsset" and "addressUser" are defined and - /// the state of the token is "waitingForUser". The function does not change the state of the token and saves "_dataEngagement" - /// and "_hashK_UA" in the parameters of the token. - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @param _dataEngagement is the public data proposed by the user for the agreement of the shared key. - /// @param _hashK_UA is the hash of the secret proposed by the user to share with the asset. - function startUserEngagement(uint256 _tokenId, uint256 _dataEngagement, uint256 _hashK_UA) external payable; - - /// @notice This function completes the mutual authentication process between the user and the asset. - /// @dev Only the asset tied to the token can finish this authentication process provided that the state of the token is - /// "waitingForUser" and dataEngagement is different from 0. This function compares hashK_UA saved in - /// the token with hashK_A. If they are equal then the state of the token changes to "engagedWithUser", dataEngagement is set to 0, - /// and the event "UserEngaged" is emitted. - /// @param _hashK_A is the hash of the secret generated by the asset to share with the user. - function userEngagement(uint256 _hashK_A) external payable; - - /// @notice This function checks if the timeout has expired. - /// @dev Everybody can call this function to check if the timeout has expired. The event "TimeoutAlarm" is emitted - /// if the timeout has expired. - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @return true if timeout has expired and false in other case. - function checkTimeout(uint256 _tokenId) external returns (bool); - - /// @notice This function sets the value of timeout. - /// @dev Only the owner of the token can set this value provided that the state of the token is "engagedWithOwner", - /// "waitingForUser" or "engagedWithUser". - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @param _timeout is the value to assign to timeout. - function setTimeout(uint256 _tokenId, uint256 _timeout) external; - - /// @notice This function updates the timestamp, thus avoiding the timeout alarm. - /// @dev Only the asset tied to the token can update its own timestamp. - function updateTimestamp() external; - - /// @notice This function lets obtain the tokenId from an address. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _addressAsset is the address to obtain the tokenId from it. - /// @return tokenId of the token tied to the asset that generates _addressAsset. - function tokenFromBCA(address _addressAsset) external view returns (uint256); - - /// @notice This function lets know the owner of the token from the address of the asset tied to the token. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _addressAsset is the address to obtain the owner from it. - /// @return owner of the token bound to the asset that generates _addressAsset. - function ownerOfFromBCA(address _addressAsset) external view returns (address); - - /// @notice This function lets know the user of the token from its tokenId. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _tokenId is the tokenId of the EIP-4519 NFT tied to the asset. - /// @return user of the token from its _tokenId. - function userOf(uint256 _tokenId) external view returns (address); - - /// @notice This function lets know the user of the token from the address of the asset tied to the token. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _addressAsset is the address to obtain the user from it. - /// @return user of the token tied to the asset that generates _addressAsset. - function userOfFromBCA(address _addressAsset) external view returns (address); - - /// @notice This function lets know how many tokens are assigned to a user. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _addressUser is the address of the user. - /// @return number of tokens assigned to a user. - function userBalanceOf(address _addressUser) external view returns (uint256); - - /// @notice This function lets know how many tokens of a particular owner are assigned to a user. - /// @dev Everybody can call this function. The code executed only reads from Ethereum. - /// @param _addressUser is the address of the user. - /// @param _addressOwner is the address of the owner. - /// @return number of tokens assigned to a user from an owner. - function userBalanceOfAnOwner(address _addressUser, address _addressOwner) external view returns (uint256); -} -``` - -## Rationale - -### Authentication - -This EIP uses smart contracts to verify the mutual authentication process since smart contracts are trustless. - -### Tie Time - -This EIP proposes including the attribute timestamp (to register in Ethereum the last time that the physical asset checked the tie with its token) and the attribute timeout (to register the maximum delay time established for the physical asset to prove again the tie). These attributes avoid that a malicious owner or user could use the asset endlessly. - -When the asset calls `updateTimestamp`, the smart contract must call `block.timestamp`, which provides current block timestamp as seconds since Unix epoch. For this reason, `timeout` must be provided in seconds. - -### EIP-721-based - -[EIP-721](./eip-721.md) is the most commonly-used standard for generic NFTs. This EIP extends EIP-721 for backwards compatibility. - -## Backwards Compatibility - -This standard is an extension of EIP-721. It is fully compatible with both of the commonly used optional extensions (`IERC721Metadata` and `IERC721Enumerable`) mentioned in the EIP-721 standard. - -## Test Cases - -The test cases presented in the paper shown below are available [here](../assets/eip-4519/PoC_SmartNFT/README.md). - -## Reference Implementation - -A first version was presented in a paper of the Special Issue **Security, Trust and Privacy in New Computing Environments** of **Sensors** journal of **MDPI** editorial. The paper, entitled [Secure Combination of IoT and Blockchain by Physically Binding IoT Devices to Smart Non-Fungible Tokens Using PUFs](../assets/eip-4519/sensors-21-03119.pdf), was written by the same authors of this EIP. - -## Security Considerations - -In this EIP, a generic system has been proposed for the creation of non-fungible tokens tied to physical assets. A generic point of view based on the improvements of the current EIP-721 NFT is provided, such as the implementation of the user management mechanism, which does not affect the token's ownership. The physical asset should have the ability to generate an Ethereum address from itself in a totally random way so that only the asset is able to know the secret from which the Ethereum address is generated. In this way, identity theft is avoided and the asset can be proven to be completely genuine. In order to ensure this, it is recommended that only the manufacturer of the asset has the ability to create its associated token. In the case of an IoT device, the device firmware will be unable to share and modify the secret. Instead of storing the secrets, it is recommended that assets reconstruct their secrets from non-sensitive information such as the helper data associated with Physical Unclonable Functions (PUFs). Although a secure key exchange protocol based on elliptic curves has been proposed, the token is open to coexist with other types of key exchange. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4519.md diff --git a/EIPS/eip-4520.md b/EIPS/eip-4520.md index 1ee2113189911f..45b73f24ee7662 100644 --- a/EIPS/eip-4520.md +++ b/EIPS/eip-4520.md @@ -1,13 +1,13 @@ --- eip: 4520 -title: Mult-byte opcodes prefixed by EB and EC. +title: Multi-byte opcodes prefixed by EB and EC. description: Reserve `0xEB` and `0xEC` for usage as extended opcode space. author: Brayton Goodall (@Spore-Druid-Bray), Mihir Faujdar (@uink45) discussions-to: https://ethereum-magicians.org/t/multi-byte-opcodes/7681 status: Stagnant type: Standards Track category: Core -created: 2021-12-1 +created: 2021-12-01 --- ## Abstract diff --git a/EIPS/eip-4521.md b/EIPS/eip-4521.md index d12bf999bd8cf6..f9b8533ed65f63 100644 --- a/EIPS/eip-4521.md +++ b/EIPS/eip-4521.md @@ -1,62 +1,7 @@ --- eip: 4521 -title: 721/20-compatible transfer -description: Recommends a simple extension to make NFTs compatible with apps and contracts that handle fungibles. -author: Ross Campbell (@z0r0z) -discussions-to: https://ethereum-magicians.org/t/eip-4521-721-20-compatible-transfer/7903 -status: Stagnant -type: Standards Track category: ERC -created: 2021-12-13 -requires: 721 +status: Moved --- -## Abstract -ERC-721, the popular standard for non-fungible tokens (NFTs), includes send functions, such as `transferFrom()` and `safeTransferFrom()`, but does not include a backwards-compatible `transfer()` found in fungible ERC-20 tokens. This standard provides references to add such a `transfer()`. - -## Motivation -This standard proposes a simple extension to allow NFTs to work with contracts designed to manage ERC-20s and many consumer wallets which expect to be able to execute a token `transfer()`. For example, if an NFT is inadvertently sent to a contract that typically handles ERC-20, that NFT will be locked. It should also simplify the task for contract programmers if they can rely on `transfer()` to both handle ERC-20 and NFTs. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -The interface for ERC-4521 `transfer()` MUST conform to ERC-20 and resulting transfers MUST fire the `Transfer` event as described in ERC-721. - -```sol -function transfer(address to, uint256 tokenId) external returns (bool success); -``` - -## Rationale -Replicating ERC-20 `transfer()` with just a minor change to accurately reflect that a unique `tokenId` rather than fungible sum is being sent is desirable for code simplicity and to make integration easier. - -## Backwards Compatibility -This EIP does not introduce any known backward compatibility issues. - -## Reference Implementation -A reference implementation of an ERC-4521 `transfer()`: - -```sol -function transfer(address to, uint256 tokenId) public virtual returns (bool success) { - require(msg.sender == ownerOf[tokenId], "NOT_OWNER"); - - unchecked { - balanceOf[msg.sender]--; - - balanceOf[to]++; - } - - delete getApproved[tokenId]; - - ownerOf[tokenId] = to; - - emit Transfer(msg.sender, to, tokenId); - - success = true; -} -``` - -## Security Considerations -Implementers must be sure to include the relevant return `bool` value for an ERC-4521 in order to conform with existing contracts that use ERC-20 interfaces, otherwise, NFTs may be locked unless a `safeTransfer` is used in such contracts. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4521.md diff --git a/EIPS/eip-4524.md b/EIPS/eip-4524.md index 4475577eddebd2..bf966b0c5f3543 100644 --- a/EIPS/eip-4524.md +++ b/EIPS/eip-4524.md @@ -1,82 +1,7 @@ --- eip: 4524 -title: Safer ERC-20 -description: Extending ERC-20 with ERC165 and adding safeTransfer (like ERC-721 and ERC-1155) -author: William Schwab (@wschwab) -discussions-to: https://ethereum-magicians.org/t/why-isnt-there-an-erc-for-safetransfer-for-erc20/7604 -status: Stagnant -type: Standards Track category: ERC -created: 2021-12-05 -requires: 20, 165 +status: Moved --- -## Abstract - -This standard extends [ERC-20](./eip-20.md) tokens with [EIP-165](./eip-165.md), and adds familiar functions from [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) ensuring receiving contracts have implemented proper functionality. - -## Motivation - -[EIP-165](./eip-165.md) adds (among other things) the ability to tell if a target recipient explicitly signals compatibility with an ERC. This is already used in the EIPs for NFTs, [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md). In addition, EIP-165 is a valuable building block for extensions on popular standards to signal implementation, a trend we've seen in a number of NFT extensions. This EIP aims to bring these innovations back to ERC-20. - -The importance of [EIP-165](./eip-165.md) is perhaps felt most for app developers looking to integrate with a generic standard such as ERC-20 or ERC-721, while integrating newer innovations built atop these standards. An easy example would be token permits, which allow for a one-transaction approval and transfer. This has already been implemented in many popular ERC-20 tokens using the [ERC-2612](./eip-2612.md) standard or similar. A platform integrating ERC-20 tokens has no easy way of telling if a particular token has implemented token permits or not. (As of this writing, ERC-2612 does not require EIP-165.) With EIP-165, the app (or contracts) could query `supportsInterface` to see if the `interfaceId` of a particular EIP is registered (in this case, EIP-2612), allowing for easier and more modular functions interacting with ERC-20 contracts. It is already common in NFT extensions to include an EIP-165 interface with a standard, we would argue this is at least in part due to the underlying [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) standards integrating EIP-165. Our hope is that this extension to ERC-20 would also help future extensions by making them easier to integrate. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -In order to be compliant with this EIP, and ERC-20-compliant contract MUST also implement the following functions: -```solidity -pragma solidity 0.8.10; - -import './IERC20.sol'; -import './IERC165.sol'; - -// the EIP-165 interfaceId for this interface is 0x534f5876 - -interface SaferERC-20 is IERC20, IERC165 { - function safeTransfer(address to, uint256 amount) external returns(bool); - function safeTransfer(address to, uint256 amount, bytes memory data) external returns(bool); - function safeTransferFrom(address from, address to, uint256 amount) external returns(bool); - function safeTransferFrom(address from, address to, uint256 amount, bytes memory data) external returns(bool); -} -``` -`safeTransfer` and `safeTransferFrom` MUST transfer as expected to EOA addresses, and to contracts implementing `ERC20Receiver` and returning the function selector (`0x4fc35859`) when called, and MUST revert when transferring to a contract which either does not have `ERC20Receiver` implemented, or does not return the function selector when called. - -In addition, a contract accepting safe transfers MUST implement the following if it wishes to accept safe transfers, and MUST return the function selector (`0x4fc35859`): -```solidity -pragma solidity 0.8.10; - -import './IERC165.sol'; - -interface ERC20Receiver is IERC165 { - function onERC20Received( - address _operator, - address _from, - uint256 _amount, - bytes _data - ) external returns(bytes4); -} -``` - -## Rationale - -This EIP is meant to be minimal and straightforward. Adding EIP-165 to ERC-20 is useful for a number of applications, and outside of a minimal amount of code increasing contract size, carries no downside. The `safeTransfer` and `safeTransferFrom` functions are well recognized from ERC-721 and ERC-1155, and therefore keeping identical naming conventions is reasonable, and the benefits of being able to check for implementation before transferring are as useful for ERC-20 tokens as they are for ERC-721 and ERC-1155. - -Another easy backport from EIP721 and EIP1155 might be the inclusion of a metadata URI for tokens, allowing them to easily reference logo and other details. This has not been included, both in order to keep this EIP as minimal as possible, and because it is already sufficiently covered by [EIP-1046](./eip-1046.md). - -## Backwards Compatibility - -There are no issues with backwards compatibility in this EIP, as the full suite of ERC-20 functions is unchanged. - -## Test Cases -Test cases have been provided in the implementation repo [here](https://github.com/wschwab/SaferERC-20/blob/main/src/SaferERC-20.t.sol). - -## Reference Implementation -A sample repo demonstrating an implementation of this EIP has been created [here](https://github.com/wschwab/SaferERC-20). It is (as of this writing) in a Dapptools environment, for details on installing and running Dapptools see the Dapptools repo. - -## Security Considerations - -`onERC20Received` is a callback function. Callback functions have been exploited in the past as a reentrancy vector, and care should be taken to make sure implementations are not vulnerable. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4524.md diff --git a/EIPS/eip-4527.md b/EIPS/eip-4527.md index 76e1e8ad8d262d..237429150b71ca 100644 --- a/EIPS/eip-4527.md +++ b/EIPS/eip-4527.md @@ -1,239 +1,7 @@ --- eip: 4527 -title: QR Code transmission protocol for wallets -description: QR Code data transmission protocol between wallets and offline signers. -author: Aaron Chen (@aaronisme), Sora Lee (@soralit), ligi (@ligi), Dan Miller (@danjm), AndreasGassmann (@andreasgassmann), xardass (@xardass), Lixin Liu (@BitcoinLixin) -discussions-to: https://ethereum-magicians.org/t/add-qr-code-scanning-between-software-wallet-cold-signer-hardware-wallet/6568 -status: Review -type: Standards Track category: ERC -created: 2021-12-07 +status: Moved --- -## Abstract - -The purpose of this EIP is to provide a process and data transmission protocol via QR Code between offline signers and watch-only wallets. - -## Motivation - -There is an increasing number of users whom like to use complete offline signers to manage their private keys, signers like hardware wallets and mobile phones in offline mode. In order to sign transactions or data, these offline signers have to rely on a watch-only wallet since it would prepare the data to be signed. Currently, there are 4 possible data transmission methods between offline signers and watch-only wallets: QR Code, USB, Bluetooth, and file transfer. The QR Code data transmission method have the following advantages when compared to the other three methods mentioned above: - -- Transparency and Security: Compared to USB or Bluetooth, users can easily decode the data via QR Code (with the help of some tools). It can also help users clearly identify what they are going to sign, which improves transparency and thus better security. -- Improved Compatibility: Compared to USB and Bluetooth, QR Code data transmissions has a wider range of compatibility. Normally, it wouldn’t be broken by software changes like browser upgrades, system upgrade, and etc. -- Improved User experience: QR Code data transmissions can provide a better user experience compared to USB, Bluetooth, and file transfer especially when the user is using a mobile device. -- A smaller attack surface: USB and Bluetooth have a bigger attack surface than QR-Codes. - -Due to these advantages, QR Code data transmissions is a better choice. Unfortunately, there is no modern standard for how offline signers should work with watch-only wallets nor how data should be encoded. -This EIP presents a standard process and data transmission protocol for offline signers to work with watch-only wallets. - -## Specification - -**Offline signer**: An offline signer is a device or application which holds the user’s private keys and does not have network access. - -**Watch-only wallet**: A watch-only wallet is a wallet that has network access and can interact with the Ethereum blockchain. - -### Process - -In order to work with offline signers, the watch-only wallet should follow the following process. - -1. The offline signer provides the public key information to the watch-only wallet to generate addresses, sync balances and etc via QR Codes. -2. The watch-only wallet generates the unsigned data and sends it to an offline signer for signing via QR Code, data that can include transactions, typed data, and etc. -3. The offline signer signs the data and provides a signature back to the watch-only wallet via QR Code. -4. The watch-only wallet receives the signature, constructs the signed data (transaction) and performs the following activities like broadcasting the transaction etc. - -### Data Transmission Protocol - -Since a single QR Code can only contain a limited amount of data, animated QR Codes should be utilized for data transmission. The `BlockchainCommons` have published a series of data transmission protocol called Uniform Resources (UR). It provides a basic method to encode data into animated QR Codes. This EIP will use UR and extend its current definition. - -`Concise Binary Object Representation(CBOR)` will be used for binary data encoding. `Concise Data Definition Language(CDDL)` will be used for expressing the CBOR. - -### Setting up the watch-only wallet with the offline signer - -In order to allow a watch-only wallet to collect information from the Ethereum blockchain, the offline signer would need to provide the public keys to the watch-only wallet in which the wallet will use them to query the necessary information from the Ethereum blockchain. - -In such a case, offline signers should provide the extended public keys and derivation path. The UR Type called `crypto-hdkey` will be used to encode this data and the derivation path will be encoded as `crypto-keypath`. - - -#### CDDL for Key Path - -The `crypto-keypath` will be used to specify the key path.The following specification is written in Concise Data Definition Language(CDDL) for `crypto-key-path` - -``` -; Metadata for the derivation path of a key. -; -; `source-fingerprint`, if present, is the fingerprint of the -; ancestor key from which the associated key was derived. -; -; If `components` is empty, then `source-fingerprint` MUST be a fingerprint of -; a master key. -; -; `depth`, if present, represents the number of derivation steps in -; the path of the associated key, even if not present in the `components` element -; of this structure. - crypto-keypath = { - components: [path-component], ; If empty, source-fingerprint MUST be present - ? source-fingerprint: uint32 .ne 0 ; fingerprint of ancestor key, or master key if components is empty - ? depth: uint8 ; 0 if this is a public key derived directly from a master key - } - path-component = ( - child-index / child-index-range / child-index-wildcard-range, - is-hardened - ) - uint32 = uint .size 4 - uint31 = uint32 .lt 2147483648 ;0x80000000 - child-index = uint31 - child-index-range = [child-index, child-index] ; [low, high] where low < high - child-index-wildcard = [] - is-hardened = bool - components = 1 - source-fingerprint = 2 - depth = 3 -``` - -#### CDDL for Extended Public Keys - -Since the purpose is to transfer public key data, the definition of `crypto-hdkey` will be kept only for public key usage purposes. - -The following specification is written in Concise Data Definition Language `CDDL` and includes the crypto-keypath spec above. - -``` -; An hd-key must be a derived key. -hd-key = { - derived-key -} -; A derived key must be public, has an optional chain code, and -; may carry additional metadata about its use and derivation. -; To maintain isomorphism with [BIP32] and allow keys to be derived from -; this key `chain-code`, `origin`, and `parent-fingerprint` must be present. -; If `origin` contains only a single derivation step and also contains `source-fingerprint`, -; then `parent-fingerprint` MUST be identical to `source-fingerprint` or may be omitted. -derived-key = ( - key-data: key-data-bytes, - ? chain-code: chain-code-bytes ; omit if no further keys may be derived from this key - ? origin: #6.304(crypto-keypath), ; How the key was derived - ? name: text, ; A short name for this key. - ? source: text, ; The device info or any other description for this key -) -key-data = 3 -chain-code = 4 -origin = 6 -name = 9 -source = 10 - -uint8 = uint .size 1 -key-data-bytes = bytes .size 33 -chain-code-bytes = bytes .size 32 -``` - -If the chain-code is provided, then it can be used to derive child keys but if it isn’t provided, it is simply a solo key and the origin can be provided to indicate the derivation key path. - -If the signer would like to provide muliple public keys instead of the extended public key for any reason, the signer can use `crypto-account` for that. - -### Sending the unsigned data from the watch-only wallet to the offline signer - -To send the unsigned data from a watch-only wallet to an offline signer, the new UR type `eth-sign-request` will be introduced to encode the signing request. - -#### CDDL for Eth Sign Request. - -The following specification is written in Concise Data Definition Language `CDDL`. -UUIDs in this specification notated UUID are CBOR binary strings tagged with #6.37, per the IANA `CBOR Tags Registry`. - -``` -; Metadata for the signing request for Ethereum. -; -sign-data-type = { - type: int .default 1 transaction data; the unsigned data type -} - -eth-transaction-data = 1; legacy transaction rlp encoding of unsigned transaction data -eth-typed-data = 2; EIP-712 typed signing data -eth-raw-bytes=3; for signing message usage, like EIP-191 personal_sign data -eth-typed-transaction=4; EIP-2718 typed transaction of unsigned transaction data - -; Metadata for the signing request for Ethereum. -; request-id: the identifier for this signing request. -; sign-data: the unsigned data -; data-type: see sign-data-type definition -; chain-id: chain id definition see https://github.com/ethereum-lists/chains for detail -; derivation-path: the key path of the private key to sign the data -; address: Ethereum address of the signing type for verification purposes which is optional - -eth-sign-request = ( - sign-data: sign-data-bytes, ; sign-data is the data to be signed by offline signer, currently it can be unsigned transaction or typed data - data-type: #3.401(sign-data-type), - chain-id: int .default 1, - derivation-path: #5.304(crypto-keypath), ;the key path for signing this request - ?request-id: uuid, ; the uuid for this signing request - ?address: eth-address-bytes, ;verification purpose for the address of the signing key - ?origin: text ;the origin of this sign request, like wallet name -) -request-id = 1 -sign-data = 2 -data-type = 3 -chain-id = 4 ;it will be the chain id of ethereum related blockchain -derivation-path = 5 -address = 6 -origin = 7 -eth-address-bytes = bytes .size 20 -sign-data-bytes = bytes ; for unsigned transactions it will be the rlp encoding for unsigned transaction data and ERC 712 typed data it will be the bytes of json string. -``` - -### The signature provided by offline signers to watch-only wallets - -After the data is signed, the offline signer should send the signature back to the watch-only wallet. The new UR type called `eth-signature` is introduced here to encode this data. - -#### CDDL for Eth Signature. - -The following specification is written in Concise Data Definition Language `CDDL`. - -``` -eth-signature = ( - request-id: uuid, - signature: eth-signature-bytes, - ? origin: text, ; The device info for providing this signature -) - -request-id = 1 -signature = 2 -origin = 3 - -eth-signature-bytes = bytes .size 65; the signature of the signing request (r,s,v) -``` - -## Rationale - -This EIP uses some existing UR types like `crypto-keypath` and `crypto-hdkey` and also introduces some new UR types like `eth-sign-request` and `eth-signature`. Here are the reasons we choose UR for the QR Code data transmission protocol: - -### UR provides a solid foundation for QR Code data transmission - -- Uses the alphanumeric QR code mode for efficiency. -- Includes a CRC32 checksum of the entire message in each part to tie the different parts of the QR code together and ensure the transmitted message has been reconstructed. -- uses `Fountain Code` for the arbitrary amount of data which can be both a minimal, finite sequence of parts and an indefinite sequence of parts. The Fountain Code can ultimately help the receiver to make the data extraction easier. - -### UR provides existing helpful types and scalability for new usages - -Currently, UR has provided some existing types like `crypto-keypath` and `crypto-hdkey` so it is quite easy to add a new type and definitions for new usages. - -### UR has an active air-gapped wallet community. - -Currently, the UR has an active `airgapped wallet community` which continues to improve the UR forward. - -## Backwards Compatibility - -Currently, there is no existing protocol to define data transmissions via QR Codes so there are no backward compatibility issues that needs to be addressed now. - -## Test Cases - -The test cases can be found on the `ur-registry-eth` package released by the Keystone team. - -## Reference Implementation - -The reference implementation can be found on the `ur-registry-eth` package released by the Keystone team. - -## Security Considerations - -The offline signer should decode all the data from `eth-sign-request` and show them to the user for confirmation prior to signing. It is recommended to provide an address field in the `eth-sign-request`. If provided, the offline signer should verify the address being the same one as the address associated with the signing key. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4527.md diff --git a/EIPS/eip-4546.md b/EIPS/eip-4546.md index c27fcabce67b99..3dcbfa7ce06799 100644 --- a/EIPS/eip-4546.md +++ b/EIPS/eip-4546.md @@ -1,173 +1,7 @@ --- eip: 4546 -title: Wrapped Deposits -description: A singleton contract for managing asset deposits. -author: Justice Hudson (@jchancehud) -discussions-to: https://ethereum-magicians.org/t/wrapped-deposit-contract-eip/7740 -status: Stagnant -type: Standards Track category: ERC -created: 2021-12-11 +status: Moved --- -## Abstract -The wrapped deposit contract handles deposits of assets (Ether, [ERC-20](./eip-20.md), [ERC-721](./eip-721.md)) on behalf of a user. A user must only approve a spend limit once and then an asset may be deposited to any number of different applications that support deposits from the contract. - -## Motivation -The current user flow for depositing assets in dapps is unnecessarily expensive and insecure. To deposit an ERC-20 asset a user must either: - - - send an approve transaction for the exact amount being sent, before making a deposit, and then repeat this process for every subsequent deposit. - - send an approve transaction for an infinite spend amount before making deposits. - -The first option is inconvenient, and expensive. The second option is insecure. Further, explaining approvals to new or non-technical users is confusing. This has to be done in _every_ dapp that supports ERC20 deposits. - -## Specification -The wrapped deposit contract SHOULD be deployed at an identifiable address (e.g. `0x1111119a9e30bceadf9f939390293ffacef93fe9`). The contract MUST be non-upgradable with no ability for state variables to be changed. - -The wrapped deposit contract MUST have the following public functions: - -```js -depositERC20(address to, address token, uint amount) external; -depositERC721(address to, address token, uint tokenId) external; -safeDepositERC721(address to, address token, uint tokenId, bytes memory data) external; -safeDepositERC1155(address to, address token, uint tokenId, uint value, bytes calldata data) external; -batchDepositERC1155(address to, address token, uint[] calldata tokenIds, uint[] calldata values, bytes calldata data) external; -depositEther(address to) external payable; -``` - -Each of these functions MUST revert if `to` is an address with a zero code size. Each function MUST attempt to call a method on the `to` address confirming that it is willing and able to accept the deposit. If this function call does not return a true value execution MUST revert. If the asset transfer is not successful execution MUST revert. - -The following interfaces SHOULD exist for contracts wishing to accept deposits: - -```ts -interface ERC20Receiver { - function acceptERC20Deposit(address depositor, address token, uint amount) external returns (bool); -} - -interface ERC721Receiver { - function acceptERC721Deposit(address depositor, address token, uint tokenId) external returns (bool); -} - -interface ERC1155Receiver { - function acceptERC1155Deposit(address depositor, address token, uint tokenId, uint value, bytes calldata data) external returns (bool); - function acceptERC1155BatchDeposit(address depositor, address token, uint[] calldata tokenIds, uint[] calldata values, bytes calldata data) external returns (bool); -} - -interface EtherReceiver { - function acceptEtherDeposit(address depositor, uint amount) external returns (bool); -} -``` - -A receiving contract MAY implement any of these functions as desired. If a given function is not implemented deposits MUST not be sent for that asset type. - -## Rationale -Having a single contract that processes all token transfers allows users to submit a single approval per token to deposit to any number of contracts. The user does not have to trust receiving contracts with token spend approvals and receiving contracts have their complexity reduced by not having to implement token transfers themselves. - -User experience is improved because a simple global dapp can be implemented with the messaging: "enable token for use in other apps". - -## Backwards Compatibility - -This EIP is not backward compatible. Any contract planning to use this deposit system must implement specific functions to accept deposits. Existing contracts that are upgradeable can add support for this EIP retroactively by implementing one or more accept deposit functions. - -Upgraded contracts can allow deposits using both the old system (approving the contract itself) and the proposed deposit system to preserve existing approvals. New users should be prompted to use the proposed deposit system. - -## Reference Implementation -```ts -pragma solidity ^0.7.0; - -interface ERC20Receiver { - function acceptERC20Deposit(address depositor, address token, uint amount) external returns (bool); -} - -interface ERC721Receiver { - function acceptERC721Deposit(address depositor, address token, uint tokenId) external returns (bool); -} - -interface ERC1155Receiver { - function acceptERC1155Deposit(address depositor, address token, uint tokenId, uint value, bytes calldata data) external returns (bool); - function acceptERC1155BatchDeposit(address depositor, address token, uint[] calldata tokenIds, uint[] calldata values, bytes calldata data) external returns (bool); -} - -interface EtherReceiver { - function acceptEtherDeposit(address depositor, uint amount) external returns (bool); -} - -interface IERC20 { - function transferFrom(address sender, address recipient, uint amount) external returns (bool); -} - -interface IERC721 { - function transferFrom(address _from, address _to, uint256 _tokenId) external payable; - function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable; -} - -interface IERC1155 { - function safeTransferFrom(address _from, address _to, uint _id, uint _value, bytes calldata _data) external; - function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; -} - -contract WrappedDeposit { - function depositERC20(address to, address token, uint amount) public { - _assertContract(to); - require(ERC20Receiver(to).acceptERC20Deposit(msg.sender, token, amount)); - bytes memory data = abi.encodeWithSelector( - IERC20(token).transferFrom.selector, - msg.sender, - to, - amount - ); - (bool success, bytes memory returndata) = token.call(data); - require(success); - // backward compat for tokens incorrectly implementing the transfer function - if (returndata.length > 0) { - require(abi.decode(returndata, (bool)), "ERC20 operation did not succeed"); - } - } - - function depositERC721(address to, address token, uint tokenId) public { - _assertContract(to); - require(ERC721Receiver(to).acceptERC721Deposit(msg.sender, token, tokenId)); - IERC721(token).transferFrom(msg.sender, to, tokenId); - } - - function safeDepositERC721(address to, address token, uint tokenId, bytes memory data) public { - _assertContract(to); - require(ERC721Receiver(to).acceptERC721Deposit(msg.sender, token, tokenId)); - IERC721(token).safeTransferFrom(msg.sender, to, tokenId, data); - } - - function safeDepositERC1155(address to, address token, uint tokenId, uint value, bytes calldata data) public { - _assertContract(to); - require(ERC1155Receiver(to).acceptERC1155Deposit(msg.sender, to, tokenId, value, data)); - IERC1155(token).safeTransferFrom(msg.sender, to, tokenId, value, data); - } - - function batchDepositERC1155(address to, address token, uint[] calldata tokenIds, uint[] calldata values, bytes calldata data) public { - _assertContract(to); - require(ERC1155Receiver(to).acceptERC1155BatchDeposit(msg.sender, to, tokenIds, values, data)); - IERC1155(token).safeBatchTransferFrom(msg.sender, to, tokenIds, values, data); - } - - function depositEther(address to) public payable { - _assertContract(to); - require(EtherReceiver(to).acceptEtherDeposit(msg.sender, msg.value)); - (bool success, ) = to.call{value: msg.value}(''); - require(success, "nonpayable"); - } - - function _assertContract(address c) private view { - uint size; - assembly { - size := extcodesize(c) - } - require(size > 0, "noncontract"); - } -} -``` -## Security Considerations -The wrapped deposit implementation should be as small as possible to reduce the risk of bugs. The contract should be small enough that an engineer can read and understand it in a few minutes. - -Receiving contracts MUST verify that `msg.sender` is equal to the wrapped deposit contract. Failing to do so allows anyone to simulate deposits. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4546.md diff --git a/EIPS/eip-4626.md b/EIPS/eip-4626.md index c28df5cba1ac01..be8961ad67107a 100644 --- a/EIPS/eip-4626.md +++ b/EIPS/eip-4626.md @@ -1,612 +1,7 @@ --- eip: 4626 -title: Tokenized Vaults -description: Tokenized Vaults with a single underlying EIP-20 token. -author: Joey Santoro (@joeysantoro), t11s (@transmissions11), Jet Jadeja (@JetJadeja), Alberto Cuesta Cañada (@alcueca), Señor Doggo (@fubuloubu) -discussions-to: https://ethereum-magicians.org/t/eip-4626-yield-bearing-vault-standard/7900 -status: Final -type: Standards Track category: ERC -created: 2021-12-22 -requires: 20, 2612 +status: Moved --- -## Abstract - -The following standard allows for the implementation of a standard API for tokenized Vaults -representing shares of a single underlying [EIP-20](./eip-20.md) token. -This standard is an extension on the EIP-20 token that provides basic functionality for depositing -and withdrawing tokens and reading balances. - -## Motivation - -Tokenized Vaults have a lack of standardization leading to diverse implementation details. -Some various examples include lending markets, aggregators, and intrinsically interest bearing tokens. -This makes integration difficult at the aggregator or plugin layer for protocols which need to conform to many standards, and forces each protocol to implement their own adapters which are error prone and waste development resources. - -A standard for tokenized Vaults will lower the integration effort for yield-bearing vaults, while creating more consistent and robust implementation patterns. - -## Specification - -All [EIP-4626](./eip-4626.md) tokenized Vaults MUST implement EIP-20 to represent shares. -If a Vault is to be non-transferrable, it MAY revert on calls to `transfer` or `transferFrom`. -The EIP-20 operations `balanceOf`, `transfer`, `totalSupply`, etc. operate on the Vault "shares" -which represent a claim to ownership on a fraction of the Vault's underlying holdings. - -All EIP-4626 tokenized Vaults MUST implement EIP-20's optional metadata extensions. -The `name` and `symbol` functions SHOULD reflect the underlying token's `name` and `symbol` in some way. - -EIP-4626 tokenized Vaults MAY implement [EIP-2612](./eip-2612.md) to improve the UX of approving shares on various integrations. - -### Definitions: - -- asset: The underlying token managed by the Vault. - Has units defined by the corresponding EIP-20 contract. -- share: The token of the Vault. Has a ratio of underlying assets - exchanged on mint/deposit/withdraw/redeem (as defined by the Vault). -- fee: An amount of assets or shares charged to the user by the Vault. Fees can exists for - deposits, yield, AUM, withdrawals, or anything else prescribed by the Vault. -- slippage: Any difference between advertised share price and economic realities of - deposit to or withdrawal from the Vault, which is not accounted by fees. - -### Methods - -#### asset - -The address of the underlying token used for the Vault for accounting, depositing, and withdrawing. - -MUST be an EIP-20 token contract. - -MUST _NOT_ revert. - -```yaml -- name: asset - type: function - stateMutability: view - - inputs: [] - - outputs: - - name: assetTokenAddress - type: address -``` - -#### totalAssets - -Total amount of the underlying asset that is "managed" by Vault. - -SHOULD include any compounding that occurs from yield. - -MUST be inclusive of any fees that are charged against assets in the Vault. - -MUST _NOT_ revert. - -```yaml -- name: totalAssets - type: function - stateMutability: view - - inputs: [] - - outputs: - - name: totalManagedAssets - type: uint256 -``` - -#### convertToShares - -The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. - -MUST NOT be inclusive of any fees that are charged against assets in the Vault. - -MUST NOT show any variations depending on the caller. - -MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. - -MUST NOT revert unless due to integer overflow caused by an unreasonably large input. - -MUST round down towards 0. - -This calculation MAY NOT reflect the "per-user" price-per-share, and instead should reflect the "average-user's" price-per-share, meaning what the average user should expect to see when exchanging to and from. - -```yaml -- name: convertToShares - type: function - stateMutability: view - - inputs: - - name: assets - type: uint256 - - outputs: - - name: shares - type: uint256 -``` - -#### convertToAssets - -The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. - -MUST NOT be inclusive of any fees that are charged against assets in the Vault. - -MUST NOT show any variations depending on the caller. - -MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. - -MUST NOT revert unless due to integer overflow caused by an unreasonably large input. - -MUST round down towards 0. - -This calculation MAY NOT reflect the "per-user" price-per-share, and instead should reflect the "average-user's" price-per-share, meaning what the average user should expect to see when exchanging to and from. - -```yaml -- name: convertToAssets - type: function - stateMutability: view - - inputs: - - name: shares - type: uint256 - - outputs: - - name: assets - type: uint256 -``` - -#### maxDeposit - -Maximum amount of the underlying asset that can be deposited into the Vault for the `receiver`, through a `deposit` call. - -MUST return the maximum amount of assets `deposit` would allow to be deposited for `receiver` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). This assumes that the user has infinite assets, i.e. MUST NOT rely on `balanceOf` of `asset`. - -MUST factor in both global and user-specific limits, like if deposits are entirely disabled (even temporarily) it MUST return 0. - -MUST return `2 ** 256 - 1` if there is no limit on the maximum amount of assets that may be deposited. - -MUST NOT revert. - -```yaml -- name: maxDeposit - type: function - stateMutability: view - - inputs: - - name: receiver - type: address - - outputs: - - name: maxAssets - type: uint256 -``` - -#### previewDeposit - -Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. - -MUST return as close to and no more than the exact amount of Vault shares that would be minted in a `deposit` call in the same transaction. I.e. `deposit` should return the same or more `shares` as `previewDeposit` if called in the same transaction. - -MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the deposit would be accepted, regardless if the user has enough tokens approved, etc. - -MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. - -MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also cause `deposit` to revert. - -Note that any unfavorable discrepancy between `convertToShares` and `previewDeposit` SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by depositing. - -```yaml -- name: previewDeposit - type: function - stateMutability: view - - inputs: - - name: assets - type: uint256 - - outputs: - - name: shares - type: uint256 -``` - -#### deposit - -Mints `shares` Vault shares to `receiver` by depositing exactly `assets` of underlying tokens. - -MUST emit the `Deposit` event. - -MUST support EIP-20 `approve` / `transferFrom` on `asset` as a deposit flow. -MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the `deposit` execution, and are accounted for during `deposit`. - -MUST revert if all of `assets` cannot be deposited (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc). - -Note that most implementations will require pre-approval of the Vault with the Vault's underlying `asset` token. - -```yaml -- name: deposit - type: function - stateMutability: nonpayable - - inputs: - - name: assets - type: uint256 - - name: receiver - type: address - - outputs: - - name: shares - type: uint256 -``` - -#### maxMint - -Maximum amount of shares that can be minted from the Vault for the `receiver`, through a `mint` call. - -MUST return the maximum amount of shares `mint` would allow to be deposited to `receiver` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). This assumes that the user has infinite assets, i.e. MUST NOT rely on `balanceOf` of `asset`. - -MUST factor in both global and user-specific limits, like if mints are entirely disabled (even temporarily) it MUST return 0. - -MUST return `2 ** 256 - 1` if there is no limit on the maximum amount of shares that may be minted. - -MUST NOT revert. - -```yaml -- name: maxMint - type: function - stateMutability: view - - inputs: - - name: receiver - type: address - - outputs: - - name: maxShares - type: uint256 -``` - -#### previewMint - -Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. - -MUST return as close to and no fewer than the exact amount of assets that would be deposited in a `mint` call in the same transaction. I.e. `mint` should return the same or fewer `assets` as `previewMint` if called in the same transaction. - -MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint would be accepted, regardless if the user has enough tokens approved, etc. - -MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. - -MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also cause `mint` to revert. - -Note that any unfavorable discrepancy between `convertToAssets` and `previewMint` SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by minting. - -```yaml -- name: previewMint - type: function - stateMutability: view - - inputs: - - name: shares - type: uint256 - - outputs: - - name: assets - type: uint256 -``` - -#### mint - -Mints exactly `shares` Vault shares to `receiver` by depositing `assets` of underlying tokens. - -MUST emit the `Deposit` event. - -MUST support EIP-20 `approve` / `transferFrom` on `asset` as a mint flow. -MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the `mint` execution, and are accounted for during `mint`. - -MUST revert if all of `shares` cannot be minted (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc). - -Note that most implementations will require pre-approval of the Vault with the Vault's underlying `asset` token. - -```yaml -- name: mint - type: function - stateMutability: nonpayable - - inputs: - - name: shares - type: uint256 - - name: receiver - type: address - - outputs: - - name: assets - type: uint256 -``` - -#### maxWithdraw - -Maximum amount of the underlying asset that can be withdrawn from the `owner` balance in the Vault, through a `withdraw` call. - -MUST return the maximum amount of assets that could be transferred from `owner` through `withdraw` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). - -MUST factor in both global and user-specific limits, like if withdrawals are entirely disabled (even temporarily) it MUST return 0. - -MUST NOT revert. - -```yaml -- name: maxWithdraw - type: function - stateMutability: view - - inputs: - - name: owner - type: address - - outputs: - - name: maxAssets - type: uint256 -``` - -#### previewWithdraw - -Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. - -MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a `withdraw` call in the same transaction. I.e. `withdraw` should return the same or fewer `shares` as `previewWithdraw` if called in the same transaction. - -MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though the withdrawal would be accepted, regardless if the user has enough shares, etc. - -MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. - -MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also cause `withdraw` to revert. - -Note that any unfavorable discrepancy between `convertToShares` and `previewWithdraw` SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by depositing. - -```yaml -- name: previewWithdraw - type: function - stateMutability: view - - inputs: - - name: assets - type: uint256 - - outputs: - - name: shares - type: uint256 -``` - -#### withdraw - -Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `receiver`. - -MUST emit the `Withdraw` event. - -MUST support a withdraw flow where the shares are burned from `owner` directly where `owner` is `msg.sender`. - -MUST support a withdraw flow where the shares are burned from `owner` directly where `msg.sender` has EIP-20 approval over the shares of `owner`. - -MAY support an additional flow in which the shares are transferred to the Vault contract before the `withdraw` execution, and are accounted for during `withdraw`. - -SHOULD check `msg.sender` can spend owner funds, assets needs to be converted to shares and shares should be checked for allowance. - -MUST revert if all of `assets` cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc). - -Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: withdraw - type: function - stateMutability: nonpayable - - inputs: - - name: assets - type: uint256 - - name: receiver - type: address - - name: owner - type: address - - outputs: - - name: shares - type: uint256 -``` - -#### maxRedeem - -Maximum amount of Vault shares that can be redeemed from the `owner` balance in the Vault, through a `redeem` call. - -MUST return the maximum amount of shares that could be transferred from `owner` through `redeem` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). - -MUST factor in both global and user-specific limits, like if redemption is entirely disabled (even temporarily) it MUST return 0. - -MUST NOT revert. - -```yaml -- name: maxRedeem - type: function - stateMutability: view - - inputs: - - name: owner - type: address - - outputs: - - name: maxShares - type: uint256 -``` - -#### previewRedeem - -Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. - -MUST return as close to and no more than the exact amount of assets that would be withdrawn in a `redeem` call in the same transaction. I.e. `redeem` should return the same or more `assets` as `previewRedeem` if called in the same transaction. - -MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the redemption would be accepted, regardless if the user has enough shares, etc. - -MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. - -MUST NOT revert due to vault specific user/global limits. MAY revert due to other conditions that would also cause `redeem` to revert. - -Note that any unfavorable discrepancy between `convertToAssets` and `previewRedeem` SHOULD be considered slippage in share price or some other type of condition, meaning the depositor will lose assets by redeeming. - -```yaml -- name: previewRedeem - type: function - stateMutability: view - - inputs: - - name: shares - type: uint256 - - outputs: - - name: assets - type: uint256 -``` - -#### redeem - -Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `receiver`. - -MUST emit the `Withdraw` event. - -MUST support a redeem flow where the shares are burned from `owner` directly where `owner` is `msg.sender`. - -MUST support a redeem flow where the shares are burned from `owner` directly where `msg.sender` has EIP-20 approval over the shares of `owner`. - -MAY support an additional flow in which the shares are transferred to the Vault contract before the `redeem` execution, and are accounted for during `redeem`. - -SHOULD check `msg.sender` can spend owner funds using allowance. - -MUST revert if all of `shares` cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc). - -Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: redeem - type: function - stateMutability: nonpayable - - inputs: - - name: shares - type: uint256 - - name: receiver - type: address - - name: owner - type: address - - outputs: - - name: assets - type: uint256 -``` - -### Events - -#### Deposit - -`sender` has exchanged `assets` for `shares`, and transferred those `shares` to `owner`. - -MUST be emitted when tokens are deposited into the Vault via the `mint` and `deposit` methods. - -```yaml -- name: Deposit - type: event - - inputs: - - name: sender - indexed: true - type: address - - name: owner - indexed: true - type: address - - name: assets - indexed: false - type: uint256 - - name: shares - indexed: false - type: uint256 -``` - -#### Withdraw - -`sender` has exchanged `shares`, owned by `owner`, for `assets`, and transferred those `assets` to `receiver`. - -MUST be emitted when shares are withdrawn from the Vault in `EIP-4626.redeem` or `EIP-4626.withdraw` methods. - -```yaml -- name: Withdraw - type: event - - inputs: - - name: sender - indexed: true - type: address - - name: receiver - indexed: true - type: address - - name: owner - indexed: true - type: address - - name: assets - indexed: false - type: uint256 - - name: shares - indexed: false - type: uint256 -``` - -## Rationale - -The Vault interface is designed to be optimized for integrators with a feature complete yet minimal interface. -Details such as accounting and allocation of deposited tokens are intentionally not specified, -as Vaults are expected to be treated as black boxes on-chain and inspected off-chain before use. - -EIP-20 is enforced because implementation details like token approval -and balance calculation directly carry over to the shares accounting. -This standardization makes the Vaults immediately compatible with all EIP-20 use cases in addition to EIP-4626. - -The mint method was included for symmetry and feature completeness. -Most current use cases of share-based Vaults do not ascribe special meaning to the shares such that -a user would optimize for a specific number of shares (`mint`) rather than specific amount of underlying (`deposit`). -However, it is easy to imagine future Vault strategies which would have unique and independently useful share representations. - -The `convertTo` functions serve as rough estimates that do not account for operation specific details like withdrawal fees, etc. -They were included for frontends and applications that need an average value of shares or assets, not an exact value possibly including slippage or other fees. -For applications that need an exact value that attempts to account for fees and slippage we have included a corresponding `preview` function to match each mutable function. These functions must not account for deposit or withdrawal limits, to ensure they are easily composable, the `max` functions are provided for that purpose. - -## Backwards Compatibility - -EIP-4626 is fully backward compatible with the EIP-20 standard and has no known compatibility issues with other standards. -For production implementations of Vaults which do not use EIP-4626, wrapper adapters can be developed and used. - -## Reference Implementation - -See [Solmate EIP-4626](https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol): -a minimal and opinionated implementation of the standard with hooks for developers to easily insert custom logic into deposits and withdrawals. - -See [Vyper EIP-4626](https://github.com/fubuloubu/ERC4626): -a demo implementation of the standard in Vyper, with hooks for share price manipulation and other testing needs. - -## Security Considerations - -Fully permissionless use cases could fall prey to malicious implementations which only conform to the interface but not the specification. -It is recommended that all integrators review the implementation for potential ways of losing user deposits before integrating. - -If implementors intend to support EOA account access directly, they should consider adding an additional function call for `deposit`/`mint`/`withdraw`/`redeem` with the means to accommodate slippage loss or unexpected deposit/withdrawal limits, since they have no other means to revert the transaction if the exact output amount is not achieved. - -The methods `totalAssets`, `convertToShares` and `convertToAssets` are estimates useful for display purposes, -and do _not_ have to confer the _exact_ amount of underlying assets their context suggests. - -The `preview` methods return values that are as close as possible to exact as possible. For that reason, they are manipulable by altering the on-chain conditions and are not always safe to be used as price oracles. This specification includes `convert` methods that are allowed to be inexact and therefore can be implemented as robust price oracles. For example, it would be correct to implement the `convert` methods as using a time-weighted average price in converting between assets and shares. - -Integrators of EIP-4626 Vaults should be aware of the difference between these view methods when integrating with this standard. Additionally, note that the amount of underlying assets a user may receive from redeeming their Vault shares (`previewRedeem`) can be significantly different than the amount that would be taken from them when minting the same quantity of shares (`previewMint`). The differences may be small (like if due to rounding error), or very significant (like if a Vault implements withdrawal or deposit fees, etc). Therefore integrators should always take care to use the preview function most relevant to their use case, and never assume they are interchangeable. - -Finally, EIP-4626 Vault implementers should be aware of the need for specific, opposing rounding directions across the different mutable and view methods, as it is considered most secure to favor the Vault itself during calculations over its users: - -- If (1) it's calculating how many shares to issue to a user for a certain amount of the underlying tokens they provide or (2) it's determining the amount of the underlying tokens to transfer to them for returning a certain amount of shares, it should round _down_. - -- If (1) it's calculating the amount of shares a user has to supply to receive a given amount of the underlying tokens or (2) it's calculating the amount of underlying tokens a user has to provide to receive a certain amount of shares, it should round _up_. - -The only functions where the preferred rounding direction would be ambiguous are the `convertTo` functions. To ensure consistency across all EIP-4626 Vault implementations it is specified that these functions MUST both always round _down_. Integrators may wish to mimic rounding up versions of these functions themselves, like by adding 1 wei to the result. - -Although the `convertTo` functions should eliminate the need for any use of an EIP-4626 Vault's `decimals` variable, it is still strongly recommended to mirror -the underlying token's `decimals` if at all possible, to eliminate possible sources of confusion and simplify integration across front-ends and for other off-chain users. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4626.md diff --git a/EIPS/eip-4671.md b/EIPS/eip-4671.md index f7f55b91e7d710..8362070fa3fda9 100644 --- a/EIPS/eip-4671.md +++ b/EIPS/eip-4671.md @@ -1,296 +1,7 @@ --- eip: 4671 -title: Non-Tradable Tokens Standard -description: A standard interface for non-tradable tokens, aka badges or souldbound NFTs. -author: Omar Aflak (@omaraflak), Pol-Malo Le Bris, Marvin Martin (@MarvinMartin24) -discussions-to: https://ethereum-magicians.org/t/eip-4671-non-tradable-token/7976 -status: Stagnant -type: Standards Track category: ERC -created: 2022-01-13 -requires: 165 +status: Moved --- -## Abstract - -A non-tradable token, or NTT, represents inherently personal possessions (material or immaterial), such as university diplomas, online training certificates, government issued documents (national id, driving license, visa, wedding, etc.), labels, and so on. - -As the name implies, non-tradable tokens are made to not be traded or transferred, they are "soulbound". They don't have monetary value, they are personally delivered to **you**, and they only serve as a **proof of possession/achievement**. - -In other words, the possession of a token carries a strong meaning in itself depending on **why** it was delivered. - -## Motivation - -We have seen in the past smart contracts being used to deliver university diplomas or driving licenses, for food labeling or attendance to events, and much more. All of these implementations are different, but they have a common ground: the tokens are **non-tradable**. - -The blockchain has been used for too long as a means of speculation, and non-tradable tokens want to be part of the general effort aiming to provide usefulness through the blockchain. - -By providing a common interface for non-tradable tokens, we allow more applications to be developed and we position blockchain technology as a standard gateway for verification of personal possessions and achievements. - -## Specification - -### Non-Tradable Token - -A NTT contract is seen as representing **one type of certificate** delivered by **one authority**. For instance, one NTT contract for the French National Id, another for Ethereum EIP creators, and so on... - -* An address might possess multiple tokens. Each token has a unique identifier: `tokenId`. -* An authority who delivers a certificate should be in position to revoke it. Think of driving licenses or weddings. However, it cannot delete your token, i.e. the record will show that you once owned a token from that contract. -* The most typical usage for third-parties will be to verify if a user has a valid token in a given contract. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -interface IERC4671 is IERC165 { - /// Event emitted when a token `tokenId` is minted for `owner` - event Minted(address owner, uint256 tokenId); - - /// Event emitted when token `tokenId` of `owner` is revoked - event Revoked(address owner, uint256 tokenId); - - /// @notice Count all tokens assigned to an owner - /// @param owner Address for whom to query the balance - /// @return Number of tokens owned by `owner` - function balanceOf(address owner) external view returns (uint256); - - /// @notice Get owner of a token - /// @param tokenId Identifier of the token - /// @return Address of the owner of `tokenId` - function ownerOf(uint256 tokenId) external view returns (address); - - /// @notice Check if a token hasn't been revoked - /// @param tokenId Identifier of the token - /// @return True if the token is valid, false otherwise - function isValid(uint256 tokenId) external view returns (bool); - - /// @notice Check if an address owns a valid token in the contract - /// @param owner Address for whom to check the ownership - /// @return True if `owner` has a valid token, false otherwise - function hasValid(address owner) external view returns (bool); -} -``` - -#### Extensions - -##### Metadata - -An interface allowing to add metadata linked to each token. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC4671.sol"; - -interface IERC4671Metadata is IERC4671 { - /// @return Descriptive name of the tokens in this contract - function name() external view returns (string memory); - - /// @return An abbreviated name of the tokens in this contract - function symbol() external view returns (string memory); - - /// @notice URI to query to get the token's metadata - /// @param tokenId Identifier of the token - /// @return URI for the token - function tokenURI(uint256 tokenId) external view returns (string memory); -} -``` - -##### Enumerable - -An interface allowing to enumerate the tokens of an owner. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC4671.sol"; - -interface IERC4671Enumerable is IERC4671 { - /// @return emittedCount Number of tokens emitted - function emittedCount() external view returns (uint256); - - /// @return holdersCount Number of token holders - function holdersCount() external view returns (uint256); - - /// @notice Get the tokenId of a token using its position in the owner's list - /// @param owner Address for whom to get the token - /// @param index Index of the token - /// @return tokenId of the token - function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); - - /// @notice Get a tokenId by it's index, where 0 <= index < total() - /// @param index Index of the token - /// @return tokenId of the token - function tokenByIndex(uint256 index) external view returns (uint256); -} -``` - -##### Delegation - -An interface allowing delegation rights of token minting. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC4671.sol"; - -interface IERC4671Delegate is IERC4671 { - /// @notice Grant one-time minting right to `operator` for `owner` - /// An allowed operator can call the function to transfer rights. - /// @param operator Address allowed to mint a token - /// @param owner Address for whom `operator` is allowed to mint a token - function delegate(address operator, address owner) external; - - /// @notice Grant one-time minting right to a list of `operators` for a corresponding list of `owners` - /// An allowed operator can call the function to transfer rights. - /// @param operators Addresses allowed to mint - /// @param owners Addresses for whom `operators` are allowed to mint a token - function delegateBatch(address[] memory operators, address[] memory owners) external; - - /// @notice Mint a token. Caller must have the right to mint for the owner. - /// @param owner Address for whom the token is minted - function mint(address owner) external; - - /// @notice Mint tokens to multiple addresses. Caller must have the right to mint for all owners. - /// @param owners Addresses for whom the tokens are minted - function mintBatch(address[] memory owners) external; - - /// @notice Get the issuer of a token - /// @param tokenId Identifier of the token - /// @return Address who minted `tokenId` - function issuerOf(uint256 tokenId) external view returns (address); -} -``` - -##### Consensus - -An interface allowing minting/revocation of tokens based on a consensus of a predefined set of addresses. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC4671.sol"; - -interface IERC4671Consensus is IERC4671 { - /// @notice Get voters addresses for this consensus contract - /// @return Addresses of the voters - function voters() external view returns (address[] memory); - - /// @notice Cast a vote to mint a token for a specific address - /// @param owner Address for whom to mint the token - function approveMint(address owner) external; - - /// @notice Cast a vote to revoke a specific token - /// @param tokenId Identifier of the token to revoke - function approveRevoke(uint256 tokenId) external; -} -``` - -##### Pull - -An interface allowing a token owner to pull his token to a another of his wallets (here `recipient`). The caller must provide a signature of the tuple `(tokenId, owner, recipient)` using the `owner` wallet. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC4671.sol"; - -interface IERC4671Pull is IERC4671 { - /// @notice Pull a token from the owner wallet to the caller's wallet - /// @param tokenId Identifier of the token to transfer - /// @param owner Address that owns tokenId - /// @param signature Signed data (tokenId, owner, recipient) by the owner of the token - function pull(uint256 tokenId, address owner, bytes memory signature) external; -} -``` - -### NTT Store - -Non-tradable tokens are meant to be fetched by third-parties, which is why there needs to be a convenient way for users to expose some or all of their tokens. We achieve this result using a store which must implement the following interface. - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -interface IERC4671Store is IERC165 { - // Event emitted when a IERC4671Enumerable contract is added to the owner's records - event Added(address owner, address token); - - // Event emitted when a IERC4671Enumerable contract is removed from the owner's records - event Removed(address owner, address token); - - /// @notice Add a IERC4671Enumerable contract address to the caller's record - /// @param token Address of the IERC4671Enumerable contract to add - function add(address token) external; - - /// @notice Remove a IERC4671Enumerable contract from the caller's record - /// @param token Address of the IERC4671Enumerable contract to remove - function remove(address token) external; - - /// @notice Get all the IERC4671Enumerable contracts for a given owner - /// @param owner Address for which to retrieve the IERC4671Enumerable contracts - function get(address owner) external view returns (address[] memory); -} -``` - -## Rationale - -### On-chain vs Off-chain - -A decision was made to keep the data off-chain (via `tokenURI()`) for two main reasons: -* Non-tradable tokens represent personal possessions. Therefore, there might be cases where the data should be encrypted. The standard should not outline decisions about encryption because there are just so many ways this could be done, and every possibility is specific to the use-case. -* Non-tradable tokens must stay generic. There could have been a possibility to make a `MetadataStore` holding the data of tokens in an elegant way, unfortunately we would have needed a support for generics in solidity (or struct inheritance), which is not available today. - -## Reference Implementation - -You can find an implementation of this standard in [../assets/eip-4671](https://github.com/ethereum/EIPs/tree/master/assets/eip-4671). - -Using this implementation, this is how you would create a token: - -```solidity -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -import "./ERC4671.sol"; - -contract EIPCreatorBadge is ERC4671 { - constructor() ERC4671("EIP Creator Badge", "EIP") {} - - function giveThatManABadge(address owner) external { - require(_isCreator(), "You must be the contract creator"); - _mint(owner); - } - - function _baseURI() internal pure override returns (string memory) { - return "https://eips.ethereum.org/ntt/"; - } -} -``` - -This could be a contract managed by the Ethereum foundation and which allows them to deliver tokens to EIP creators. - -## Security Considerations - -One security aspect is related to the `tokenURI` method which returns the metadata linked to a token. Since the standard represents inherently personal possessions, users might want to encrypt the data in some cases e.g. national id cards. Moreover, it is the responsibility of the contract creator to make sure the URI returned by this method is available at all times. - -The standard does not define any way to transfer a token from one wallet to another. Therefore, users must be very cautious with the wallet they use to receive these tokens. If a wallet is lost, the only way to get the tokens back is for the issuing authorities to deliver the tokens again, akin real life. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4671.md diff --git a/EIPS/eip-4675.md b/EIPS/eip-4675.md index 6e04d3f3ef53ed..07210894d9c9cc 100644 --- a/EIPS/eip-4675.md +++ b/EIPS/eip-4675.md @@ -1,213 +1,7 @@ --- eip: 4675 -title: Multi-Fractional Non-Fungible Tokens -description: Fractionalize multiple NFTs using a single contract -author: David Kim (@powerstream3604) -discussions-to: https://ethereum-magicians.org/t/eip-4675-multi-fractional-non-fungible-token-standard/8008 -status: Draft -type: Standards Track category: ERC -created: 2022-01-13 -requires: 165, 721 +status: Moved --- -## Abstract -This standard outlines a smart contract interface eligible to represent any number of fractionalized non-fungible tokens. Existing projects utilizing standards like [EIP-1633](./eip-1633.md) conventionally deploy separate [EIP-20](./eip-20.md) compatible token contracts to fractionalize the non-fungible token into EIP-20 tokens. In contrast, this ERC allows each token ID to represent a token type representing(fractionalizing) the non-fungible token. - -This standard is approximate in terms of using `_id` for distinguishing token types. However, this ERC has a clear difference with [EIP-1155](./eip-1155.md) as each `_id` represents a distinct NFT. - -## Motivation -The conventional fractionalization process of fractionalizing a NFT to FT requires deployment of a FT token contract representing the ownership of NFT. This leads to inefficient bytecode usage on Ethereum Blockchain and limits functionalities since each token contract is separated into its own permissioned address. -With the rise of multiple NFT projects needing to fractionalize NFT to FT, new type of token standard is needed to back up them. - -## Specification - -```solidity -/** - @title Multi-Fractional Non-Fungible Token Standard - @dev Note : The ERC-165 identifier for this interface is 0x83f5d35f. -*/ -interface IMFNFT { - /** - @dev This emits when ownership of any token changes by any mechanism. - The `_from` argument MUST be the address of an account/contract sending the token. - The `_to` argument MUST be the address of an account/contract receiving the token. - The `_id` argument MUST be the token type being transferred. (represents NFT) - The `_value` argument MUST be the number of tokens the holder balance is decrease by and match the recipient balance is increased by. - */ - event Transfer(address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value); - - /** - @dev This emits when the approved address for token is changed or reaffirmed. - The `_owner` argument MUST be the address of account/contract approving to withdraw. - The `_spender` argument MUST be the address of account/contract approved to withdraw from the `_owner` balance. - The `_id` argument MUST be the token type being transferred. (represents NFT) - The `_value` argument MUST be the number of tokens the `_approved` is able to withdraw from `_owner` balance. - */ - event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _value); - - /** - @dev This emits when new token type is added which represents the share of the Non-Fungible Token. - The `_parentToken` argument MUST be the address of the Non-Fungible Token contract. - The `_parentTokenId` argument MUST be the token ID of the Non-Fungible Token. - The `_id` argument MUST be the token type being added. (represents NFT) - The `_totalSupply` argument MUST be the number of total token supply of the token type. - */ - event TokenAddition(address indexed _parentToken, uint256 indexed _parentTokenId, uint256 _id, uint256 _totalSupply); - - /** - @notice Transfers `_value` amount of an `_id` from the msg.sender address to the `_to` address specified - @dev msg.sender must have sufficient balance to handle the tokens being transferred out of the account. - MUST revert if `_to` is the zero address. - MUST revert if balance of msg.sender for token `_id` is lower than the `_value` being transferred. - MUST revert on any other error. - MUST emit the `Transfer` event to reflect the balance change. - @param _to Source address - @param _id ID of the token type - @param _value Transfer amount - @return True if transfer was successful, false if not - */ - function transfer(address _to, uint256 _id, uint256 _value) external returns (bool); - - /** - @notice Approves `_value` amount of an `_id` from the msg.sender to the `_spender` address specified. - @dev msg.sender must have sufficient balance to handle the tokens when the `_spender` wants to transfer the token on behalf. - MUST revert if `_spender` is the zero address. - MUST revert on any other error. - MUST emit the `Approval` event. - @param _spender Spender address(account/contract which can withdraw token on behalf of msg.sender) - @param _id ID of the token type - @param _value Approval amount - @return True if approval was successful, false if not - */ - function approve(address _spender, uint256 _id, uint256 _value) external returns (bool); - - /** - @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified. - @dev Caller must be approved to manage the tokens being transferred out of the `_from` account. - MUST revert if `_to` is the zero address. - MUST revert if balance of holder for token `_id` is lower than the `_value` sent. - MUST revert on any other error. - MUST emit `Transfer` event to reflect the balance change. - @param _from Source address - @param _to Target Address - @param _id ID of the token type - @param _value Transfer amount - @return True if transfer was successful, false if not - - */ - function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external returns (bool); - - /** - @notice Sets the NFT as a new type token - @dev The contract itself should verify if the ownership of NFT is belongs to this contract itself with the `_parentNFTContractAddress` & `_parentNFTTokenId` before adding the token. - MUST revert if the same NFT is already registered. - MUST revert if `_parentNFTContractAddress` is address zero. - MUST revert if `_parentNFTContractAddress` is not ERC-721 compatible. - MUST revert if this contract itself is not the owner of the NFT. - MUST revert on any other error. - MUST emit `TokenAddition` event to reflect the token type addition. - @param _parentNFTContractAddress NFT contract address - @param _parentNFTTokenId NFT tokenID - @param _totalSupply Total token supply - */ - function setParentNFT(address _parentNFTContractAddress, uint256 _parentNFTTokenId, uint256 _totalSupply) external; - - /** - @notice Get the token ID's total token supply. - @param _id ID of the token - @return The total token supply of the specified token type - */ - function totalSupply(uint256 _id) external view returns (uint256); - - /** - @notice Get the balance of an account's tokens. - @param _owner The address of the token holder - @param _id ID of the token - @return The _owner's balance of the token type requested - */ - function balanceOf(address _owner, uint256 _id) external view returns (uint256); - - /** - @notice Get the amount which `_spender` is still allowed to withdraw from `_owner` - @param _owner The address of the token holder - @param _spender The address approved to withdraw token on behalf of `_owner` - @param _id ID of the token - @return The amount which `_spender` is still allowed to withdraw from `_owner` - */ - function allowance(address _owner, address _spender, uint256 _id) external view returns (uint256); - - /** - @notice Get the bool value which represents whether the NFT is already registered and fractionalized by this contract. - @param _parentNFTContractAddress NFT contract address - @param _parentNFTTokenId NFT tokenID - @return The bool value representing the whether the NFT is already registered. - */ - function isRegistered(address _parentNFTContractAddress, uint256 _parentNFTTokenId) external view returns (bool); -} - -interface ERC165 { - /** - @notice Query if a contract implements an interface - @param interfaceID The interface identifier, as specified in ERC-165 - @dev Interface identification is specified in ERC-165. This function - uses less than 30,000 gas. - @return `true` if the contract implements `interfaceID` and - `interfaceID` is not 0xffffffff, `false` otherwise - */ - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -To receive Non-Fungible Token on `safe Transfer` the contract should include `onERC721Received()`. -Including `onERC721Received()` is needed to be compatible with Safe Transfer Rules. -```solidity -/** - @notice Handle the receipt of an NFT - @param _operator The address which called `safeTransferFrom` function - @param _from The address which previously owned the token - @param _tokenId The NFT identifier which is being transferred - @param _data Additional data with no specified format - @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` -*/ -function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external pure returns (bytes4); -``` - -## Rationale - -**Metadata** - -The `symbol()` & `name()` functions were not included since the majority of users can just fetch it from the originating NFT contract. Also, copying the name & symbol every time when token gets added might place a lot of redundant bytecode on the Ethereum blockchain. -However, according to the need and design of the project it could also be added to each token type by fetching the metadata from the NFT contract. - -**Design** - -Most of the decisions made around the design of this ERC were done to keep it as flexible for diverse token design & architecture. -These minimum requirement for this standard allows for each project to determine their own system for minting, governing, burning their MFNFT tokens depending on their programmable architecture. - -## Backwards Compatibility - -To make this standard compatible with existing standards, this standard `event` & `function` names are identical with ERC-20 token standard with some more `events` & `functions` to add token type dynamically. - -Also, the sequence of parameter in use of `_id` for distinguishing token types in `functions` and `events` are very much similar to ERC-1155 Multi-Token Standard. - -Since this standard is intended to interact with the EIP-721 Non-Fungible Token Standard, it is kept purposefully agnostic to extensions beyond the standard in order to allow specific projects to design their own token usage and scenario. - -## Test Cases - -Reference Implementation of MFNFT Token includes test cases written using hardhat. (Test coverage : 100%) - -## Reference Implementation -[MFNFT - Implementation](../assets/eip-4675/README.md) - -## Security Considerations - -To fractionalize an already minted NFT, it is evident that ownership of NFT should be given to token contracts before fractionalization. -In the case of fractionalizing NFT, the token contract should thoroughly verify the ownership of NFT before fractionalizing it to prevent tokens from being a separate tokens with the NFT. - -If an arbitrary account has the right to call `setParentNFT()` there might be a front-running issue. The caller of `setParentNFT()` might be different from the real NFT sender. -To prevent this issue, implementors should just allow **admin** to call, or fractionalize and receive NFT in an atomic transaction similar to flash loan(swap). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4675.md diff --git a/EIPS/eip-4736.md b/EIPS/eip-4736.md index cca49f44af6d67..3266787337e5d9 100644 --- a/EIPS/eip-4736.md +++ b/EIPS/eip-4736.md @@ -1,10 +1,10 @@ --- eip: 4736 title: Consensus Layer Withdrawal Protection -description: Additional security for "set withdrawal address" operation when a consensus layer mnemonic may be compromised, without changing consensus +description: Additional security for BLSToExecutionChange operation when a consensus layer mnemonic may be compromised, without changing consensus author: Benjamin Chodroff (@benjaminchodroff), Jim McDonald (@mcdee) discussions-to: https://ethereum-magicians.org/t/consensus-layer-withdrawal-protection/8161 -status: Review +status: Final type: Standards Track category: Interface created: 2022-01-30 @@ -12,17 +12,17 @@ created: 2022-01-30 ## Abstract -If a consensus layer mnemonic phrase is compromised, it is impossible for the consensus layer network to differentiate the "legitimate" holder of the key from an "illegitimate" holder. However, there are signals that can be considered in a wider sense without changing core Ethereum consensus. This proposal outlines ways in which the execution layer deposit address, a consensus layer rebroadcast delay, and list of signed messages could create a social consensus that would significantly favor but not guarantee legitimate mnemonic holders would win a race condition against an attacker, while not changing core Ethereum consensus. +If a consensus layer mnemonic phrase is compromised, it is impossible for the consensus layer network to differentiate the legitimate holder of the key from an illegitimate holder. However, there are signals that can be considered in a wider sense without changing core Ethereum consensus. This proposal outlines ways in which on chain evidence such as the execution layer deposit address and list of signed messages could create a social consensus that would significantly favor but not guarantee legitimate mnemonic holders would win a race condition against an attacker. ## Motivation -The consensus layer set withdrawal address proposal is secure for a single user who has certainty their keys and mnemonic have not been compromised. However, as validator withdrawals on the consensus layer are not yet possible, no user can have absolute certainty that their keys are not compromised until the set withdrawal address is on chain, and by then too late to change. All legitimate mnemonic phrase holders were originally in control of the execution layer deposit address. Beacon node clients and node operators may optionally load a list of verifiable deposit addresses, a list of verifiable set withdrawal address messages to broadcasts, and specify a rebroadcast delay that may create a social consensus for legitimate holders to successfully win a race condition against an attacker. If attackers compromise a significant number of consensus layer nodes, it would pose risks to the entire Ethereum community. +The consensus layer `BLSToExecutionChange` message is secure for a single user who has certainty their keys and mnemonic have not been compromised. However, as validator withdrawals on the consensus layer are not possible until the Capella hard fork, no user can have absolute certainty that their keys are not compromised until the `BLSToExecutionChange` is on chain, and by then too late to change. All legitimate mnemonic phrase holders were originally in control of the execution layer deposit address. Beacon node clients and node operators may optionally load a list of verifiable `BLSToExecutionChange` messages to broadcasts that may create a social consensus for legitimate holders to successfully win a race condition against an attacker. If attackers compromise a significant number of consensus layer nodes, it would pose risks to the entire Ethereum community. -Setting a withdrawal address to an execution layer address was not supported by the eth2.0-deposit-cli until v1.1.1 on March 23, 2021, leaving early adopters wishing they could force set their execution layer address earlier. Forcing this change is not something that can be enforced in-protocol, partly due to lack of information on the beacon chain about the execution layer deposit address and partly due to the fact that this was never listed as a requirement. It is also possible that the execution layer deposit address is no longer under the control of the legitimate holder of the withdrawal private key. +Setting a withdrawal address to an execution layer address was not supported by the eth2.0-deposit-cli until v1.1.1 on March 23, 2021, leaving early adopters wishing they could force set their execution layer address to a deposit address earlier. Forcing this change is not something that can be enforced in-protocol, partly due to lack of information on the beacon chain about the execution layer deposit address and partly due to the fact that this was never listed as a requirement. It is also possible that the execution layer deposit address is no longer under the control of the legitimate holder of the withdrawal private key. -However, it is possible for individual nodes to locally restrict the changes they wish to include in blocks they propose, and which they propagate around the network, in a way that does not change consensus. It is also possible for client nodes to help broadcast signed set withdrawal address requests to ensure as many nodes witness this message as soon as possible in a fair manner. Further, such set withdrawal address signed messages can be preloaded into clients in advance to further help nodes filter attacking requests. +However, it is possible for individual nodes to locally restrict the changes they wish to include in blocks they propose, and which they propagate around the network, in a way that does not change consensus. It is also possible for client nodes to help broadcast signed `BLSToExecutionChange` requests to ensure as many nodes witness this message as soon as possible in a fair manner. Further, such `BLSToExecutionChange` signed messages can be preloaded into clients in advance to further help nodes filter attacking requests. -This proposal provides purely optional additional protection. It aims to request nodes set a priority on withdrawal credential claims that favour a verifiable execution layer deposit address in the event of two conflicting set withdrawal credentials. It also establishes a list of set withdrawal address signed messages to help broadcast "as soon as possible" when the network supports it, and encourage client teams to help use these lists to honour filter and prioritize accepting requests by REST and transmitting them via P2P. This will not change consensus, but may help prevent propagating an attack where a withdrawal key has been knowingly or unknowingly compromised. +This proposal provides purely optional additional protection. It aims to request nodes set a priority on withdrawal credential claims that favour a verifiable execution layer deposit address in the event of two conflicting `BLSToExecutionChange` messages. It also establishes a list of `BLSToExecutionChange` signed messages to help broadcast "as soon as possible" when the network supports it, and encourage client teams to help use these lists to honour filter and prioritize accepting requests by REST and transmitting them via P2P. This will not change consensus, but may help prevent propagating an attack where a withdrawal key has been knowingly or unknowingly compromised. It is critical to understand that this proposal is not a consensus change. Nothing in this proposal restricts the validity of withdrawal credential operations within the protocol. It is a voluntary change by client teams to build this functionality in to their beacon nodes, and a voluntary change by node operators to accept any or all of the restrictions and broadcasting capabilities suggested by end users. @@ -30,67 +30,44 @@ Because of the above, even if fully implemented, it will be down to chance as to ## Specification -The Consensus Layer set withdrawal credentials operation MUST have at least the following fields: +The Consensus Layer `BLSToExecutionChange` operation has the following fields: * Validator index * Current withdrawal BLS public key * Proposed execution layer withdrawal address * Signature by withdrawal private key over the prior fields -This proposal describes three OPTIONAL and RECOMMENDED mechanisms which a client beacon node MAY implement, and end users are RECOMMENDED to use in their beacon node operation. +This proposal describes OPTIONAL and RECOMMENDED mechanisms which a client beacon node MAY implement, and end users are RECOMMENDED to use in their beacon node operation. -### 1. Set Withdrawal Address Broadcast File +### `BLSToExecutionChange` Broadcast File -Beacon node clients MAY support an OPTIONAL file of lines specifying "validator index" , "current withdrawal BLS public key" , "proposed execution layer withdrawal address", and "signature" which, if implemented and if provided, SHALL instruct nodes to automatically submit a one-time set withdrawal address broadcast message for each valid signature at the block height the network supports a "set withdrawal address" operation. This file SHALL give all node operators an OPTIONAL opportunity to ensure any valid set withdrawal address messages are broadcast, heard, and shared by nodes during the first epoch supporting the set withdrawal address operation. This OPTIONAL file SHALL also instruct nodes to perpetually prefer accepting and repeating signatures matching the signature in the file, and SHALL reject accepting or rebroadcasting messages which do not match a signature for a given withdrawal credential. +Beacon node clients MAY support an OPTIONAL file of lines specifying "validator index" , "current withdrawal BLS public key" , "proposed execution layer withdrawal address", and "signature" which, if implemented and if provided, SHALL instruct nodes to automatically submit a one-time `BLSToExecutionChange` broadcast message for each valid signature at the Capella hard fork. This file SHALL give all node operators an OPTIONAL opportunity to ensure any valid `BLSToExecutionChange` messages are broadcast, heard, and shared by nodes at the Capella hard fork. This OPTIONAL file SHALL also instruct nodes to perpetually prefer accepting and repeating signatures matching the signature in the file, and SHALL reject accepting or rebroadcasting messages which do not match a signature for a given withdrawal credential. -### 2. Set Withdrawal Address Rebroadcast Delay +### `BLSToExecutionChange` Handling -Beacon node clients MAY implement an OPTIONAL time measurement parameter "set withdrawal address rebroadcast delay" that, if implemented and if provided, SHALL create a delay in rebroadcasting set withdrawal addresses (RECOMMENDED to default to 2000 seconds (>5 epochs), or OPTIONAL set to 0 seconds for no delay, or MAY set to -1 to strictly only rebroadcast requests matching a "Set Withdrawal Address Broadcast" entry). This setting SHALL allow set withdrawal address requests time for peer replication of client accepted valid requests that are preferred by the community. This MAY prevent a "first to arrive" critical race condition for a conflicting set withdraw address. - -### Set Withdrawal Address Handling - -Beacon node clients are RECOMMENDED to first rely on a "Set Withdrawal Address Broadcast" file of verifiable signatures, and then MAY fallback to accept a "first request" but delay in rebroadcasting it via P2P. All of this proposal is OPTIONAL for beacon nodes to implement or use, but all client teams are RECOMMENDED to include a copy or link to the uncontested verification file and RECOMMENDED enable it by default to protect the entire Ethereum community. This OPTIONAL protection will prove the user was both in control of the consensus layer and execution layer address, while making sure their intended set withdrawal address message is ready to broadcast as soon as the network supports it. - -If a node is presented with a set withdrawal address operation via the REST API or P2P, they are RECOMMENDED to follow this process: - -A) Withdrawal credential found in "Set Withdrawal Address Broadcast" file: - - 1. Signature Match: If a valid set withdrawal request signature is received for a withdrawal credential that matches the first signature found in the "Set Withdrawal Address Broadcast" file, accept it via REST API, rebroadcast it via P2P, and drop any pending “first preferred” if existing. - 2. Signature Mismatch: If a valid set withdrawal request is received for a withdrawal credential that does not match the first signature found in the "Set Withdrawal Address Broadcast" file, reject it via REST API, and drop it to prevent rebroadcasting it via P2P. - -B) Withdrawal credential not found in or no "Set Withdrawal Address Broadcast" file provided, or capability not implemented in the client: - -1. Matching withdraw credential and withdraw address in "Set Withdrawal Address Broadcast" file: If a valid set withdrawal address request is received for a withdrawal credential that matches the first found withdrawal address provided in the "Set Withdrawal Address Broadcast" file, accept it via REST API, rebroadcast it via P2P, and drop any pending “first preferred” if existing. -2. Mismatching withdraw credential and withdraw address in "Set Withdrawal Address Broadcast" file: If a valid set withdrawal request is received for a withdrawal credential that does not match the first found withdrawal address provided in the "withdrawal address" file, reject it via REST API, and drop it to prevent rebroadcasting it via P2P. -3. Missing withdraw address in or no "Set Withdrawal Address Broadcast" file: - - i. First Preferred: If first valid set withdrawal address request is received for a not finalized withdrawal credential that does not have any listed withdrawal credential entry in the "Set Withdrawal Address Broadcast" file, accept it via REST API, but do not yet rebroadcast it via P2P (“grace period”) and do not yet propose any local blocks with this message. Once the client “Set Withdrawal Address Grace Period” has expired and no other messages have invalidated this message, rebroadcast the request via P2P and include in locally built blocks if not already present. - - ii. Subsequent Rejected: If an existing valid "First Preferred" request exists for a not finalized withdrawal credential, reject it via REST API, and drop it to prevent rebroadcasting via P2P. - -Note that these restrictions SHALL NOT apply to set withdrawal credential operations found in blocks. If any operation has been included on-chain, it MUST by definition be valid regardless of its contents or protective mechanisms described above. +Beacon node clients are RECOMMENDED to allow accepting "`BLSToExecutionChange` Broadcast" file of verifiable signatures, and then MAY fallback to accept a "first request" via P2P. All of this proposal is OPTIONAL for beacon nodes to implement or use, but all client teams are RECOMMENDED to allow a "`BLSToExecutionChange` Broadcast File" to be loaded locally before the Capella hard fork. This OPTIONAL protection will allow a user to attempt to set a withdrawal address message as soon as the network supports it without any change to consensus. ## Rationale -This proposal is intended to protect legitimate mnemonic phrase holders where the phrase was knowingly or unknowingly compromised. As there is no safe way to transfer ownership of a validator without exiting, it can safely be assumed that all current validator holders intend to set to a withdrawal address they specify. Using the deposit address in the execution layer to determine the legitimate holder is not possible to consider in consensus as it may be far back in history and place an overwhelming burden to maintain such a list. As such, this proposal outlines optional mechanism which protect legitimate original mnemonic holders and does so in a way that does not place any mandatory burden on client node software or operators. +This proposal is intended to protect legitimate validator mnemonic holders where it was knowingly or unknowingly compromised. As there is no safe way to transfer ownership of a validator without exiting, it can safely be assumed that all validator holders intend to set to a withdrawal address they specify. Using the deposit address in the execution layer to determine the legitimate holder is not possible to consider in consensus as it may be far back in history and place an overwhelming burden to maintain such a list. As such, this proposal outlines optional mechanism which protect legitimate original mnemonic holders and does so in a way that does not place any mandatory burden on client node software or operators. ## Backwards Compatibility -As there is currently no existing "set withdrawal address" operation, there is no documented backwards compatibility. As all of the proposal is OPTIONAL in both implementation and operation, it is expected that client beacon nodes that do not implement this functionality would still remain fully backwards compatible with any or all clients that do implement part or all of the functionality described in this proposal. Additionally, while users are RECOMMENDED to enable these OPTIONAL features, if they decide to either disable or ignore some or all of the features, or even purposefully load content contrary to the intended purpose, the beacon node client will continue to execute fully compatible with the rest of the network as none of the proposal will change core Ethereum consensus. +As there is no existing `BLSToExecutionChange` operation prior to Capella, there is no documented backwards compatibility. As all of the proposal is OPTIONAL in both implementation and operation, it is expected that client beacon nodes that do not implement this functionality would still remain fully backwards compatible with any or all clients that do implement part or all of the functionality described in this proposal. Additionally, while users are RECOMMENDED to enable these OPTIONAL features, if they decide to either disable or ignore some or all of the features, or even purposefully load content contrary to the intended purpose, the beacon node client will continue to execute fully compatible with the rest of the network as none of the proposal will change core Ethereum consensus. ## Reference Implementation -### Set Withdrawal Address Broadcast File +### `BLSToExecutionChange` Broadcast File A "change-operations.json" file intended to be preloaded with all consensus layer withdrawal credential signatures and verifiable execution layer deposit addresses. This file may be generated by a script and able to be independently verified by community members using the consensus layer node, and intended to be included by all clients, enabled by default. Client nodes are encouraged to enable packaging this independently verifiable list with the client software, and enable it by default to help further protect the community from unsuspected attacks. -The change-operations.json format is the "Set Withdrawal Address File - Claim" combined into a single JSON array. +The change-operations.json format is the "`BLSToExecutionChange` File - Claim" combined into a single JSON array. -### Set Withdrawal Address Broadcast File - Claim +### `BLSToExecutionChange` Broadcast File - Claim -A community collected and independently verifiable list of "Set Withdrawal Address Broadcasts" containing verifiable claims will be collected. Client teams and node operators may verify these claims independently and are suggested to include "Uncontested and Verified" claims enabled by default in their package. +A community collected and independently verifiable list of "`BLSToExecutionChange` Broadcasts" containing verifiable claims will be collected. Node operators may verify these claims independently and are suggested to load claims in compatible beacon node clients. -To make a verifiable claim, users MAY upload using their GitHub ID with the following contents to the CLWP repository in a text file "[chain]/validatorIndex.json" such as "mainnet/123456.json" or MAY construct a repository of their own. +To make a verifiable claim, users MAY upload a claim to any public repository in a text file "[chain]/validatorIndex.json" such as "mainnet/123456.json". 123456.json: @@ -100,20 +77,20 @@ To make a verifiable claim, users MAY upload using their GitHub ID with the foll #### Claim Acceptance -In order for a submission to be merged into CLWP GitHub repository, the submission must have: +In order for a submission to be merged into public repository, the submission must have: 1. Valid filename in the format validatorIndex.json 2. Valid validator index which is active on the consensus layer 3. Verifiable signature 5. A single change operation for a single validator, with all required fields in the file with no other content present -All merge requests that fail will be provided a reason from above which must be addressed prior to merge. Any future verifiable amendments to accepted claims must be proposed by the same GitHub user, or it will be treated as a contention. +All merge requests that fail will be provided a reason from above which must be addressed prior to merge. Any future verifiable amendments to accepted claims must be proposed by the same submitter, or it will be treated as a contention. -#### Set Withdrawal Address Broadcast +#### `BLSToExecutionChange` Broadcast Anyone in the community will be able to independently verify the files from the claims provided using the Capella spec and command line clients such as "ethdo" which support the specification. -A claim will be considered contested if a claim arrives where the verifiable consensus layer signatures differ between two or more GitHub submissions, where neither party has proven ownership of the execution layer deposit address. If a contested but verified "Set Withdrawal Address Broadcast" request arrives to the GitHub community, all parties will be notified via GitHub, and may try to convince the wider community by providing any publicly verifiable on chain evidence or off chain evidence supporting their claim to then include their claim in nodes. Node operators may decide which verifiable claims they wish to include based on social consensus. +A claim will be considered contested if a claim arrives where the verifiable consensus layer signatures differ between two or more submissions, where neither party has proven ownership of the execution layer deposit address. If a contested but verified "`BLSToExecutionChange` Broadcast" request arrives to a repository, all parties can be notified, and may try to convince the wider community by providing any publicly verifiable on chain evidence or off chain evidence supporting their claim to then include their claim in nodes. Node operators may decide which verifiable claims they wish to include based on social consensus. ## Security Considerations @@ -122,7 +99,7 @@ A claim will be considered contested if a claim arrives where the verifiable con * User A: Controls the CL keys and the EL key used for the deposit * User B: Controls the CL keys, but does not control the EL key for the deposit -User A signs and submits a claim to the CLWP repository, clients load User A message into the "Set Withdrawal Address Broadcast" file. At the time of the first epoch support Set Withdrawal Address, many (not all) nodes begin to broadcast the message. User B also tries to submit a different but valid Set Withdrawal Address to an address that does not match the signature in the claim. This message is successfully received via REST API, but some (not all) nodes begin to silently drop this message as the signature does not match the signature in the "Set Withdrawal Address Broadcast" file. As such, these nodes do not replicate this message via P2P. The nodes which do not have a Set Withdrawal Address Broadcast file loaded may still impose a "Set Withdrawal Address Rebroadcast Delay" to keep listening (for about 5 epochs) to see if there are any conflicts to this message. This delay may give User A an advantage in beating User B to consensus, but there is no certainty as it will depend on chance which validator and nodes are involved. +User A signs and submits a claim to the CLWP repository, clients load User A message into the "`BLSToExecutionChange` Broadcast" file. At the time of the first epoch support `BLSToExecutionChange`, many (not all) nodes begin to broadcast the message. User B also tries to submit a different but valid `BLSToExecutionChange` to an address that does not match the signature in the claim. This message is successfully received via REST API, but some (not all) nodes begin to silently drop this message as the signature does not match the signature in the "`BLSToExecutionChange` Broadcast" file. As such, these nodes do not replicate this message via P2P. ### 2: Attacker has both EL deposit key and CL keys, uncontested claim @@ -136,7 +113,7 @@ It is possible/likely that User A would notice that all their funds in the EL de * User A: Controls the CL keys/mnemonic and the EL key used for the deposit, and submits a claim to move to a new address * User B: Controls the CL keys/mnemonic and the EL key used for the deposit, and submits a claim to move to a new address -This is a contested claim and as such there is no way to prove who is in control using on chain data. Instead, either user may try to persuade the community they are the rightful owner (identity verification, social media, etc.) in an attempt to get node operators to load their contested claim into their "Set Withdrawal Address Broadcast" file. However, there is no way to fully prove it. +This is a contested claim and as such there is no way to prove who is in control using on chain data. Instead, either user may try to persuade the community they are the rightful owner (identity verification, social media, etc.) in an attempt to get node operators to load their contested claim into their "`BLSToExecutionChange` Broadcast" file. However, there is no way to fully prove it. ### 4: A user has lost either their CL key and/or mnemonic (no withdrawal key) @@ -149,7 +126,7 @@ There is no way to recover this scenario with this proposal as we cannot prove a * User A: Controls EL and CL key/mnemonic, successfully achieves a set address withdrawal * User B: Controls CL key, decides to attack -Upon noticing User A has submitted a successful set address withdrawal, User B may run a validator and attempt to get User A slashed +Upon noticing User A has submitted a successful set address withdrawal, User B may run a validator and attempt to get User A slashed. Users who suspect their validator key or seed phrase is compromised should take action to exit their validator as early as possible. ### 6: Compromised key, but not vulnerable to withdrawal @@ -158,10 +135,10 @@ Upon noticing User A has submitted a successful set address withdrawal, User B m User A may generate the withdrawal key (requires the mnemonic). User B can attack User A by getting them slashed, but will be unable to generate the withdrawal key. -### 7: Attacker loads a malicious Set Withdrawal Address Broadcast file into one or multiple nodes, User A submits claim +### 7: Attacker loads a malicious `BLSToExecutionChange` Broadcast file into one or multiple nodes, User A submits claim * User A: Submits a valid uncontested claim which is broadcast out as soon as possible by many nodes -* User B: Submits no claim, but broadcasts a valid malicious claim out through their Set Withdrawal Address Broadcast list, and blocks User A's claim from their node. +* User B: Submits no claim, but broadcasts a valid malicious claim out through their `BLSToExecutionChange` Broadcast list, and blocks User A's claim from their node. User B's claim will make it into many nodes, but when it hits nodes that have adopted User A's signature they will be dropped and not rebroadcast. Statistically, User B will have a harder time achieving consensus among the entire community, but it will be down to chance. @@ -171,9 +148,9 @@ The attacker will statistically likely win as they will be first to have their m ### Second Order Effects -1. A user who participates in the "Set Withdrawal Address Broadcast" may cause the attacker to give up early and instead start to slash. For some users, the thought of getting slashed is preferable to giving an adversary any funds. As the proposal is voluntary, users may choose not to participate if they fear this scenario. -2. The attacker may set up their own Set Withdrawal Address Broadcast to reject signatures not matching their attack. This is possible with or without this proposal. -3. The attacker may be the one collecting "Set Withdrawal Address Broadcast" claims for this proposal and may purposefully reject legitimate requests. Anyone is free to set up their own community claim collection and gather their own community support using the same mechanisms described in this proposal to form an alternative social consensus. Come at me bro. +1. A user who participates in the "`BLSToExecutionChange` Broadcast" may cause the attacker to give up early and instead start to slash. For some users, the thought of getting slashed is preferable to giving an adversary any funds. As the proposal is voluntary, users may choose not to participate if they fear this scenario. +2. The attacker may set up their own `BLSToExecutionChange` Broadcast to reject signatures not matching their attack. This is possible with or without this proposal. +3. The attacker may be the one collecting "`BLSToExecutionChange` Broadcast" claims for this proposal and may purposefully reject legitimate requests. Anyone is free to set up their own community claim collection and gather their own community support using the same mechanisms described in this proposal to form an alternative social consensus. ## Copyright diff --git a/EIPS/eip-4750.md b/EIPS/eip-4750.md index 0b621a8ec5d882..90f716078d0b08 100644 --- a/EIPS/eip-4750.md +++ b/EIPS/eip-4750.md @@ -33,15 +33,15 @@ The type section of EOF containers must adhere to following requirements: 1. The section is comprised of a list of metadata where the metadata index in the type section corresponds to a code section index. Therefore, the type section size MUST be `n * 4` bytes, where `n` is the number of code sections. 2. Each metadata item has 3 attributes: a uint8 `inputs`, a uint8 `outputs`, and a uint16 `max_stack_height`. *Note:* This implies that there is a limit of 255 stack for the input and in the output. This is further restricted to 127 stack items, because the upper bit of both the input and output bytes are reserved for future use. `max_stack_height` is further defined in [EIP-5450](./eip-5450.md). -3. The first code section MUST have 0 inputs and 0 outputs. +3. The 0th code section MUST have 0 inputs and 0 outputs. Refer to [EIP-3540](./eip-3540.md) to see the full structure of a well-formed EOF bytecode. ### New execution state in EVM -A return stack is introduced, separate from the operand stack. It is a stack of items representing execution state to return to after function execution is finished. Each item is comprised of: code section index, offset in the code section (PC value), calling function stack height. +A return stack is introduced, separate from the operand stack. It is a stack of items representing execution state to return to after function execution is finished. Each item is comprised of code section index and offset in the code section (PC value). -Note: Implementations are free to choose particular encoding for a stack item. In the specification below we assume that representation is three unsigned integers: `code_section_index`, `offset`, `stack_height`. +Note: Implementations are free to choose particular encoding for a stack item. In the specification below we assume that representation is two unsigned integers: `code_section_index`, `offset`. The return stack is limited to a maximum 1024 items. @@ -51,24 +51,24 @@ Additionally, EVM keeps track of the index of currently executing section - `cur We introduce two new instructions: -1. `CALLF` (`0xb0`) - call a function -2. `RETF` (`0xb1`) - return from a function +1. `CALLF` (`0xe3`) - call a function +2. `RETF` (`0xe4`) - return from a function If the code is legacy bytecode, any of these instructions results in an *exceptional halt*. (*Note: This means no change to behaviour.*) First we define several helper values: -- `caller_stack_height = return_stack.top().stack_height` - stack height value saved in the top item of return stack -- `type[i].inputs = type_section_contents[i * 4]` - number of inputs of ith section -- `type[i].outputs = type_section_contents[i * 4 + 1]` - number of outputs of ith section +- `type[i].inputs = type_section_contents[i * 4]` - number of inputs of ith code section +- `type[i].outputs = type_section_contents[i * 4 + 1]` - number of outputs of ith code section +- `type[i].max_stack_height = type_section_contents[i * 4 + 2:i * 4 + 4]` - maximum operand stack height of ith code section If the code is valid EOF1, the following execution rules apply: #### `CALLF` -1. Has one immediate argument,`code_section_index`, encoded as a 16-bit unsigned big-endian value. -2. If operand stack has less than `caller_stack_height + type[code_section_index].inputs` items, execution results in exceptional halt. -3. If operand stack size exceeds `1024 - type[code_section_index].max_stack_height` (i.e. if the called function may exceed the global stack height limit), execution results in exceptional halt. This also guarantees that the stack height after the call is within the limits. +1. Has one immediate argument,`target_section_index`, encoded as a 16-bit unsigned big-endian value. +2. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that operand stack has enough items to use as callee's inputs. +3. If operand stack size exceeds `1024 - type[target_section_index].max_stack_height + type[target_section_index].inputs` (i.e. if the called function may exceed the global stack height limit), execution results in exceptional halt. This also guarantees that the stack height after the call is within the limits. 4. If return stack already has `1024` items, execution results in exceptional halt. 5. Charges 5 gas. 6. Pops nothing and pushes nothing to operand stack. @@ -76,23 +76,23 @@ If the code is valid EOF1, the following execution rules apply: ``` (code_section_index = current_section_index, - offset = PC_post_instruction, - stack_height = data_stack.height - types[code_section_index].inputs) + offset = PC_post_instruction) ``` - Under `PC_post_instruction` we mean the PC position after the entire immediate argument of `CALLF`. Operand stack height is saved as it was before function inputs were pushed. + Under `PC_post_instruction` we mean the PC position after the entire immediate argument of `CALLF`. - *Note:* Code validation rules of [EIP-5450](./eip-5450.md) guarantee there is always an instruction following `CALLF` (since terminating instruction or unconditional jump is required to be final one in the section), therefore `PC_post_instruction` always points to an instruction inside section bounds. -8. Sets `current_section_index` to `code_section_index` and `PC` to `0`, and execution continues in the called section. + *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees there is always an instruction following `CALLF` (since terminating instruction or unconditional jump is required to be final one in the section), therefore `PC_post_instruction` always points to an instruction inside section bounds. +8. Sets `current_section_index` to `target_section_index` and `PC` to `0`, and execution continues in the called section. #### `RETF` 1. Does not have immediate arguments. -2. If operand stack does not equal `caller_stack_height + type[current_section_index].outputs` items, execution results in exceptional halt. +2. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that operand stack has exact number of items to use as outputs. 3. Charges 3 gas. 4. Pops nothing and pushes nothing to operand stack. 5. Pops an item from return stack and sets `current_section_index` and `PC` to values from this item. - 1. If return stack is empty after this, execution halts with success. + +*Note:* EOF validation requirement for 0th code section to be non-returning (non-returning sections introduced in a separate EIP) guarantees that return stack cannot be empty before `RETF`. ### Code Validation @@ -103,6 +103,7 @@ In addition to container format validation rules above, we extend code section v 3. `RJUMP`, `RJUMPI` and `RJUMPV` immediate argument value (jump destination relative offset) validation: 1. Code section is invalid in case offset points to a position outside of section bounds. 2. Code section is invalid in case offset points to one of two bytes directly following `CALLF` instruction. +5. No unreachable code sections are allowed, i.e. every code section can be reached from the 0th code section with a series of `CALLF` / `JUMPF` (`JUMPF` introduced in a separate EIP) instructions (0th code section is always reachable). ### Disallowed instructions @@ -116,18 +117,21 @@ Dynamic jump instructions `JUMP` (`0x56`) and `JUMPI` (`0x57`) are invalid and t ### Execution -1. Execution starts at the first byte of the first code section, and PC is set to 0. -2. Return stack is initialized to contain one item: `(code_section_index = 0, offset = 0, stack_height = 0)` -3. If any instruction access the operand stack item below `caller_stack_height`, execution results in exceptional halt. This rule replaces the old stack underflow check. -4. No change in stack overflow check: if any instruction causes the operand stack height to exceed `1024`, execution results in exceptional halt. +1. Execution starts at the first byte of the 0th code section, and PC is set to 0. +2. Return stack is initialized empty. +3. Stack underflow check is not performed anymore. *Note:* EOF validation [EIP-5450](./eip-5450.md) guarantees that it cannot happen at run-time. +3. Stack overflow check is not performed anymore, except during `CALLF` as specified above. ## Rationale -### `RETF` in the top frame ends execution vs exceptionally halts +### `RETF` in the top frame ends execution vs exceptionally halts vs is not allowed during validation + +Alternative logic for `RETF` in the top frame could be to allow it during code validation and make it either: -Alternative logic for executing `RETF` in the top frame could be to exceptionally halt execution, because there is arguably no caller for the starting function. This would mean that return stack is initialized as empty, and `RETF` exceptionally aborts when return stack is empty. +- end execution if the return stack is emptied by the `RETF` or +- exceptionally halt if the return stack is empty before the `RETF`. -We have decided in favor of always having at least one item in the return stack, because it allows to avoid having a special case for empty stack in the interpreter loop stack underflow check. We keep the stack underflow rule general by having `caller_stack_height = 0` in the top frame. +This has been superseded with the validation rule of top frame (0th code section) being non-returning (non-returning sections introduced in a separate EIP), because validating non-returning status of functions is valuable by itself for other reasons. Therefore all considerations of runtime behavior of `RETF` in the top frame were obsoleted. ### Code section limit and instruction size diff --git a/EIPS/eip-4758.md b/EIPS/eip-4758.md index e5d569214cb57f..df7433a9a0f56d 100644 --- a/EIPS/eip-4758.md +++ b/EIPS/eip-4758.md @@ -4,7 +4,7 @@ title: Deactivate SELFDESTRUCT description: Deactivate SELFDESTRUCT by changing it to SENDALL, which does recover all funds to the caller but does not delete any code or storage. author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad) discussions-to: https://ethereum-magicians.org/t/eip-4758-deactivate-selfdestruct/8710 -status: Review +status: Stagnant type: Standards Track category: Core created: 2022-02-03 diff --git a/EIPS/eip-4762.md b/EIPS/eip-4762.md index 03bcdc5c4f2633..6ebc7c5f7b0bcd 100644 --- a/EIPS/eip-4762.md +++ b/EIPS/eip-4762.md @@ -4,7 +4,7 @@ title: Statelessness gas cost changes description: Changes the gas schedule to reflect the costs of creating a witness by requiring clients update their database layout to match. author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad) discussions-to: https://ethereum-magicians.org/t/eip-4762-statelessness-gas-cost-changes/8714 -status: Stagnant +status: Draft type: Standards Track category: Core created: 2022-02-03 @@ -19,6 +19,20 @@ The introduction of Verkle trees into Ethereum requires fundamental changes and ## Specification +### Helper functions + +```python +def get_storage_slot_tree_keys(storage_key: int) -> [int, int]: + if storage_key < (CODE_OFFSET - HEADER_STORAGE_OFFSET): + pos = HEADER_STORAGE_OFFSET + storage_key + else: + pos = MAIN_STORAGE_OFFSET + storage_key + return ( + pos // 256, + pos % 256 + ) +``` + ### Access events We define access events as follows. When an access event takes place, the accessed data is saved to the Verkle tree (even if it was not modified). An access event is of the form`(address, sub_key, leaf_key)`, determining what data is being accessed. @@ -76,19 +90,7 @@ If the `EXTCODEHASH` opcode is called targeting some address, process an access (address, tree_key, sub_key) ``` -Where tree_key and sub_key are computed as follows: - -```python -def get_storage_slot_tree_keys(storage_key: int) -> [int, int]: - if storage_key < (CODE_OFFSET - HEADER_STORAGE_OFFSET): - pos = HEADER_STORAGE_OFFSET + storage_key - else: - pos = MAIN_STORAGE_OFFSET + storage_key - return ( - pos // 256, - pos % 256 - ) -``` +Where `tree_key` and `sub_key` are computed as `tree_key, sub_key = get_storage_slot_tree_keys(address, key)` #### Access events for code @@ -98,17 +100,17 @@ In the conditions below, “chunk chunk_id is accessed” is understood to mean (address, (chunk_id + 128) // 256, (chunk_id + 128) % 256) ``` - * At each step of EVM execution, if and only if PC < len(code), chunk PC // CHUNK_SIZE (where PC is the current program counter) of the callee is accessed. In particular, note the following corner cases: - * The destination of a `JUMP` (or positively evaluated JUMPI) is considered to be accessed, even if the destination is not a jumpdest or is inside pushdata - * The destination of a `JUMPI` is not considered to be accessed if the jump conditional is false. + * At each step of EVM execution, if and only if `PC < len(code)`, chunk `PC // CHUNK_SIZE` (where `PC` is the current program counter) of the callee is accessed. In particular, note the following corner cases: + * The destination of a `JUMP` (or positively evaluated `JUMPI`) is considered to be accessed, even if the destination is not a jumpdest or is inside pushdata + * The destination of a `JUMPI` is not considered to be accessed if the jump conditional is `false`. * The destination of a jump is not considered to be accessed if the execution gets to the jump opcode but does not have enough gas to pay for the gas cost of executing the `JUMP` opcode (including chunk access cost if the `JUMP` is the first opcode in a not-yet-accessed chunk) - * The destination of a jump is not considered to be accessed if it is beyond the code (`destination >= len(code)`) + * The destination of a jump is not considered to be accessed if it is beyond the code (`destination >= len(code)`) * If code stops execution by walking past the end of the code, `PC = len(code)` is not considered to be accessed - * If the current step of EVM execution is a `PUSH{n}`, all chunks `(PC // CHUNK_SIZE) <= chunk_index <= ((PC + n) // CHUNK_SIZE)`` of the callee are accessed. - * If a nonzero-read-size `CODECOPY` or `EXTCODECOPY` read bytes `x...y` inclusive, all chunks ``(x // CHUNK_SIZE) <= chunk_index <= (min(y, code_size - 1) // CHUNK_SIZE)`` of the accessed contract are accessed. - * Example 1: for a `CODECOPY` with start position 100, read size 50, `code_size = 200`, `x = 100` and `y = 149` - * Example 2: for a `CODECOPY` with start position 600, read size 0, no chunks are accessed - * Example 3: for a `CODECOPY` with start position 1500, read size 2000, `code_size = 3100`, `x = 1500` and `y = 3099` + * If the current step of EVM execution is a `PUSH{n}`, all chunks `(PC // CHUNK_SIZE) <= chunk_index <= ((PC + n) // CHUNK_SIZE)` of the callee are accessed. + * If a nonzero-read-size `CODECOPY` or `EXTCODECOPY` read bytes `x...y` inclusive, all chunks `(x // CHUNK_SIZE) <= chunk_index <= (min(y, code_size - 1) // CHUNK_SIZE)` of the accessed contract are accessed. + * Example 1: for a `CODECOPY` with start position 100, read size 50, `code_size = 200`, `x = 100` and `y = 149` + * Example 2: for a `CODECOPY` with start position 600, read size 0, no chunks are accessed + * Example 3: for a `CODECOPY` with start position 1500, read size 2000, `code_size = 3100`, `x = 1500` and `y = 3099` * `CODESIZE`, `EXTCODESIZE` and `EXTCODEHASH` do NOT access any chunks. When a contract is created, access chunks `0 ... (len(code)+30)//31` @@ -118,7 +120,7 @@ We define **write events** as follows. Note that when a write takes place, an ac #### Write events for account headers -When a nonzero-balance-sending CALL or SELFDESTRUCT with a given sender and recipient takes place, process these write events: +When a nonzero-balance-sending `CALL` or `SELFDESTRUCT` with a given sender and recipient takes place, process these write events: ``` (sender, 0, BALANCE_LEAF_KEY) @@ -150,29 +152,17 @@ When a contract is created, process these write events: #### Write events for storage -SSTORE opcodes with a given `address` and `key` process a write event of the form +`SSTORE` opcodes with a given `address` and `key` process a write event of the form ``` (address, tree_key, sub_key) ``` -Where `tree_key` and `sub_key` are computed as follows: - -```python -def get_storage_slot_tree_keys(storage_key: int) -> [int, int]: - if storage_key < (CODE_OFFSET - HEADER_STORAGE_OFFSET): - pos = HEADER_STORAGE_OFFSET + storage_key - else: - pos = MAIN_STORAGE_OFFSET + storage_key - return ( - pos // 256, - pos % 256 - ) -``` +Where `tree_key` and `sub_key` are computed as `tree_key, sub_key = get_storage_slot_tree_keys(address, key)` #### Write events for code -When a contract is created, make write events: +When a contract is created, process the write events: ```python ( @@ -187,6 +177,7 @@ For `i` in `0 ... (len(code)+30)//31`. ### Transactions #### Access events + For a transaction, make these access events: ``` @@ -220,7 +211,7 @@ if `value` is non-zero: Remove the following gas costs: * Increased gas cost of `CALL` if it is nonzero-value-sending - * EIP-2200 `SSTORE` gas costs except for the `SLOAD_GAS` + * [EIP-2200](./eip-2200.md) `SSTORE` gas costs except for the `SLOAD_GAS` * 200 per byte contract code cost Reduce gas cost: @@ -229,36 +220,40 @@ Reduce gas cost: |Constant |Value| |-|-| -|WITNESS_BRANCH_COST |1900| -|WITNESS_CHUNK_COST |200| -|SUBTREE_EDIT_COST |3000| -|CHUNK_EDIT_COST |500| -|CHUNK_FILL_COST |6200| +|`WITNESS_BRANCH_COST` |1900| +|`WITNESS_CHUNK_COST` |200| +|`SUBTREE_EDIT_COST` |3000| +|`CHUNK_EDIT_COST` |500| +|`CHUNK_FILL_COST` |6200| When executing a transaction, maintain four sets: * `accessed_subtrees: Set[Tuple[address, int]]` * `accessed_leaves: Set[Tuple[address, int, int]]` - * `edited_subtrees`: `Set[Tuple[address, int]]` - * `edited_leaves`: `Set[Tuple[address, int, int]]` + * `edited_subtrees: Set[Tuple[address, int]]` + * `edited_leaves: Set[Tuple[address, int, int]]` When an **access** event of `(address, sub_key, leaf_key)` occurs, perform the following checks: - * If ``(address, sub_key)`` is not in accessed_subtrees, charge WITNESS_BRANCH_COST gas and add that tuple to accessed_subtrees. - * If `leaf_key` is not `None` and ``(address, sub_key, leaf_key)`` is not in `accessed_leaves`, charge `WITNESS_CHUNK_COST` gas and add it to `accessed_leaves` + * Perform the following steps unless `address` is either: + * the transaction's originator; + * the transactions's target; + * If `(address, sub_key)` is not in `accessed_subtrees`, charge `WITNESS_BRANCH_COST` gas and add that tuple to `accessed_subtrees`. + * If `leaf_key` is not `None` and `(address, sub_key, leaf_key)` is not in `accessed_leaves`, charge `WITNESS_CHUNK_COST` gas and add it to `accessed_leaves` When a **write** event of `(address, sub_key, leaf_key)` occurs, perform the following checks: - * If (address, sub_key) is not in edited_subtrees, charge `SUBTREE_EDIT_COST` gas and add that tuple to edited_subtrees. - * If leaf_key is not None and `(address, sub_key, leaf_key)` is not in `edited_leaves`, charge `CHUNK_EDIT_COST` gas and add it to `edited_leaves` - * Additionally, if there was no value stored at `(address, sub_key, leaf_key)` (ie. the state held None at that position), charge `CHUNK_FILL_COST` + * If `address` is either the transaction's originator or target, skip the following steps. + * If `(address, sub_key)` is not in `edited_subtrees`, charge `SUBTREE_EDIT_COST` gas and add that tuple to `edited_subtrees`. + * If `leaf_key` is not `None` and `(address, sub_key, leaf_key)` is not in `edited_leaves`, charge `CHUNK_EDIT_COST` gas and add it to `edited_leaves` + * Additionally, if there was no value stored at `(address, sub_key, leaf_key)` (ie. the state held `None` at that position), charge `CHUNK_FILL_COST` -Note that tree keys can no longer be emptied: only the values `0...2**256-1` can be written to a tree key, and 0 is distinct from None. Once a tree key is changed from `None` to not-`None`, it can never go back to `None`. +Note that tree keys can no longer be emptied: only the values `0...2**256-1` can be written to a tree key, and 0 is distinct from `None`. Once a tree key is changed from `None` to not-`None`, it can never go back to `None`. ### Replacement for access lists -We replace EIP 2930 access lists with an SSZ structure of the form: +We replace [EIP-2930](./eip-2930.md) access lists with an SSZ structure of the form: ```python class AccessList(Container): @@ -289,7 +284,7 @@ Gains from the latter two properties have not yet been analyzed, but are likely The precise specification of when access events take place, which makes up most of the complexity of the gas repricing, is necessary to clearly specify when data needs to be saved to the period 1 tree. -## Backward Compatibility +## Backwards Compatibility This EIP requires a hard fork, since it modifies consensus rules. @@ -299,7 +294,8 @@ The main backwards-compatibility-breaking changes is the gas costs for code chun This EIP will mean that certain operations, mostly reading and writing several elements in the same suffix tree, become cheaper. If clients retain the same database structure as they have now, this would result in a DOS vector. -So some adaptation of the database is required in order to make this work. +So some adaptation of the database is required in order to make this work: + * In all possible futures, it is important to logically separate the commitment scheme from data storage. In particular, no traversal of the commitment scheme tree should be necessary to find any given state element * In order to make accesses to the same stem cheap as required for this EIP, the best way is probably to store each stem in the same location in the database. Basically the 256 leaves of 32 bytes each would be stored in an 8kB BLOB. The overhead of reading/writing this BLOB is small because most of the cost of disk access is seeking and not the amount transferred. diff --git a/EIPS/eip-4788.md b/EIPS/eip-4788.md index 24f65168b0a181..aa39884b5ba038 100644 --- a/EIPS/eip-4788.md +++ b/EIPS/eip-4788.md @@ -1,140 +1,283 @@ --- eip: 4788 -title: Beacon state root in the EVM -description: Expose beacon chain state roots in the EVM -author: Alex Stokes (@ralexstokes), Danny Ryan (@djrtwo) -discussions-to: https://ethereum-magicians.org/t/eip-4788-beacon-state-root-in-evm/8281 -status: Stagnant +title: Beacon block root in the EVM +description: Expose beacon chain roots in the EVM +author: Alex Stokes (@ralexstokes), Ansgar Dietrichs (@adietrichs), Danny Ryan (@djrtwo), Martin Holst Swende (@holiman), lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-4788-beacon-root-in-evm/8281 +status: Final type: Standards Track category: Core created: 2022-02-10 +requires: 1559 --- ## Abstract -Commit to the state root of the beacon chain in the `ommers` field in the post-merge execution block. Reflect the changes in the `ommersHash` field of the execution block header. +Commit to the hash tree root of each beacon chain block in the corresponding execution payload header. -Store each beacon chain state root into a contract and add a new opcode that reads this contract. +Store each of these roots in a smart contract. ## Motivation -Exposing the beacon chain state root allows for proofs about the beacon state to be verified inside the EVM. This functionality supports a wide variety of use cases in smart contracts involving validator status and finality produced by the consensus layer. - -In particular, this functionality is required for beacon chain validator withdrawals to the EVM. +Roots of the beacon chain blocks are cryptographic accumulators that allow proofs of arbitrary consensus state. +Exposing these roots inside the EVM allows for trust-minimized access to the consensus layer. +This functionality supports a wide variety of use cases that improve trust assumptions of staking pools, +restaking constructions, smart contract bridges, MEV mitigations and more. ## Specification -| constants | value | units -|--- |--- |--- -| `FORK_TIMESTAMP` | TBD | -| `FORK_EPOCH` | TBD | -| `HISTORY_STORAGE_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffd` | -| `OPCODE_VALUE` | `0x48` | -| `G_beacon_state_root` | 20 | gas +| constants | value | +|--- |--- | +| `FORK_TIMESTAMP` | TBD | +| `HISTORY_BUFFER_LENGTH` | `8191` | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | +| `BEACON_ROOTS_ADDRESS` | `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02` | ### Background -The method of injecting the beacon state root in this EIP follows the general strategy of [EIP-4399](./eip-4399.md) to make a post-merge change to the EVM integrating information from the beacon chain. This EIP along with [EIP-3675](./eip-3675.md) should be taken as relevant background to understand the particular approach of this EIP. +The high-level idea is that each execution block contains the parent beacon block's root. Even in the event of missed slots since the previous block root does not change, +we only need a constant amount of space to represent this "oracle" in each execution block. To improve the usability of this oracle, a small history of block roots +are stored in the contract. -The method for exposing the state root data via opcode is inspired by [EIP-2935](./eip-2935.md). +To bound the amount of storage this construction consumes, a ring buffer is used that mirrors a block root accumulator on the consensus layer. ### Block structure and validity -Beginning at the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST**: - -1. set the value of the `ommers` field in the block to an RLP list with one element: the 32 byte [hash tree root](https://github.com/ethereum/consensus-specs/blob/dev/ssz/simple-serialize.md#merkleization) of the [beacon state](https://github.com/ethereum/consensus-specs/blob/dev/specs/bellatrix/beacon-chain.md#beaconstate) from the previous slot to this block. +Beginning at the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST** extend the header schema with an additional field: the `parent_beacon_block_root`. +This root consumes 32 bytes and is exactly the [hash tree root](https://github.com/ethereum/consensus-specs/blob/fa09d896484bbe240334fa21ffaa454bafe5842e/ssz/simple-serialize.md#merkleization) of the parent beacon block for the given execution block. -2. set the value of the `ommersHash` field in the block header to the Keccak256 hash of the `ommers` field. +The resulting RLP encoding of the header is therefore: ```python -beaconStateRoot = <32 byte value> # provided by consensus client -ommers = RLP([beaconStateRoot]) # in the block body -ommersHash = Keccak256(ommers) # in the block header +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, + blob_gas_used, + excess_blob_gas, + parent_beacon_block_root, +]) ``` -3. Add the block validation that the `ommersHash` does indeed match the expected commitment given the `ommers` value. +Validity of the parent beacon block root is guaranteed from the consensus layer, much like how withdrawals are handled. -### EVM changes +When verifying a block, execution clients **MUST** ensure the root value in the block header matches the one provided by the consensus client. -#### Block processing +For a genesis block with no existing parent beacon block root the 32 zero bytes are used as a root placeholder. -At the start of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e. before processing any transactions), write the beacon state root provided in the block into the storage of the smart contract at `HISTORY_STORAGE_ADDRESS`. This data is keyed by the block number. +#### Beacon roots contract -In pseudocode: +The beacon roots contract has two operations: `get` and `set`. The input itself is not used to determine which function to execute, for that the result of `caller` is used. If `caller` is equal to `SYSTEM_ADDRESS` then the operation to perform is `set`. Otherwise, `get`. -```python -beacon_state_root = block.ommers[0] -sstore(HISTORY_STORAGE_ADDRESS, block.number, beacon_state_root) -``` +##### `get` + +* Callers provide the `timestamp` they are querying encoded as 32 bytes in big-endian format. +* If the input is not exactly 32 bytes, the contract must revert. +* If the input is equal to 0, the contract must revert. +* Given `timestamp`, the contract computes the storage index in which the timestamp is stored by computing the modulo `timestamp % HISTORY_BUFFER_LENGTH` and reads the value. +* If the `timestamp` does not match, the contract must revert. +* Finally, the beacon root associated with the timestamp is returned to the user. It is stored at `timestamp % HISTORY_BUFFER_LENGTH + HISTORY_BUFFER_LENGTH`. -#### New opcode +##### `set` -Beginning at the execution timestamp `FORK_TIMESTAMP`, introduce a new opcode `BEACON_STATE_ROOT` at `OPCODE_VALUE`. This opcode consumes one word from the stack encoding the block number for the root. The opcode has a gas cost of `G_beacon_state_root`. +* Caller provides the parent beacon block root as calldata to the contract. +* Set the storage value at `header.timestamp % HISTORY_BUFFER_LENGTH` to be `header.timestamp` +* Set the storage value at `header.timestamp % HISTORY_BUFFER_LENGTH + HISTORY_BUFFER_LENGTH` to be `calldata[0:32]` -The result of executing this opcode leaves one word on the stack corresponding to a read of the history contract's storage; in pseudocode: +##### Pseudocode ```python -block_number = evm.stack.pop() -sload(HISTORY_STORAGE_ADDRESS, block_number) -``` +if evm.caller == SYSTEM_ADDRESS: + set() +else: + get() -If there is no root stored at the requested block number, the opcode follows the existing EVM semantics of `sload` returning `0`. +def get(): + if len(evm.calldata) != 32: + evm.revert() -## Rationale + if to_uint256_be(evm.calldata) == 0: + evm.revert() -### General strategy + timestamp_idx = to_uint256_be(evm.calldata) % HISTORY_BUFFER_LENGTH + timestamp = storage.get(timestamp_idx) -See the rationale for EIP-4399 for discussion about this general strategy of reusing execution block elements for beacon chain data. + if timestamp != evm.calldata: + evm.revert() -### Fork mechanics + root_idx = timestamp_idx + HISTORY_BUFFER_LENGTH + root = storage.get(root_idx) -This EIP requires the consensus layer and execution layer to execute a network upgrade in lockstep. -To carry out this task, a `FORK_EPOCH` (of the beacon chain) will be chosen and then used to compute a timestamp `FORK_TIMESTAMP`. -This `FORK_TIMESTAMP` can be used in the execution layer to identify when the protocol change should be deployed. + evm.return(root) -This technique works because the timestamps in post-merge execution blocks are aligned to beacon chain slots and thus serve as a proxy for the slot number. +def set(): + timestamp_idx = to_uint256_be(evm.timestamp) % HISTORY_BUFFER_LENGTH + root_idx = timestamp_idx + HISTORY_BUFFER_LENGTH -Another option for the fork definition would be to pick a beacon chain epoch and an execution payload block number. -This design however is not reliable due to the presence of skipped slots on the beacon chain. + storage.set(timestamp_idx, evm.timestamp) + storage.set(root_idx, evm.calldata) +``` -### Execution layer validations +##### Bytecode + +The exact contract bytecode is shared below. + +```asm +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x4d +jumpi + +push1 0x20 +calldatasize +eq +push1 0x24 +jumpi + +push0 +push0 +revert + +jumpdest +push0 +calldataload +dup1 +iszero +push1 0x49 +jumpi + +push3 0x001fff +dup2 +mod +swap1 +dup2 +sload +eq +push1 0x3c +jumpi + +push0 +push0 +revert + +jumpdest +push3 0x001fff +add +sload +push0 +mstore +push1 0x20 +push0 +return + +jumpdest +push0 +push0 +revert + +jumpdest +push3 0x001fff +timestamp +mod +timestamp +dup2 +sstore +push0 +calldataload +swap1 +push3 0x001fff +add +sstore +stop +``` -By including the beacon state root in the execution block in the deprecated `ommers` field, execution clients can still verify the chain in a self-contained way without relying on an available consensus client. -This property is important during syncing (and likely other phases of execution node operation). +#### Deployment + +The beacon roots contract is deployed like any other smart contract. A special synthetic address is generated +by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x60618060095f395ff33373fffffffffffffffffffffffffffffffffffffffe14604d57602036146024575f5ffd5b5f35801560495762001fff810690815414603c575f5ffd5b62001fff01545f5260205ff35b5f5ffd5b62001fff42064281555f359062001fff015500", + "v": "0x1b", + "r": "0x539", + "s": "0x1b9b6eb1f0", + "hash": "0xdf52c2d3bbe38820fff7b5eaab3db1b91f8e1412b56497d88388fb5d4ea1fde0" +} +``` + +Note, the input in the transaction has a simple constructor prefixing the desired runtime code. + +The sender of the transaction can be calculated as `0x0B799C86a49DEeb90402691F1041aa3AF2d3C875`. The address of the first contract deployed from the account is `rlp([sender, 0])` which equals `0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02`. This is how `BEACON_ROOTS_ADDRESS` is determined. Although this style of contract creation is not tied to any specific initcode like create2 is, the synthetic address is cryptographically bound to the input data of the transaction (e.g. the initcode). + +### Block processing -### Minimizing client code change +At the start of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e. before processing any transactions), call `BEACON_ROOTS_ADDRESS` as `SYSTEM_ADDRESS` with the 32-byte input of `header.parent_beacon_block_root`, a gas limit of `30_000_000`, and `0` value. This will trigger the `set()` routine of the beacon roots contract. This is a system operation and therefore: -By including the `ommersHash` validation, clients can use existing code with only minimal changes (supplying the actual state root) during block production and verification. -Having the beacon state root value in the `ommers` field means that it is fairly straightforward to provide the value from the block data to the EVM execution context for client implementations as they stand today. +* the call must execute to completion +* the call does not count against the block's gas limit +* the call does not follow the [EIP-1559](./eip-1559.md) burn semantics - no value should be transferred as part of the call +* if no code exists at `BEACON_ROOTS_ADDRESS`, the call must fail silently -### Gas cost of opcode +Clients may decide to omit an explicit EVM call and directly set the storage values. Note: While this is a valid optimization for Ethereum mainnet, it could be problematic on non-mainnet situations in case a different contract is used. -The suggested gas cost is just using the value for the `BLOCKHASH` opcode as `BEACON_STATE_ROOT` is an analogous operation. +If this EIP is active in a genesis block, the genesis header's `parent_beacon_block_root` must be `0x0` and no system transaction may occur. + +## Rationale ### Why not repurpose `BLOCKHASH`? -The `BLOCKHASH` opcode could be repurposed to provide a beacon state root instead of the current execution block hash. -To minimize code change and simplify deployment to mainnet, this EIP suggests leaving `BLOCKHASH` alone and adding a new opcode with the desired semantics. +The `BLOCKHASH` opcode could be repurposed to provide the beacon root instead of some execution block hash. +To minimize code change, avoid breaking changes to smart contracts, and simplify deployment to mainnet, this EIP suggests leaving `BLOCKHASH` alone and adding new +functionality with the desired semantics. + +### Beacon block root instead of state root + +Block roots are preferred over state roots so there is a constant amount of work to do with each new execution block. Otherwise, skipped slots would require +a linear amount of work with each new payload. While skipped slots are quite rare on mainnet, it is best to not add additional load under what would already +be nonfavorable conditions. -### Why not bound history of state roots? +Use of block root over state root does mean proofs will require a few additional nodes but this cost is negligible (and could be amortized across all consumers, +e.g. with a singleton state root contract that caches the proof per slot). -Marginal state growth; adding every single root results in an additional ~84MB of state growth per year compared to ~30 GB of state overall. +### Why two ring buffers? -TODO: say something about statelessness -TODO: get latest numbers on state size, and compare against predicted growth +The first ring buffer only tracks `HISTORY_BUFFER_LENGTH` worth of roots and so for all possible timestamp values would consume a constant amount of storage. +However, this design opens the contract to an attack where a skipped slot that has the same value modulo the ring buffer length would return an old root value, +rather than the most recent one. -### Beacon state root instead of block root +To nullify this attack while retaining a fixed memory footprint, this EIP keeps track of the pair of data `(parent_beacon_block_root, timestamp)` for each index into the +ring buffer and verifies the timestamp matches the one originally used to write the root data when being read. Given the fixed size of storage slots (only 32 bytes), the requirement +to store a pair of values necessitates two ring buffers, rather than just one. -Each slot on the beacon chain containing a block has both a block root and a state root (reflecting the state after applying said block). -The beacon block includes the state root so a proof about the state could also be authored against a block root at the cost of a few additional hashes. -Given that most use cases want to prove data encapsulated in a given state, rather than a given block, this EIP suggests exposing state roots over block roots. +### Size of ring buffers -### Block number in lieu of slot +The ring buffer data structures are sized to hold 8191 roots from the consensus layer. Using a prime number as the ring buffer size ensures that no value is overwritten until the entire ring buffer has been saturated and thereafter, each value will be updated once per iteration. This also means that even if the slot times were to change, we would continue to use at most 8191 storage slots. -The state roots are keyed by the `number` of the execution block. -Another option is to key roots by the beacon chain slot they belong to. -While at first pass this may seem more direct, the beacon chain can have "skipped" slots where a beacon proposer failed to produce a block that was included at a given slot. -Handling roots of skipped slots would complicate the EVM mechanism so this EIP suggests to use the execution block number where each distinct block number is guaranteed to have a distinct root. +Given the current mainnet values, 8191 roots provides about a day of coverage. This gives users plenty of time to make a transaction with a verification against a specific root and get the transaction included on-chain. ## Backwards Compatibility @@ -142,15 +285,15 @@ No issues. ## Test Cases -TODO +N/A ## Reference Implementation -TODO +N/A ## Security Considerations -TODO +N/A ## Copyright diff --git a/EIPS/eip-4799.md b/EIPS/eip-4799.md index 922d6828122fb0..7de60257d4d049 100644 --- a/EIPS/eip-4799.md +++ b/EIPS/eip-4799.md @@ -1,200 +1,7 @@ --- eip: 4799 -title: Non-Fungible Token Ownership Designation Standard -description: A standardized interface for designating ownership of an NFT -author: David Buckman (@davidbuckman), Isaac Buckman (@isaacbuckman) -discussions-to: https://ethereum-magicians.org/t/erc-4799-non-fungible-token-wrapping-standard/8396 -status: Stagnant -type: Standards Track category: ERC -created: 2022-02-13 -requires: 165 +status: Moved --- -## Abstract - -The following defines a standard interface for designating ownership of an NFT to someone while the NFT is held in escrow by a smart contract. The standard allows for the construction of a directed acyclic graph of NFTs, where the designated owner of every NFT in a given chain is the terminal address of that chain. This enables the introduction of additional functionality to pre-existing NFTs, without having to give up the authenticity of the original. In effect, this means that all NFTs are composable and can be rented, used as collateral, fractionalized, and more. - -## Motivation - -Many NFTs aim to provide their holders with some utility - utility that can come in many forms. This can be the right to inhabit an apartment, access to tickets to an event, an airdrop of tokens, or one of the infinitely many other potential applications. However, in their current form, NFTs are limited by the fact that the only verifiable wallet associated with an NFT is the owner, so clients that want to distribute utility are forced to do so to an NFT's listed owner. This means that any complex ownership agreements must be encoded into the original NFT contract - there is no mechanism by which an owner can link the authenticity of their original NFT to any external contract. - -The goal of this standard is to allow users and developers the ability to define arbitrarily complex ownership agreements on NFTs that have already been minted. This way, new contracts with innovative ownership structures can be deployed, but they can still leverage the authenticity afforded by established NFT contracts - in the past a wrapping contract meant brand new NFTs with no established authenticity. - -Prior to this standard, wrapping an NFT inside another contract was the only way to add functionality after the NFT contract had been deployed, but this meant losing access to the utility of holding the original NFT. Any application querying for the owner of that NFT would determine the wrapping smart contract to be the owner. Using this standard, applications will have a standardized method of interacting with wrapping contracts so that they can continue to direct their utility to users even when the NFT has been wrapped. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; - -interface IERC4799NFT is IERC165 { - /// @dev This emits when ownership of any NFT changes by any mechanism. - /// This event emits when NFTs are created (`from` == 0) and destroyed - /// (`to` == 0). Exception: during contract creation, any number of NFTs - /// may be created and assigned without emitting Transfer. At the time of - /// any transfer, the approved address for that NFT (if any) is reset to none. - event Transfer( - address indexed from, - address indexed to, - uint256 indexed tokenId - ); - - /// @notice Find the owner of an NFT - /// @dev NFTs assigned to zero address are considered invalid, and queries - /// about them throw - /// @param tokenId The identifier for an NFT - /// @return The address of the owner of the NFT - function ownerOf(uint256 tokenId) external view returns (address); -} -``` -```solidity -/// @title ERC-4799 Non-Fungible Token Ownership Designation Standard -/// @dev See https://eips.ethereum.org/EIPS/eip-4799 -/// Note: the ERC-165 identifier for this interface is [TODO]. - -import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; -import "./IERC4799NFT.sol"; - -interface IERC4799 is IERC165 { - /// @dev Emitted when a source token designates its ownership to the owner of the target token - event OwnershipDesignation( - IERC4799NFT indexed sourceContract, - uint256 sourceTokenId, - IERC4799NFT indexed targetContract, - uint256 targetTokenId - ); - - /// @notice Find the designated NFT - /// @param sourceContract The contract address of the source NFT - /// @param sourceTokenId The tokenId of the source NFT - /// @return (targetContract, targetTokenId) contract address and tokenId of the parent NFT - function designatedTokenOf(IERC4799NFT sourceContract, uint256 sourceTokenId) - external - view - returns (IERC4799NFT, uint256); -} -``` - -The authenticity of designated ownership of an NFT is conferred by the designating ERC-4799 contract’s ownership of the original NFT according to the source contract. This MUST be verified by clients by querying the source contract. - -Clients respecting this specification SHALL NOT distribute any utility to the address of the ERC-4799 contract. Instead, they MUST distribute it to the owner of the designated token that the ERC-4799 contract points them to. - -## Rationale - -To maximize the future compatibility of the wrapping contract, we first defined a canonical NFT interface. We created `IERC4799NFT`, an interface implicitly implemented by virtually all popular NFT contracts, including all deployed contracts that are [ERC-721](./eip-721.md) compliant. This interface represents the essence of an NFT: a mapping from a token identifier to the address of a singular owner, represented by the function `ownerOf`. - -The core of our proposal is the `IERC4799` interface, an interface for a standard NFT ownership designation contract (ODC). ERC4799 requires the implementation of a `designatedTokenOf` function, which maps a source NFT to exactly one target NFT. Through this function, the ODC expresses its belief of designated ownership. This designated ownership is only authentic if the ODC is listed as the owner of the original NFT, thus maintaining the invariant that every NFT has exactly one designated owner. - -## Backwards Compatibility - -The `IERC4799NFT` interface is backwards compatible with `IERC721`, as `IERC721` implicitly extends `IERC4799NFT`. This means that the ERC-4799 standard, which wraps NFTs that implement `ERC4799NFT`, is fully backwards compatible with ERC-721. - -## Reference Implementation - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity >=0.8.0 <0.9.0; - -import "./IERC4799.sol"; -import "./IERC4799NFT.sol"; -import "./ERC721.sol"; -import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; - -contract ERC721Composable is IERC4799, IERC721Receiver { - mapping(IERC4799NFT => mapping(uint256 => IERC4799NFT)) private _targetContracts; - mapping(IERC4799NFT => mapping(uint256 => uint256)) private _targetTokenIds; - - function designatedTokenOf(IERC4799NFT sourceContract, uint256 sourceTokenId) - external - view - override - returns (IERC4799NFT, uint256) - { - return ( - IERC4799NFT(_targetContracts[sourceContract][sourceTokenId]), - _targetTokenIds[sourceContract][sourceTokenId] - ); - } - - function designateToken( - IERC4799NFT sourceContract, - uint256 sourceTokenId, - IERC4799NFT targetContract, - uint256 targetTokenId - ) external { - require( - ERC721(address(sourceContract)).ownerOf(sourceTokenId) == msg.sender || - ERC721(address(sourceContract)).getApproved(sourceTokenId) == msg.sender, - "ERC721Composable: Only owner or approved address can set a designate ownership"); - _targetContracts[sourceContract][sourceTokenId] = targetContract; - _targetTokenIds[sourceContract][sourceTokenId] = targetTokenId; - emit OwnershipDesignation( - sourceContract, - sourceTokenId, - targetContract, - targetTokenId - ); - } - - function onERC721Received( - address, - address from, - uint256 sourceTokenId, - bytes calldata - ) external override returns (bytes4) { - ERC721(msg.sender).approve(from, sourceTokenId); - return IERC721Receiver.onERC721Received.selector; - } - - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override - returns (bool) - { - return - (interfaceId == type(IERC4799).interfaceId || - interfaceId == type(IERC721Receiver).interfaceId); - } -} -``` -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity >=0.8.0 <0.9.0; - -import "./IERC4799.sol"; -import "./IERC4799NFT.sol"; -import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; - -contract DesignatedOwner { - function designatedOwnerOf( - IERC4799NFT tokenContract, - uint256 tokenId, - uint256 maxDepth - ) public view returns (address owner) { - owner = tokenContract.ownerOf(tokenId); - if (ERC165Checker.supportsInterface(owner, type(IERC4799).interfaceId)) { - require(maxDepth > 0, "designatedOwnerOf: depth limit exceeded"); - (tokenContract, tokenId) = IERC4799(owner).designatedTokenOf( - tokenContract, - tokenId - ); - return designatedOwnerOf(tokenContract, tokenId, maxDepth - 1); - } - } -} -``` - -## Security Considerations - -### Long/Cyclical Chains of Ownership - -The primary security concern is that of malicious actors creating excessively long or cyclical chains of ownership, leading applications that attempt to query for the designated owner of a given token to run out of gas and be unable to function. To address this, clients are expected to always query considering a `maxDepth` parameter, cutting off computation after a certain number of chain traversals. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4799.md diff --git a/EIPS/eip-4804.md b/EIPS/eip-4804.md index a4bc21d69f3dc0..6617a0fe57da75 100644 --- a/EIPS/eip-4804.md +++ b/EIPS/eip-4804.md @@ -1,145 +1,7 @@ --- eip: 4804 -title: Web3 URL to EVM Call Message Translation -description: A translation of an HTTP-style Web3 URL to an EVM call message -author: Qi Zhou (@qizhou), Chao Pi (@pichaoqkc), Sam Wilson (@SamWilsn) -discussions-to: https://ethereum-magicians.org/t/eip-4804-web3-url-to-evm-call-message-translation/8300 -status: Review -type: Standards Track category: ERC -created: 2022-02-14 -requires: 681 +status: Moved --- -## Abstract - -This standard translates an RFC 2396 URI like `web3://uniswap.eth/` or `ethereum-web3://uniswap.eth/` to an EVM message such as: - -``` -EVMMessage { - To: 0xaabbccddee.... // where uniswap.eth's address registered at ENS - Calldata: 0x - ... -} -``` - -## Motivation - -Currently, reading data from Web3 generally relies on a translation done by a Web2 proxy to Web3 blockchain. The translation is mostly done by the proxies such as dApp websites/node service provider/etherscan, which are out of the control of users. The standard here aims to provide a simple way for Web2 users to directly access the content of Web3, especially on-chain Web contents such as SVG/HTML. Moreover, this standard enables interoperability with other standards already compatible with URIs, like SVG/HTML. - -## Specification - -This specification only defines read-only (i.e. Solidity's `view` functions) semantics. State modifying functions may be defined as a future extension. - -A Web3 URL is in the following form - -``` -web3URL = web3Schema [userinfo "@"] contractName [":" chainid] path ["?" query] -web3Schema = [ "ethereum-web3://" | "eth-web3://" | "web3://" ] -contractName = address | [name "." [ subDomain0 "." ... ]] nsProviderSuffix -path = ["/" method ["/" argument_0 ["/" argument_1 ... ]]] -argument = [type "!"] value -query = "attribute_1=value_1 [ "&" attribute_2=value_2 ... ] -attribute = "returns" | "returnTypes" | other_attribute -``` - -where - -- **web3Schema** indicates the schema of the URL, which is "eth[ereum]://web3-" or "web3://" for short. -- **userinfo** indicates which user is calling the EVM, i.e., "From" field in EVM call message. If not specified, the protocol will use 0x0 as the sender address. -- **contractName** indicates the contract to be called, i.e., "To" field in the EVM call message. If the **contractName** is an **address**, i.e., 0x + 20-byte-data hex, then "To" will be the address. Otherwise, the name is from a name service. In the second case, **nsProviderSuffix** will be the suffix from name service providers such as "eth", etc. The way to translate the name from a name service to an address will be discussed in later EIPs. -- **chainid** indicates which chain to resolve **contractName** and call the message. If not specified, the protocol will use the same chain as the name service provider, e.g., 1 for eth. If no name service provider is available, the default chainid is 1. -- **query** is an optional component containing a sequence of attribute-value pairs separated by "&". - -### Resolve Mode - -Once the "To" address and chainid are determined, the protocol will check the resolver mode of contract by calling "resolveMode" method. The protocol currently supports two resolve modes: - -#### Manual Mode - -The manual mode will not do any interpretation of **path** and **query**, and put **path** [ "?" **query** ] as the calldata of the message directly. - -#### Auto Mode - -The auto mode is the default mode to resolve (also applies when the "resolveMode" method is unavailable in the target contract). In the auto mode, if **path** is empty, then the protocol will call the target contract with empty calldata. Otherwise, the calldata of the EVM message will use standard Solidity contract ABI, where - -- **method** is a string of function method be called -- **argument_i** is the ith argument of the method. If **type** is specified, the value will be translated to the corresponding type. The protocol currently supports the basic types such as uint256, bytes32, address, bytes, and string. If **type** is not specified, then the type will be automatically detected using the following rule in a sequential way: - -1. **type**="uint256", if **value** is numeric; or -2. **type**="bytes32", if **value** is in the form of 0x+32-byte-data hex; or -3. **type**="address", if **value** is in the form of 0x+20-byte-data hex; or -4. **type**="bytes", if **value** is in the form of 0x followed by any number of bytes besides 20 or 32; or -5. else **type**="address" and parse the argument as a domain name in the form of `[name "." [ subDomain0 "." ... ]] nsProviderSuffix`. In this case, the actual value of the argument will be obtained from **nsProviderSuffix**, e.g., eth. If **nsProviderSuffix** is not supported, an unsupported NS provider error will be returned. - -Note that if **method** does not exist, i.e., **path** is empty or "/", then the contract will be called with empty calldata. - -- **returns** attribute in **query** tells the format of the returned data. If not specified, the returned message data will be parsed in "(bytes32)" and MIME will be set based on the suffix of the last argument. If **returns** is "()", the returned data will be parsed in raw bytes in JSON. Otherwise, the returned message will be parsed in the specified **returns** attribute in JSON. If multiple **returns** attributes are present, the value of the last **returns** attribute will be applied. Note that **returnTypes** is the alias of **returns**, but it is not recommended to use and is mainly for backward-compatible purpose. - -### Examples - -#### Example 1 - -``` -web3://enshomepage.eth/ -``` - -The protocol will find the address of **enshomepage.eth** from ENS in chainid 1 (Mainnet), and then the protocol will call the address with "From" = "0x..." and "Calldata" = "0x". - -#### Example 2 - -``` -web3://cyberbrokers-meta.eth/renderBroker/9999 -``` - -The protocol will find the address of **cyberbrokers-meta.eth** from ENS on chainid 1 (Mainnet), and then call the address with "To" = "0x..." and "Calldata" = "0x" + `keccak("view(uint256)")[0:4] + abi.encode(uint256(9999))`. - -#### Example 3 - -``` -web3://ensdomains.eth:4/ -``` - -The protocol will find the address of **ensdomains.eth** from ENS on chainid 4 (Rinkeby), and then call the address with "From" = "0x..." and "Calldata" = "0x" with chainid = 4. - -#### Example 4 - -``` -web3://0x9e081Df45E0D167636DB9C61C7ce719A58d82E3b:4 -``` - -The protocol will call the address with "To" = "0x9e081Df45E0D167636DB9C61C7ce719A58d82E3b" and "Calldata" = "0x" with chainid = 4. - -#### Example 5 - -``` -web3://wusdt.eth:4/balanceOf/charles.eth?returns=(uint256) -``` - -The protocol will find the addresses of **wusdt.eth** and **charles.eth** and then call the method "balanceOf(address)" of the contract with the **charles.eth**'s address. The returned data will be parsed as uint256 like `[ "10000000000000" ]`. - -#### Example 6 -``` -web3://wusdt.eth:4/balanceOf/charles.eth?returns=() -``` - -The protocol will find the address of **wusdt.eth** and then call the method "balanceOf(address)" of the address. The returned data will be parsed as raw bytes like `["0x000000000000000000000000000000000000000000000000000009184e72a000"]`. - -## Rationale - -The purpose of the proposal is to add a decentralized presentation layer for Ethereum. With the layer, we are able to render any web content (including HTML/CSS/JPG/PNG/SVG, etc) on-chain using human-readable URLs, and thus EVM can be served as decentralized Backend. The design of the standard is based on the following principles: - -- **Human-readable**. The Web3 URL should be easily recognized by human similar to Web2 URL (http://). As a result, we support names from name services to replace address for better readability. In addition, instead of using calldata in hex, we use human-readable method + arguments and translate them to calldata for better readability. - -- **Maximum-Compatible with HTTP-URL standard**. The Web3 URL should be compatible with HTTP-URL standard including relative pathing, query, fragment, etc so that the support of existing HTTP-URL (e.g., by browser) can be easily extended to Web3 URL with minimal modification. This also means that existing Web2 users can easily migrate to Web3 with minimal extra knowledge of this standard. - -- **Simple**. Instead of providing explicit types in arguments, we use a "maximum likelihood" principle of auto-detecting the types of the arguments such as address, bytes32, and uint256. This could greatly minimize the length of URL, while avoiding confusion. In addition, explicit types are also supported to clear the confusion if necessary. - -- **Flexible**. The contract is able to override the encoding rule so that the contract has fine-control of understanding the actual Web resources that the users want to locate. - -## Security Considerations - -No security considerations were found. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4804.md diff --git a/EIPS/eip-4824.md b/EIPS/eip-4824.md index ed7404e6f9be1c..8c9fde03f38948 100644 --- a/EIPS/eip-4824.md +++ b/EIPS/eip-4824.md @@ -1,313 +1,7 @@ --- eip: 4824 -title: Common Interfaces for DAOs -description: An API for decentralized autonomous organizations (DAOs). -author: Joshua Tan (@thelastjosh), Isaac Patka (@ipatka), Ido Gershtein , Eyal Eithcowich , Michael Zargham (@mzargham), Sam Furter (@nivida) -discussions-to: https://ethereum-magicians.org/t/eip-4824-decentralized-autonomous-organizations/8362 -status: Draft -type: Standards Track category: ERC -created: 2022-02-17 +status: Moved --- -## Abstract - -An API standard for decentralized autonomous organizations (DAOs), focused on relating on-chain and off-chain representations of membership and proposals. - -## Motivation - -DAOs, since being invoked in the Ethereum whitepaper, have been vaguely defined. This has led to a wide range of patterns but little standardization or interoperability between the frameworks and tools that have emerged. Standardization and interoperability are necessary to support a variety of use-cases. In particular, a standard daoURI, similar to tokenURI in [EIP-721](./eip-721), will enhance DAO discoverability, legibility, proposal simulation, and interoperability between tools. More consistent data across the ecosystem is also a prerequisite for future DAO standards. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Every contract implementing this EIP MUST implement the `EIP4824` interface below: - -```solidity -pragma solidity ^0.8.1; - -/// @title EIP-4824 Common Interfaces for DAOs -/// @dev See https://eips.ethereum.org/EIPS/eip-4824 - -interface EIP4824 { - /// @notice A distinct Uniform Resource Identifier (URI) pointing to a JSON object following the "EIP-4824 DAO JSON-LD Schema". This JSON file splits into four URIs: membersURI, proposalsURI, activityLogURI, and governanceURI. The membersURI should point to a JSON file that conforms to the "EIP-4824 Members JSON-LD Schema". The proposalsURI should point to a JSON file that conforms to the "EIP-4824 Proposals JSON-LD Schema". The activityLogURI should point to a JSON file that conforms to the "EIP-4824 Activity Log JSON-LD Schema". The governanceURI should point to a flatfile, normatively a .md file. Each of the JSON files named above can be statically-hosted or dynamically-generated. - function daoURI() external view returns (string _daoURI); -} -``` - -The DAO JSON-LD Schema mentioned above: - -```json -{ - "@context": "http://www.daostar.org/schemas", - "type": "DAO", - "name": "", - "description": "", - "membersURI": "", - "proposalsURI": "", - "activityLogURI": "", - "governanceURI": "" -} -``` - -A DAO MAY inherit the above interface above or it MAY create an external registration contract that is compliant with this EIP. The external registration contract MUST store the DAO’s primary address. - -```solidity -pragma solidity ^0.8.1; - -/// @title EIP-4824 Common Interfaces for DAOs -/// @dev See - -error NotOwner(); -error NotOffered(); - -contract EIP4824Registration is EIP4824 { - string private _daoURI; - address daoAddress; - - event NewURI(string daoURI); - - constructor() { - daoAddress = address(0xdead); - } - - function initialize(address _daoAddress, string memory daoURI_) external { - if (daoAddress != address(0)) revert AlreadyInitialized(); - daoAddress = _daoAddress; - _daoURI = daoURI_; - } - - function setURI(string memory daoURI_) external { - if (msg.sender != daoAddress) revert NotOwner(); - _daoURI = daoURI_; - emit NewURI(daoURI_); - } - - function daoURI() external view returns (string memory daoURI_) { - return _daoURI; - } -} -``` - -If a DAO uses an external registration contract, the DAO SHOULD use a common registration factory contract to enable efficient network indexing. - -```solidity -pragma solidity ^0.8.1; - -/// @title EIP-4824 Common Interfaces for DAOs -/// @dev See - -contract CloneFactory { - // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 - function createClone(address target) internal returns (address result) { - bytes20 targetBytes = bytes20(target); - assembly { - let clone := mload(0x40) - mstore( - clone, - 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 - ) - mstore(add(clone, 0x14), targetBytes) - mstore( - add(clone, 0x28), - 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 - ) - result := create(0, clone, 0x37) - } - } -} - -contract EIP4824RegistrationFactory is CloneFactory { - event NewRegistration( - address indexed daoAddress, - string daoURI, - address registration - ); - - address public template; /*Template contract to clone*/ - - constructor(address _template) public { - template = _template; - } - - function summonRegistration(string calldata daoURI_) external { - EIP4824Registration reg = EIP4824Registration(createClone(template)); /*Create a new clone of the template*/ - reg.initialize(msg.sender, daoURI_); - emit NewRegistration(msg.sender, daoURI_, address(reg)); - } -} -``` - -### Members - -Members JSON-LD Schema. - -```json -{ - "@context": "", - "type": "DAO", - "name": "", - "members": [ - { - "type": "EthereumAddress", - "id": "
" - }, - { - "type": "EthereumAddress", - "id": "
" - } - ] -} -``` - -### Proposals - -Proposals JSON-LD Schema. Every contract implementing this EIP should implement a proposalsURI pointing to a JSON object satisfying this schema. - -In particular, any on-chain proposal MUST be associated to an id of the form CAIP10_ADDRESS + “?proposalId=” + PROPOSAL_COUNTER, where CAIP10_ADDRESS is an address following the CAIP-10 standard and PROPOSAL_COUNTER is an arbitrary identifier such as a uint256 counter or a hash that is locally unique per CAIP-10 address. Off-chain proposals MAY use a similar id format where CAIP10_ADDRESS is replaced with an appropriate URI or URL. - -```json -{ - "@context": "http://www.daostar.org/schemas", - "type": "DAO", - "name": "", - "proposals": [ - { - "type": "proposal", - "id": "", - "name": "", - "contentURI": "", - "status": "", - "calls": [ - { - "type": "CallDataEVM", - "operation": "", - "from": "", - "to": "", - "value": "", - "data": "" - } - ] - } - ] -} -``` - -### Activity Log - -Activity Log JSON-LD Schema. - -```json -{ - "@context": "", - "type": "DAO", - "name": "", - "activities": [ - { - "id": "", - "type": "activity", - "proposal": { - "id": "", - "type": "proposal" - }, - "member": { - "type": "EthereumAddress", - "id": "
" - } - }, - ], - "activities": [ - { - "id": "", - "type": "activity", - "proposal": { - "id": "", - "type": "proposal" - }, - "member": { - "type": "EthereumAddress", - "id": "
" - } - } - ] -} -``` - -## Rationale - -In this standard, we assume that all DAOs possess at least two primitives: *membership* and *behavior*. *Membership* is defined by a set of addresses. *Behavior* is defined by a set of possible contract actions, including calls to external contracts and calls to internal functions. *Proposals* relate membership and behavior; they are objects that members can interact with and which, if and when executed, become behaviors of the DAO. - -### APIs, URIs, and off-chain data - -DAOs themselves have a number of existing and emerging use-cases. But almost all DAOs need to publish data off-chain for a number of reasons: communicating to and recruiting members, coordinating activities, powering user interfaces and governance applications such as Snapshot or Tally, or enabling search and discovery via platforms like DeepDAO, Messari, and Etherscan. Having a standardized schema for this data organized across multiple URIs, i.e. an API specification, would strengthen existing use-cases for DAOs, help scale tooling and frameworks across the ecosystem, and build support for additional forms of interoperability. - -While we considered standardizing on-chain aspects of DAOs in this standard, particularly on-chain proposal objects and proposal IDs, we felt that this level of standardization was premature given (1) the relative immaturity of use-cases, such as multi-DAO proposals or master-minion contracts, that would benefit from such standardization, (2) the close linkage between proposal systems and governance, which we did not want to standardize (see “governanceURI”, below), and (3) the prevalence of off-chain and L2 voting and proposal systems in DAOs (see “proposalsURI”, below). Further, a standard URI interface is relatively easy to adopt and has been actively demanded by frameworks (see “Community Consensus”, below). - -### membersURI - -Approaches to membership vary widely in DAOs. Some DAOs and DAO frameworks (e.g. Gnosis Safe, Tribute), maintain an explicit, on-chain set of members, sometimes called owners or stewards. But many DAOs are structured so that membership status is based on the ownership of a token or tokens (e.g. Moloch, Compound, DAOstack, 1Hive Gardens). In these DAOs, computing the list of current members typically requires some form of off-chain indexing of events. - -In choosing to ask only for an (off-chain) JSON schema of members, we are trading off some on-chain functionality for more flexibility and efficiency. We expect different DAOs to use membersURI in different ways: to serve a static copy of on-chain membership data, to contextualize the on-chain data (e.g. many Gnosis Safe stewards would not say that they are the only members of the DAO), to serve consistent membership for a DAO composed of multiple contracts, or to point at an external service that computes the list, among many other possibilities. We also expect many DAO frameworks to offer a standard endpoint that computes this JSON file, and we provide a few examples of such endpoints in the implementation section. - -We encourage extensions of the Membership JSON-LD Schema, e.g. for DAOs that wish to create a state variable that captures active/inactive status or different membership levels. - -### proposalsURI - -Proposals have become a standard way for the members of a DAO to trigger on-chain actions, e.g. sending out tokens as part of grant or executing arbitrary code in an external contract. In practice, however, many DAOs are governed by off-chain decision-making systems on platforms such as Discourse, Discord, or Snapshot, where off-chain proposals may function as signaling mechanisms for an administrator or as a prerequisite for a later on-chain vote. (To be clear, on-chain votes may also serve as non-binding signaling mechanisms or as “binding” signals leading to some sort of off-chain execution.) The schema we propose is intended to support both on-chain and off-chain proposals, though DAOs themselves may choose to report only on-chain, only off-chain, or some custom mix of proposal types. - -**Proposal ID**. Every unique on-chain proposal MUST be associated to a proposal ID of the form CAIP10_ADDRESS + “?proposalId=” + PROPOSAL_COUNTER, where PROPOSAL_COUNTER is an arbitrary string which is unique per CAIP10_ADDRESS. Note that PROPOSAL_COUNTER may not be the same as the on-chain representation of the proposal; however, each PROPOSAL_COUNTER should be unique per CAIP10_ADDRESS, such that the proposal ID is a globally unique identifier. We endorse the CAIP-10 standard to support multi-chain / layer 2 proposals and the “?proposalId=” query syntax to suggest off-chain usage. - -**ContentURI**. In many cases, a proposal will have some (off-chain) content such as a forum post or a description on a voting platform which predates or accompanies the actual proposal. - -**Status**. Almost all proposals have a status or state, but the actual status is tied to the governance system, and there is no clear consensus between existing DAOs about what those statuses should be (see table below). Therefore, we have defined a “status” property with a generic, free text description field. - -| Project | Proposal Statuses | -| --- | --- | -| Aragon | Not specified | -| Colony | [‘Null’, ‘Staking’, ‘Submit’, ‘Reveal’, ‘Closed’, ‘Finalizable’, ‘Finalized’, ‘Failed’] | -| Compound | [‘Pending’, ‘Active’, ‘Canceled’, ‘Defeated’, ‘Succeeded’, ‘Queued’, ‘Expired’, ‘Executed’] | -| DAOstack/ Alchemy | [‘None’, ‘ExpiredInQueue’, ‘Executed’, ‘Queued’, ‘PreBoosted’, ‘Boosted’, ‘QuietEndingPeriod’] | -| Moloch v2 | [sponsored, processed, didPass, cancelled, whitelist, guildkick] | -| Tribute | [‘EXISTS’, ‘SPONSORED’, ‘PROCESSED’] | - -**ExecutionData**. For on-chain proposals with non-empty execution, we include an array field to expose the call data. The main use-case for this data is execution simulation of proposals. - -### activityLogURI - -The activity log JSON is intended to capture the interplay between a member of a DAO and a given proposal. Examples of activities include the creation/submission of a proposal, voting on a proposal, disputing a proposal, and so on. - -*Alternatives we considered: history, interactions* - -### governanceURI - -Membership, to be meaningful, usually implies rights and affordances of some sort, e.g. the right to vote on proposals, the right to ragequit, the right to veto proposals, and so on. But many rights and affordances of membership are realized off-chain (e.g. right to vote on a Snapshot, gated access to a Discord). Instead of trying to standardize these wide-ranging practices or forcing DAOs to locate descriptions of those rights on-chain, we believe that a flatfile represents the easiest and most widely-acceptable mechanism for communicating what membership means and how proposals work. These flatfiles can then be consumed by services such as Etherscan, supporting DAO discoverability and legibility. - -We chose the word “governance” as an appropriate word that reflects (1) the widespread use of the word in the DAO ecosystem and (2) the common practice of emitting a governance.md file in open-source software projects. - -*Alternative names considered: description, readme, constitution* - -### Why JSON-LD - -We chose to use JSON-LD rather than the more widespread and simpler JSON standard because (1) we want to support use-cases where a DAO wants to include members using some other form of identification than their Ethereum address and (2) we want this standard to be compatible with future multi-chain standards. Either use-case would require us to implement a context and type for addresses, which is already implemented in JSON-LD. - -Further, given the emergence of patterns such as subDAOs and DAOs of DAOs in large organizations such as Synthetix, as well as L2 and multi-chain use-cases, we expect some organizations will point multiple DAOs to the same URI, which would then serve as a gateway to data from multiple contracts and services. The choice of JSON-LD allows for easier extension and management of that data. - -### **Community Consensus** - -The initial draft standard was developed as part of the DAOstar One roundtable series, which included representatives from all major EVM-based DAO frameworks (Aragon, Compound, DAOstack, Gnosis, Moloch, OpenZeppelin, and Tribute), a wide selection of DAO tooling developers, as well as several major DAOs. Thank you to all the participants of the roundtable. We would especially like to thank Auryn Macmillan, Fabien of Snapshot, Selim Imoberdorf, Lucia Korpas, and Mehdi Salehi for their contributions. - -In-person events will be held at Schelling Point 2022 and at ETHDenver 2022, where we hope to receive more comments from the community. We also plan to schedule a series of community calls through early 2022. - -## Backwards Compatibility -Existing contracts that do not wish to use this specification are unaffected. DAOs that wish to adopt the standard without updating or migrating contracts can do so via an external registration contract. - -## Security Considerations - -This standard defines the interfaces for the DAO URIs but does not specify the rules under which the URIs are set, or how the data is prepared. Developers implementing this standard should consider how to update this data in a way aligned with the DAO’s governance model, and keep the data fresh in a way that minimizes reliance on centralized service providers. - -Indexers that rely on the data returned by the URI should take caution if DAOs return executable code from the URIs. This executable code might be intended to get the freshest information on membership, proposals, and activity log, but it could also be used to run unrelated tasks. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4824.md diff --git a/EIPS/eip-4834.md b/EIPS/eip-4834.md index 8ddcc36d958b7e..c68ab4e15bbdea 100644 --- a/EIPS/eip-4834.md +++ b/EIPS/eip-4834.md @@ -1,229 +1,7 @@ --- eip: 4834 -title: Hierarchical Domains -description: Extremely generic name resolution -author: Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/erc-4834-hierarchical-domains-standard/8388 -status: Final -type: Standards Track category: ERC -created: 2022-02-22 +status: Moved --- -## Abstract - -This is a standard for generic name resolution with arbitrarily complex access control and resolution. It permits a contract that implements this EIP (referred to as a "domain" hereafter) to be addressable with a more human-friendly name, with a similar purpose to [EIP-137](./eip-137.md) (also known as "ENS"). - -## Motivation - -The advantage of this EIP over existing standards is that it provides a minimal interface that supports name resolution, adds standardized access control, and has a simple architecture. ENS, although useful, has a comparatively complex architecture and does not have standard access control. - -In addition, all domains (including subdomains, TLDs, and even the root itself) are actually implemented as domains, meaning that name resolution is a simple iterative algorithm, not unlike DNS itself. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Contract Interface - -```solidity -interface IDomain { - /// @notice Query if a domain has a subdomain with a given name - /// @param name The subdomain to query, in right to left order - /// @return `true` if the domain has a subdomain with the given name, `false` otherwise - function hasDomain(string[] memory name) external view returns (bool); - - /// @notice Fetch the subdomain with a given name - /// @dev This should revert if `hasDomain(name)` is `false` - /// @param name The subdomain to fetch, in right to left order - /// @return The subdomain with the given name - function getDomain(string[] memory name) external view returns (address); -} -``` - -### Name Resolution - -To resolve a name (like `"a.b.c"`), split it by the delimiter (resulting in something like `["a", "b", "c"]`). Set `domain` initially to the root domain, and `path` to be an empty list. - -Pop off the last element of the array (`"c"`) and add it to the path, then call `domain.hasDomain(path)`. If it's `false`, then the domain resolution fails. Otherwise, set the domain to `domain.getDomain(path)`. Repeat until the list of split segments is empty. - -There is no limit to the amount of nesting that is possible. For example, `0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z` would be valid if the root contains `z`, and `z` contains `y`, and so on. - -Here is a solidity function that resolves a name: - -```solidity -function resolve(string[] calldata splitName, IDomain root) public view returns (address) { - IDomain current = root; - string[] memory path = []; - for (uint i = splitName.length - 1; i >= 0; i--) { - // Append to back of list - path.push(splitName[i]); - // Require that the current domain has a domain - require(current.hasDomain(path), "Name resolution failed"); - // Resolve subdomain - current = current.getDomain(path); - } - return current; -} -``` - -### Optional Extension: Registerable - -```solidity -interface IDomainRegisterable is IDomain { - //// Events - - /// @notice Must be emitted when a new subdomain is created (e.g. through `createDomain`) - /// @param sender msg.sender for createDomain - /// @param name name for createDomain - /// @param subdomain subdomain in createDomain - event SubdomainCreate(address indexed sender, string name, address subdomain); - - /// @notice Must be emitted when the resolved address for a domain is changed (e.g. with `setDomain`) - /// @param sender msg.sender for setDomain - /// @param name name for setDomain - /// @param subdomain subdomain in setDomain - /// @param oldSubdomain the old subdomain - event SubdomainUpdate(address indexed sender, string name, address subdomain, address oldSubdomain); - - /// @notice Must be emitted when a domain is unmapped (e.g. with `deleteDomain`) - /// @param sender msg.sender for deleteDomain - /// @param name name for deleteDomain - /// @param subdomain the old subdomain - event SubdomainDelete(address indexed sender, string name, address subdomain); - - //// CRUD - - /// @notice Create a subdomain with a given name - /// @dev This should revert if `canCreateDomain(msg.sender, name, pointer)` is `false` or if the domain exists - /// @param name The subdomain name to be created - /// @param subdomain The subdomain to create - function createDomain(string memory name, address subdomain) external payable; - - /// @notice Update a subdomain with a given name - /// @dev This should revert if `canSetDomain(msg.sender, name, pointer)` is `false` of if the domain doesn't exist - /// @param name The subdomain name to be updated - /// @param subdomain The subdomain to set - function setDomain(string memory name, address subdomain) external; - - /// @notice Delete the subdomain with a given name - /// @dev This should revert if the domain doesn't exist or if `canDeleteDomain(msg.sender, name)` is `false` - /// @param name The subdomain to delete - function deleteDomain(string memory name) external; - - - //// Parent Domain Access Control - - /// @notice Get if an account can create a subdomain with a given name - /// @dev This must return `false` if `hasDomain(name)` is `true`. - /// @param updater The account that may or may not be able to create/update a subdomain - /// @param name The subdomain name that would be created/updated - /// @param subdomain The subdomain that would be set - /// @return Whether an account can update or create the subdomain - function canCreateDomain(address updater, string memory name, address subdomain) external view returns (bool); - - /// @notice Get if an account can update or create a subdomain with a given name - /// @dev This must return `false` if `hasDomain(name)` is `false`. - /// If `getDomain(name)` is also a domain implementing the subdomain access control extension, this should return `false` if `getDomain(name).canMoveSubdomain(msg.sender, this, subdomain)` is `false`. - /// @param updater The account that may or may not be able to create/update a subdomain - /// @param name The subdomain name that would be created/updated - /// @param subdomain The subdomain that would be set - /// @return Whether an account can update or create the subdomain - function canSetDomain(address updater, string memory name, address subdomain) external view returns (bool); - - /// @notice Get if an account can delete the subdomain with a given name - /// @dev This must return `false` if `hasDomain(name)` is `false`. - /// If `getDomain(name)` is a domain implementing the subdomain access control extension, this should return `false` if `getDomain(name).canDeleteSubdomain(msg.sender, this, subdomain)` is `false`. - /// @param updater The account that may or may not be able to delete a subdomain - /// @param name The subdomain to delete - /// @return Whether an account can delete the subdomain - function canDeleteDomain(address updater, string memory name) external view returns (bool); -} -``` - -### Optional Extension: Enumerable - -```solidity -interface IDomainEnumerable is IDomain { - /// @notice Query all subdomains. Must revert if the number of domains is unknown or infinite. - /// @return The subdomain with the given index. - function subdomainByIndex(uint256 index) external view returns (string memory); - - /// @notice Get the total number of subdomains. Must revert if the number of domains is unknown or infinite. - /// @return The total number of subdomains. - function totalSubdomains() external view returns (uint256); -} -``` - -### Optional Extension: Access Control - -```solidity -interface IDomainAccessControl is IDomain { - /// @notice Get if an account can move the subdomain away from the current domain - /// @dev May be called by `canSetDomain` of the parent domain - implement access control here!!! - /// @param updater The account that may be moving the subdomain - /// @param name The subdomain name - /// @param parent The parent domain - /// @param newSubdomain The domain that will be set next - /// @return Whether an account can update the subdomain - function canMoveSubdomain(address updater, string memory name, IDomain parent, address newSubdomain) external view returns (bool); - - /// @notice Get if an account can unset this domain as a subdomain - /// @dev May be called by `canDeleteDomain` of the parent domain - implement access control here!!! - /// @param updater The account that may or may not be able to delete a subdomain - /// @param name The subdomain to delete - /// @param parent The parent domain - /// @return Whether an account can delete the subdomain - function canDeleteSubdomain(address updater, string memory name, IDomain parent) external view returns (bool); -} -``` - -## Rationale - -This EIP's goal, as mentioned in the abstract, is to have a simple interface for resolving names. Here are a few design decisions and why they were made: - -- Name resolution algorithm - - Unlike ENS's resolution algorithm, this EIP's name resolution is fully under the control of the contracts along the resolution path. - - This behavior is more intuitive to users. - - This behavior allows for greater flexibility - e.g. a contract that changes what it resolves to based on the time of day. -- Parent domain access control - - A simple "ownable" interface was not used because this specification was designed to be as generic as possible. If an ownable implementation is desired, it can be implemented. - - This also gives parent domains the ability to call subdomains' access control methods so that subdomains, too, can choose whatever access control mechanism they desire -- Subdomain access control - - These methods are included so that subdomains aren't always limited to their parent domain's access control - - The root domain can be controlled by a DAO with a non-transferable token with equal shares, a TLD can be controlled by a DAO with a token representing stake, a domain of that TLD can be controlled by a single owner, a subdomain of that domain can be controlled by a single owner linked to an NFT, and so on. - - Subdomain access control functions are suggestions: an ownable domain might implement an owner override, so that perhaps subdomains might be recovered if the keys are lost. - -## Backwards Compatibility - -This EIP is general enough to support ENS, but ENS is not general enough to support this EIP. - -## Security Considerations - -### Malicious canMoveSubdomain (Black Hole) - -#### Description: Malicious `canMoveSubdomain` - -Moving a subdomain using `setDomain` is a potentially dangerous operation. - -Depending on the parent domain's implementation, if a malicious new subdomain unexpectedly returns `false` on `canMoveSubdomain`, that subdomain can effectively lock the ownership of the domain. - -Alternatively, it might return `true` when it isn't expected (i.e. a backdoor), allowing the contract owner to take over the domain. - -#### Mitigation: Malicious `canMoveSubdomain` - -Clients should help by warning if `canMoveSubdomain` or `canDeleteSubdomain` for the new subdomain changes to `false`. It is important to note, however, that since these are functions, it is possible for the value to change depending on whether or not it has already been linked. It is also still possible for it to unexpectedly return true. It is therefore recommended to **always** audit the new subdomain's source code before calling `setDomain`. - -### Parent Domain Resolution - -#### Description: Parent Domain Resolution - -Parent domains have full control of name resolution for their subdomains. If a particular domain is linked to `a.b.c`, then `b.c` can, depending on its code, set `a.b.c` to any domain, and `c` can set `b.c` itself to any domain. - -#### Mitigation: Parent Domain Resolution - -Before acquiring a domain that has been pre-linked, it is recommended to always have the contract **and** all the parents up to the root audited. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4834.md diff --git a/EIPS/eip-4844.md b/EIPS/eip-4844.md index 073f340474fb1d..de2e4a46ad93fc 100644 --- a/EIPS/eip-4844.md +++ b/EIPS/eip-4844.md @@ -4,7 +4,7 @@ title: Shard Blob Transactions description: Shard Blob Transactions scale data-availability of Ethereum in a simple, forwards-compatible manner. author: Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad), Diederik Loerakker (@protolambda), George Kadianakis (@asn-d6), Matt Garnett (@lightclient), Mofi Taiwo (@Inphi), Ansgar Dietrichs (@adietrichs) discussions-to: https://ethereum-magicians.org/t/eip-4844-shard-blob-transactions/8430 -status: Review +status: Final type: Standards Track category: Core created: 2022-02-25 @@ -31,7 +31,7 @@ However, data sharding will still take a considerable amount of time to finish i This EIP provides a stop-gap solution until that point by implementing the _transaction format_ that would be used in sharding, but not actually sharding those transactions. Instead, the data from this transaction format is simply part of the beacon chain and is fully downloaded by all consensus nodes (but can be deleted after only a relatively short delay). -Compared to full data sharding, this EIP has a reduced cap on the number of these transactions that can be included, corresponding to a target of ~0.25 MB per block and a limit of ~0.5 MB. +Compared to full data sharding, this EIP has a reduced cap on the number of these transactions that can be included, corresponding to a target of ~0.375 MB per block and a limit of ~0.75 MB. ## Specification @@ -39,50 +39,45 @@ Compared to full data sharding, this EIP has a reduced cap on the number of thes | Constant | Value | | - | - | -| `BLOB_TX_TYPE` | `Bytes1(0x05)` | +| `BLOB_TX_TYPE` | `Bytes1(0x03)` | +| `BYTES_PER_FIELD_ELEMENT` | `32` | | `FIELD_ELEMENTS_PER_BLOB` | `4096` | | `BLS_MODULUS` | `52435875175126190479447740508185965837690552500527637822603658699938581184513` | -| `BLOB_COMMITMENT_VERSION_KZG` | `Bytes1(0x01)` | -| `POINT_EVALUATION_PRECOMPILE_ADDRESS` | `Bytes20(0x14)` | +| `VERSIONED_HASH_VERSION_KZG` | `Bytes1(0x01)` | +| `POINT_EVALUATION_PRECOMPILE_ADDRESS` | `Bytes20(0x0A)` | | `POINT_EVALUATION_PRECOMPILE_GAS` | `50000` | -| `MAX_DATA_GAS_PER_BLOCK` | `2**19` | -| `TARGET_DATA_GAS_PER_BLOCK` | `2**18` | -| `MIN_DATA_GASPRICE` | `1` | -| `DATA_GASPRICE_UPDATE_FRACTION` | `2225652` | -| `MAX_VERSIONED_HASHES_LIST_SIZE` | `2**24` | -| `MAX_CALLDATA_SIZE` | `2**24` | -| `MAX_ACCESS_LIST_SIZE` | `2**24` | -| `MAX_ACCESS_LIST_STORAGE_KEYS` | `2**24` | -| `MAX_TX_WRAP_KZG_COMMITMENTS` | `2**24` | -| `LIMIT_BLOBS_PER_TX` | `2**24` | -| `DATA_GAS_PER_BLOB` | `2**17` | +| `MAX_BLOB_GAS_PER_BLOCK` | `786432` | +| `TARGET_BLOB_GAS_PER_BLOCK` | `393216` | +| `MIN_BASE_FEE_PER_BLOB_GAS` | `1` | +| `BLOB_BASE_FEE_UPDATE_FRACTION` | `3338477` | +| `GAS_PER_BLOB` | `2**17` | | `HASH_OPCODE_BYTE` | `Bytes1(0x49)` | | `HASH_OPCODE_GAS` | `3` | +| [`MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS`](https://github.com/ethereum/consensus-specs/blob/4de1d156c78b555421b72d6067c73b614ab55584/configs/mainnet.yaml#L148) | `4096` | ### Type aliases | Type | Base type | Additional checks | | - | - | - | -| `BLSFieldElement` | `uint256` | `x < BLS_MODULUS` | -| `Blob` | `Vector[BLSFieldElement, FIELD_ELEMENTS_PER_BLOB]` | | +| `Blob` | `ByteVector[BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB]` | | | `VersionedHash` | `Bytes32` | | -| `KZGCommitment` | `Bytes48` | Same as BLS standard "is valid pubkey" check but also allows `0x00..00` for point-at-infinity | +| `KZGCommitment` | `Bytes48` | Perform IETF BLS signature "KeyValidate" check but do allow the identity point | | `KZGProof` | `Bytes48` | Same as for `KZGCommitment` | ### Cryptographic Helpers -Throughout this proposal we use cryptographic methods and classes defined in the corresponding [consensus 4844 specs](https://github.com/ethereum/consensus-specs/blob/23d3aeebba3b5da0df4bd25108461b442199f406/specs/eip4844). +Throughout this proposal we use cryptographic methods and classes defined in the corresponding [consensus 4844 specs](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb). -Specifically, we use the following methods from [`polynomial-commitments.md`](https://github.com/ethereum/consensus-specs/blob/23d3aeebba3b5da0df4bd25108461b442199f406/specs/eip4844/polynomial-commitments.md): +Specifically, we use the following methods from [`polynomial-commitments.md`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md): -- [`verify_kzg_proof()`](https://github.com/ethereum/consensus-specs/blob/23d3aeebba3b5da0df4bd25108461b442199f406/specs/eip4844/polynomial-commitments.md#verify_kzg_proof) -- [`verify_aggregate_kzg_proof()`](https://github.com/ethereum/consensus-specs/blob/23d3aeebba3b5da0df4bd25108461b442199f406/specs/eip4844/polynomial-commitments.md#verify_aggregate_kzg_proof) +- [`verify_kzg_proof()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_kzg_proof) +- [`verify_blob_kzg_proof_batch()`](https://github.com/ethereum/consensus-specs/blob/86fb82b221474cc89387fa6436806507b3849d88/specs/deneb/polynomial-commitments.md#verify_blob_kzg_proof_batch) ### Helpers ```python -def kzg_to_versioned_hash(kzg: KZGCommitment) -> VersionedHash: - return BLOB_COMMITMENT_VERSION_KZG + sha256(kzg)[1:] +def kzg_to_versioned_hash(commitment: KZGCommitment) -> VersionedHash: + return VERSIONED_HASH_VERSION_KZG + sha256(commitment)[1:] ``` Approximates `factor * e ** (numerator / denominator)` using Taylor expansion: @@ -99,93 +94,34 @@ def fake_exponential(factor: int, numerator: int, denominator: int) -> int: return output // denominator ``` -### New transaction type +### Blob transaction -We introduce a new [EIP-2718](./eip-2718.md) transaction type, -with the format being the single byte `BLOB_TX_TYPE` followed by an SSZ encoding of the -`SignedBlobTransaction` container comprising the transaction contents: +We introduce a new type of [EIP-2718](./eip-2718.md) transaction, "blob transaction", where the `TransactionType` is `BLOB_TX_TYPE` and the `TransactionPayload` is the RLP serialization of the following `TransactionPayloadBody`: -```python -class SignedBlobTransaction(Container): - message: BlobTransaction - signature: ECDSASignature - -class BlobTransaction(Container): - chain_id: uint256 - nonce: uint64 - max_priority_fee_per_gas: uint256 - max_fee_per_gas: uint256 - gas: uint64 - to: Union[None, Address] # Address = Bytes20 - value: uint256 - data: ByteList[MAX_CALLDATA_SIZE] - access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] - max_fee_per_data_gas: uint256 - blob_versioned_hashes: List[VersionedHash, MAX_VERSIONED_HASHES_LIST_SIZE] - -class AccessTuple(Container): - address: Address # Bytes20 - storage_keys: List[Hash, MAX_ACCESS_LIST_STORAGE_KEYS] - -class ECDSASignature(Container): - y_parity: boolean - r: uint256 - s: uint256 +``` +[chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes, y_parity, r, s] ``` -The `max_priority_fee_per_gas` and `max_fee_per_gas` fields follow [EIP-1559](./eip-1559.md) semantics, -and `access_list` as in [`EIP-2930`](./eip-2930.md). - -[`EIP-2718`](./eip-2718.md) is extended with a "wrapper data", the typed transaction can be encoded in two forms, dependent on the context: - -- Network (default): `TransactionType || TransactionNetworkPayload`, or `LegacyTransaction` -- Minimal (as in execution payload): `TransactionType || TransactionPayload`, or `LegacyTransaction` - -Execution-payloads / blocks use the minimal encoding of transactions. -In the transaction-pool and local transaction-journal the network encoding is used. - -For previous types of transactions the network encoding is no different, i.e. `TransactionNetworkPayload == TransactionPayload`. - -The `TransactionNetworkPayload` wraps a `TransactionPayload` with additional data: -this wrapping data SHOULD be verified directly before or after signature verification. - -When a blob transaction is passed through the network (see the [Networking](#networking) section below), -the `TransactionNetworkPayload` version of the transaction also includes `blobs` and `kzgs` (commitments list). -The execution layer verifies the wrapper validity against the inner `TransactionPayload` after signature verification as: +The fields `chain_id`, `nonce`, `max_priority_fee_per_gas`, `max_fee_per_gas`, `gas_limit`, `value`, `data`, and `access_list` follow the same semantics as [EIP-1559](./eip-1559.md). -- All hashes in `blob_versioned_hashes` must start with the byte `BLOB_COMMITMENT_VERSION_KZG` -- There may be at most `MAX_DATA_GAS_PER_BLOCK // DATA_GAS_PER_BLOB` total blob commitments in a valid block. -- There is an equal amount of versioned hashes, kzg commitments and blobs. -- The KZG commitments hash to the versioned hashes, i.e. `kzg_to_versioned_hash(kzg[i]) == versioned_hash[i]` -- The KZG commitments match the blob contents. (Note: this can be optimized with additional data, using a proof for a - random evaluation at two points derived from the commitment and blob data) +The field `to` deviates slightly from the semantics with the exception that it MUST NOT be `nil` and therefore must always represent a 20-byte address. This means that blob transactions cannot have the form of a create transaction. +The field `max_fee_per_blob_gas` is a `uint256` and the field `blob_versioned_hashes` represents a list of hash outputs from `kzg_to_versioned_hash`. -The signature is verified and `tx.origin` is calculated as follows: +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. -```python -def unsigned_tx_hash(tx: SignedBlobTransaction) -> Bytes32: - # The pre-image is prefixed with the transaction-type to avoid hash collisions with other tx hashers and types - return keccak256(BLOB_TX_TYPE + ssz.serialize(tx.message)) - -def get_origin(tx: SignedBlobTransaction) -> Address: - sig = tx.signature - # v = int(y_parity) + 27, same as EIP-1559 - return ecrecover(unsigned_tx_hash(tx), int(sig.y_parity)+27, sig.r, sig.s) -``` +#### Signature -The hash of a signed blob transaction should be computed as: +The signature values `y_parity`, `r`, and `s` are calculated by constructing a secp256k1 signature over the following digest: -```python -def signed_tx_hash(tx: SignedBlobTransaction) -> Bytes32: - return keccak256(BLOB_TX_TYPE + ssz.serialize(tx)) -``` +`keccak256(BLOB_TX_TYPE || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))`. ### Header extension -The current header encoding is extended with a new 256-bit unsigned integer field `excess_data_gas`. This is the running -total of excess data gas consumed on chain since this EIP was activated. If the total amount of data gas is below the -target, `excess_data_gas` is capped at zero. +The current header encoding is extended with two new 64-bit unsigned integer fields: + +- `blob_gas_used` is the total amount of blob gas consumed by the transactions within the block. +- `excess_blob_gas` is a running total of blob gas consumed in excess of the target, prior to the block. Blocks with above-target blob gas consumption increase this value, blocks with below-target blob gas consumption decrease it (bounded at 0). The resulting RLP encoding of the header is therefore: @@ -208,44 +144,52 @@ rlp([ 0x0000000000000000, # nonce base_fee_per_gas, withdrawals_root, - excess_data_gas + blob_gas_used, + excess_blob_gas, ]) ``` -The value of `excess_data_gas` can be calculated using the parent header and number of blobs in the block. +The value of `excess_blob_gas` can be calculated using the parent header. ```python -def calc_excess_data_gas(parent: Header, new_blobs: int) -> int: - consumed_data_gas = new_blobs * DATA_GAS_PER_BLOB - if parent.excess_data_gas + consumed_data_gas < TARGET_DATA_GAS_PER_BLOCK: +def calc_excess_blob_gas(parent: Header) -> int: + if parent.excess_blob_gas + parent.blob_gas_used < TARGET_BLOB_GAS_PER_BLOCK: return 0 else: - return parent.excess_data_gas + consumed_data_gas - TARGET_DATA_GAS_PER_BLOCK + return parent.excess_blob_gas + parent.blob_gas_used - TARGET_BLOB_GAS_PER_BLOCK ``` -For the first post-fork block, `parent.excess_data_gas` is evaluated as `0`. +For the first post-fork block, both `parent.blob_gas_used` and `parent.excess_blob_gas` are evaluated as `0`. -### Beacon chain validation +### Gas accounting -On the consensus-layer the blobs are now referenced, but not fully encoded, in the beacon block body. -Instead of embedding the full contents in the body, the contents of the blobs are propagated separately, as a "sidecar". +We introduce blob gas as a new type of gas. It is independent of normal gas and follows its own targeting rule, similar to EIP-1559. +We use the `excess_blob_gas` header field to store persistent data needed to compute the blob gas base fee. For now, only blobs are priced in blob gas. -This "sidecar" design provides forward compatibility for further data increases by black-boxing `is_data_available()`: -with full sharding `is_data_available()` can be replaced by data-availability-sampling (DAS) thus avoiding all blobs being downloaded by all beacon nodes on the network. +```python +def calc_blob_fee(header: Header, tx: Transaction) -> int: + return get_total_blob_gas(tx) * get_base_fee_per_blob_gas(header) -Note that the consensus-layer is tasked with persisting the blobs for data availability, the execution-layer is not. +def get_total_blob_gas(tx: Transaction) -> int: + return GAS_PER_BLOB * len(tx.blob_versioned_hashes) -The `ethereum/consensus-specs` repository defines the following beacon-node changes involved in this EIP: +def get_base_fee_per_blob_gas(header: Header) -> int: + return fake_exponential( + MIN_BASE_FEE_PER_BLOB_GAS, + header.excess_blob_gas, + BLOB_BASE_FEE_UPDATE_FRACTION + ) +``` -- Beacon chain: process updated beacon blocks and ensure blobs are available. -- P2P network: gossip and sync updated beacon block types and new blobs sidecars. -- Honest validator: produce beacon blocks with blobs, publish the blobs sidecars. +The block validity conditions are modified to include blob gas checks (see the [Execution layer validation](#execution-layer-validation) section below). + +The actual `blob_fee` as calculated via `calc_blob_fee` is deducted from the sender balance before transaction execution and burned, and is not refunded in case of transaction failure. ### Opcode to get versioned hashes -We add an opcode `DATAHASH` (with byte value `HASH_OPCODE_BYTE`) which reads `index` from the top of the stack -as big-endian `uint256`, and replaces it on the stack with `tx.message.blob_versioned_hashes[index]` -if `index < len(tx.message.blob_versioned_hashes)`, and otherwise with a zeroed `bytes32` value. +We add an instruction `BLOBHASH` (with opcode `HASH_OPCODE_BYTE`) which reads `index` from the top of the stack +as big-endian `uint256`, and replaces it on the stack with `tx.blob_versioned_hashes[index]` +if `index < len(tx.blob_versioned_hashes)`, and otherwise with a zeroed `bytes32` value. The opcode has a gas cost of `HASH_OPCODE_GAS`. ### Point evaluation precompile @@ -261,18 +205,19 @@ def point_evaluation_precompile(input: Bytes) -> Bytes: Verify p(z) = y given commitment that corresponds to the polynomial p(x) and a KZG proof. Also verify that the provided commitment matches the provided versioned_hash. """ - # The data is encoded as follows: versioned_hash | z | y | commitment | proof | + # The data is encoded as follows: versioned_hash | z | y | commitment | proof | with z and y being padded 32 byte big endian values + assert len(input) == 192 versioned_hash = input[:32] z = input[32:64] y = input[64:96] commitment = input[96:144] - kzg_proof = input[144:192] + proof = input[144:192] # Verify commitment matches versioned_hash assert kzg_to_versioned_hash(commitment) == versioned_hash - # Verify KZG proof - assert verify_kzg_proof(commitment, z, y, kzg_proof) + # Verify KZG proof with z and y in big endian format + assert verify_kzg_proof(commitment, z, y, proof) # Return FIELD_ELEMENTS_PER_BLOB and BLS_MODULUS as padded 32 byte big endian values return Bytes(U256(FIELD_ELEMENTS_PER_BLOB).to_be_bytes32() + U256(BLS_MODULUS).to_be_bytes32()) @@ -280,87 +225,102 @@ def point_evaluation_precompile(input: Bytes) -> Bytes: The precompile MUST reject non-canonical field elements (i.e. provided field elements MUST be strictly less than `BLS_MODULUS`). -### Gas accounting +### Consensus layer validation -We introduce data gas as a new type of gas. It is independent of normal gas and follows its own targeting rule, similar to EIP-1559. -We use the `excess_data_gas` header field to store persistent data needed to compute the data gas price. For now, only blobs are priced in data gas. +On the consensus layer the blobs are referenced, but not fully encoded, in the beacon block body. +Instead of embedding the full contents in the body, the blobs are propagated separately, as "sidecars". -```python -def calc_data_fee(tx: SignedBlobTransaction, parent: Header) -> int: - return get_total_data_gas(tx) * get_data_gasprice(header) +This "sidecar" design provides forward compatibility for further data increases by black-boxing `is_data_available()`: +with full sharding `is_data_available()` can be replaced by data-availability-sampling (DAS) thus avoiding all blobs being downloaded by all beacon nodes on the network. -def get_total_data_gas(tx: SignedBlobTransaction) -> int: - return DATA_GAS_PER_BLOB * len(tx.message.blob_versioned_hashes) +Note that the consensus layer is tasked with persisting the blobs for data availability, the execution layer is not. -def get_data_gasprice(header: Header) -> int: - return fake_exponential( - MIN_DATA_GASPRICE, - header.excess_data_gas, - DATA_GASPRICE_UPDATE_FRACTION - ) -``` +The `ethereum/consensus-specs` repository defines the following consensus layer changes involved in this EIP: + +- Beacon chain: process updated beacon blocks and ensure blobs are available. +- P2P network: gossip and sync updated beacon block types and new blob sidecars. +- Honest validator: produce beacon blocks with blobs; sign and publish the associated blob sidecars. -The block validity conditions are modified to include data gas checks: +### Execution layer validation + +On the execution layer, the block validity conditions are extended as follows: ```python def validate_block(block: Block) -> None: ... + # check that the excess blob gas was updated correctly + assert block.header.excess_blob_gas == calc_excess_blob_gas(block.parent.header) + + blob_gas_used = 0 + for tx in block.transactions: ... - # the signer must be able to afford the transaction - assert signer(tx).balance >= tx.message.gas * tx.message.max_fee_per_gas + get_total_data_gas(tx) * tx.message.max_fee_per_data_gas + # modify the check for sufficient balance + max_total_fee = tx.gas * tx.max_fee_per_gas + if get_tx_type(tx) == BLOB_TX_TYPE: + max_total_fee += get_total_blob_gas(tx) * tx.max_fee_per_blob_gas + assert signer(tx).balance >= max_total_fee - # ensure that the user was willing to at least pay the current data gasprice - assert tx.message.max_fee_per_data_gas >= get_data_gasprice(parent(block).header) -``` + ... -The actual `data_fee` as calculated via `calc_data_fee` is deducted from the sender balance before transaction execution and burned, and is not refunded in case of transaction failure. + # add validity logic specific to blob txs + if get_tx_type(tx) == BLOB_TX_TYPE: + # there must be at least one blob + assert len(tx.blob_versioned_hashes) > 0 -### Networking + # all versioned blob hashes must start with VERSIONED_HASH_VERSION_KZG + for h in tx.blob_versioned_hashes: + assert h[0] == VERSIONED_HASH_VERSION_KZG -Nodes must not automatically broadcast blob transactions to their peers. -Instead, those transactions are only announced using `NewPooledTransactionHashes` messages, and can then be manually requested via `GetPooledTransactions`. + # ensure that the user was willing to at least pay the current blob base fee + assert tx.max_fee_per_blob_gas >= get_base_fee_per_blob_gas(block.header) -Transactions are presented as `TransactionType || TransactionNetworkPayload` on the execution layer network, -the payload is a SSZ encoded container: + # keep track of total blob gas spent in the block + blob_gas_used += get_total_blob_gas(tx) + + # ensure the total blob gas spent is at most equal to the limit + assert blob_gas_used <= MAX_BLOB_GAS_PER_BLOCK + + # ensure blob_gas_used matches header + assert block.header.blob_gas_used == blob_gas_used -```python -class BlobTransactionNetworkWrapper(Container): - tx: SignedBlobTransaction - # KZGCommitment = Bytes48 - blob_kzgs: List[KZGCommitment, MAX_TX_WRAP_KZG_COMMITMENTS] - # BLSFieldElement = uint256 - blobs: List[Vector[BLSFieldElement, FIELD_ELEMENTS_PER_BLOB], LIMIT_BLOBS_PER_TX] - # KZGProof = Bytes48 - kzg_aggregated_proof: KZGProof ``` -We do network-level validation of `BlobTransactionNetworkWrapper` objects as follows: +### Networking + +Blob transactions have two network representations. During transaction gossip responses (`PooledTransactions`), the EIP-2718 `TransactionPayload` of the blob transaction is wrapped to become: -```python -def validate_blob_transaction_wrapper(wrapper: BlobTransactionNetworkWrapper): - versioned_hashes = wrapper.tx.message.blob_versioned_hashes - commitments = wrapper.blob_kzgs - blobs = wrapper.blobs - # note: assert blobs are not malformatted - assert len(versioned_hashes) == len(commitments) == len(blobs) - - # Verify that commitments match the blobs by checking the KZG proof - assert verify_aggregate_kzg_proof(blobs, commitments, wrapper.kzg_aggregated_proof) - - # Now that all commitments have been verified, check that versioned_hashes matches the commitments - for versioned_hash, commitment in zip(versioned_hashes, commitments): - assert versioned_hash == kzg_to_versioned_hash(commitment) ``` +rlp([tx_payload_body, blobs, commitments, proofs]) +``` + +Each of these elements are defined as follows: + +- `tx_payload_body` - is the `TransactionPayloadBody` of standard EIP-2718 [blob transaction](#blob-transaction) +- `blobs` - list of `Blob` items +- `commitments` - list of `KZGCommitment` of the corresponding `blobs` +- `proofs` - list of `KZGProof` of the corresponding `blobs` and `commitments` + +The node MUST validate `tx_payload_body` and verify the wrapped data against it. To do so, ensure that: + +- There are an equal number of `tx_payload_body.blob_versioned_hashes`, `blobs`, `commitments`, and `proofs`. +- The KZG `commitments` hash to the versioned hashes, i.e. `kzg_to_versioned_hash(commitments[i]) == tx_payload_body.blob_versioned_hashes[i]` +- The KZG `commitments` match the corresponding `blobs` and `proofs`. (Note: this can be optimized using `verify_blob_kzg_proof_batch`, with a proof for a + random evaluation at a point derived from the commitment and blob data for each blob) + +For body retrieval responses (`BlockBodies`), the standard EIP-2718 blob transaction `TransactionPayload` is used. + +Nodes MUST NOT automatically broadcast blob transactions to their peers. +Instead, those transactions are only announced using `NewPooledTransactionHashes` messages, and can then be manually requested via `GetPooledTransactions`. ## Rationale ### On the path to sharding This EIP introduces blob transactions in the same format in which they are expected to exist in the final sharding specification. -This provides a temporary but significant scaling relief for rollups by allowing them to initially scale to 0.25 MB per slot, +This provides a temporary but significant scaling relief for rollups by allowing them to initially scale to 0.375 MB per slot, with a separate fee market allowing fees to be very low while usage of this system is limited. The core goal of rollup scaling stopgaps is to provide temporary scaling relief, @@ -383,20 +343,16 @@ The work that is already done in this EIP includes: - _All_ of the execution / consensus cross-verification logic required for full sharding - Layer separation between `BeaconBlock` verification and data availability sampling blobs - Most of the `BeaconBlock` logic required for full sharding -- A self-adjusting independent gasprice for blobs +- A self-adjusting independent base fee for blobs The work that remains to be done to get to full sharding includes: -- A low-degree extension of the `blob_kzgs` in the consensus layer to allow 2D sampling +- A low-degree extension of the `commitments` in the consensus layer to allow 2D sampling - An actual implementation of data availability sampling - PBS (proposer/builder separation), to avoid requiring individual validators to process 32 MB of data in one slot - Proof of custody or similar in-protocol requirement for each validator to verify a particular part of the sharded data in each block -This EIP also sets the stage for longer-term protocol cleanups: - -- It adds an SSZ transaction type, and paves the precedent that all new transaction types should be SSZ -- It defines `TransactionNetworkPayload` to separate network and block encodings of a transaction type -- Its (cleaner) gas price update rule could be applied to the primary basefee +This EIP also sets the stage for longer-term protocol cleanups. For example, its (cleaner) gas base fee update rule could be applied to the primary basefee calculation. ### How rollups would function @@ -410,13 +366,13 @@ For each value it would provide a KZG proof and use the point evaluation precomp and then perform the fraud proof verification on that data as is done today. ZK rollups would provide two commitments to their transaction or state delta data: -the kzg in the blob and some commitment using whatever proof system the ZK rollup uses internally. -They would use a commitment proof of equivalence protocol, using the point evaluation precompile, -to prove that the kzg (which the protocol ensures points to available data) and the ZK rollup's own commitment refer to the same data. +the blob commitment (which the protocol ensures points to available data) and the ZK rollup's own commitment using whatever proof system the rollup uses internally. +They would use a proof of equivalence protocol, using the point evaluation precompile, +to prove that the two commitments refer to the same data. ### Versioned hashes & precompile return data -We use versioned hashes (rather than kzgs) as references to blobs in the execution layer to ensure forward compatibility with future changes. +We use versioned hashes (rather than commitments) as references to blobs in the execution layer to ensure forward compatibility with future changes. For example, if we need to switch to Merkle trees + STARKs for quantum-safety reasons, then we would add a new version, allowing the point evaluation precompile to work with the new format. Rollups would not have to make any EVM-level changes to how they work; @@ -426,30 +382,30 @@ However, the point evaluation happens inside a finite field, and it is only well In the interest of not adding another precompile, we return the modulus and the polynomial degree directly from the point evaluation precompile. It can then be used by the caller. It is also "free" in that the caller can just ignore this part of the return value without incurring an extra cost -- systems that remain upgradable for the foreseeable future will likely use this route for now. -### Data gasprice update rule +### Base fee per blob gas update rule -The data gasprice update rule is intended to approximate the formula `data_gasprice = MIN_DATA_GASPRICE * e**(excess_data_gas / DATA_GASPRICE_UPDATE_FRACTION)`, -where `excess_data_gas` is the total "extra" amount of data gas that the chain has consumed relative to the "targeted" number (`TARGET_DATA_GAS_PER_BLOCK` per block). -Like EIP-1559, it's a self-correcting formula: as the excess goes higher, the `data_gasprice` increases exponentially, reducing usage and eventually forcing the excess back down. +The base fee per blob gas update rule is intended to approximate the formula `base_fee_per_blob_gas = MIN_BASE_FEE_PER_BLOB_GAS * e**(excess_blob_gas / BLOB_BASE_FEE_UPDATE_FRACTION)`, +where `excess_blob_gas` is the total "extra" amount of blob gas that the chain has consumed relative to the "targeted" number (`TARGET_BLOB_GAS_PER_BLOCK` per block). +Like EIP-1559, it's a self-correcting formula: as the excess goes higher, the `base_fee_per_blob_gas` increases exponentially, reducing usage and eventually forcing the excess back down. The block-by-block behavior is roughly as follows. -If block `N` consumes `X` data gas, then in block `N+1` `excess_data_gas` increases by `X - TARGET_DATA_GAS_PER_BLOCK`, -and so the `data_gasprice` of block `N+1` increases by a factor of `e**((X - TARGET_DATA_GAS_PER_BLOCK) / DATA_GASPRICE_UPDATE_FRACTION)`. +If block `N` consumes `X` blob gas, then in block `N+1` `excess_blob_gas` increases by `X - TARGET_BLOB_GAS_PER_BLOCK`, +and so the `base_fee_per_blob_gas` of block `N+1` increases by a factor of `e**((X - TARGET_BLOB_GAS_PER_BLOCK) / BLOB_BASE_FEE_UPDATE_FRACTION)`. Hence, it has a similar effect to the existing EIP-1559, but is more "stable" in the sense that it responds in the same way to the same total usage regardless of how it's distributed. -The parameter `DATA_GASPRICE_UPDATE_FRACTION` controls the maximum rate of change of the blob gas price. It is chosen to target a maximum change rate of `e(TARGET_DATA_GAS_PER_BLOCK / DATA_GASPRICE_UPDATE_FRACTION) ≈ 1.125` per block. +The parameter `BLOB_BASE_FEE_UPDATE_FRACTION` controls the maximum rate of change of the base fee per blob gas. It is chosen to target a maximum change rate of `e**(TARGET_BLOB_GAS_PER_BLOCK / BLOB_BASE_FEE_UPDATE_FRACTION) ≈ 1.125` per block. ### Throughput -The values for `TARGET_DATA_GAS_PER_BLOCK` and `MAX_DATA_GAS_PER_BLOCK` are chosen to correspond to a target of 2 blobs (0.25 MB) and maximum of 4 blobs (0.5 MB) per block. These small initial limits are intended to minimize the strain on the network created by this EIP and are expected to be increased in future upgrades as the network demonstrates reliability under larger blocks. +The values for `TARGET_BLOB_GAS_PER_BLOCK` and `MAX_BLOB_GAS_PER_BLOCK` are chosen to correspond to a target of 3 blobs (0.375 MB) and maximum of 6 blobs (0.75 MB) per block. These small initial limits are intended to minimize the strain on the network created by this EIP and are expected to be increased in future upgrades as the network demonstrates reliability under larger blocks. ## Backwards Compatibility ### Blob non-accessibility -This EIP introduces a transaction type that has a distinct mempool version (`BlobTransactionNetworkWrapper`) and execution-payload version (`SignedBlobTransaction`), -with only one-way convertibility between the two. The blobs are in the `BlobTransactionNetworkWrapper` and not in the `SignedBlobTransaction`; -instead, they go into the `BeaconBlockBody`. This means that there is now a part of a transaction that will not be accessible from the web3 API. +This EIP introduces a transaction type that has a distinct mempool version and execution-payload version, +with only one-way convertibility between the two. The blobs are in the network representation and not in the consensus representation; +instead, they are coupled with the beacon block. This means that there is now a part of a transaction that will not be accessible from the web3 API. ### Mempool issues @@ -460,21 +416,21 @@ By only broadcasting announcements for blob transactions, receiving nodes will h allowing them to throttle throughput to an acceptable level. [EIP-5793](./eip-5793.md) will give further fine-grained control to nodes by extending the `NewPooledTransactionHashes` announcement messages to include the transaction type and size. -In addition, we recommend including a 1.1x data gasprice bump requirement to the mempool transaction replacement rules. +In addition, we recommend including a 1.1x base fee per blob gas bump requirement to the mempool transaction replacement rules. ## Test Cases -TBD +Execution layer test cases for this EIP can be found in the [`eip4844_blobs`](https://github.com/ethereum/execution-spec-tests/tree/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip4844_blobs) of the `ethereum/execution-spec-tests` repository. Consensus layer test cases can be found [here](https://github.com/ethereum/consensus-specs/tree/2297c09b7e457a13f7b2261a28cb45777be82f83/tests/core/pyspec/eth2spec/test/deneb). ## Security Considerations -This EIP increases the storage requirements per Beacon block by a maximum of ~0.5 MB. -This is 4x larger than the theoretical maximum size of a block today (30M gas / 16 gas per calldata byte = 1.875M bytes), and so it will not greatly increase worst-case bandwidth. -Post-merge, block times are expected to be static rather than an unpredictable Poisson distribution, giving a guaranteed period of time for large blocks to propagate. +This EIP increases the bandwidth requirements per beacon block by a maximum of ~0.75 MB. +This is 40% larger than the theoretical maximum size of a block today (30M gas / 16 gas per calldata byte = 1.875M bytes), and so it will not greatly increase worst-case bandwidth. +Post-merge, block times are static rather than an unpredictable Poisson distribution, giving a guaranteed period of time for large blocks to propagate. The _sustained_ load of this EIP is much lower than alternatives that reduce calldata costs, even if the calldata is limited, -because there is no existing software that stores the blobs indefinitely and there is no expectation that they need to be stored for as long as an execution payload. -This makes it easier to implement a policy that these blobs should be deleted after e.g. 30-60 days, +because there is no expectation that the blobs need to be stored for as long as an execution payload. +This makes it possible to implement a policy that these blobs must be kept for at least a certain period. The specific value chosen is `MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS` epochs, which is around 18 days, a much shorter delay compared to proposed (but yet to be implemented) one-year rotation times for execution payload history. ## Copyright diff --git a/EIPS/eip-4881.md b/EIPS/eip-4881.md index 6b95d597cf9688..5d02f92261e8d1 100644 --- a/EIPS/eip-4881.md +++ b/EIPS/eip-4881.md @@ -3,20 +3,23 @@ eip: 4881 title: Deposit Contract Snapshot Interface description: Establishing the format and endpoint for transmitting a snapshot of the deposit Merkle tree author: Mark Mackey (@ethDreamer) -discussions-to: https://ethereum-magicians.org/t/eip-4881-deposit-contract-snapshot-interface/ -status: Draft +discussions-to: https://ethereum-magicians.org/t/eip-4881-deposit-contract-snapshot-interface/8554 +status: Final type: Standards Track category: Interface created: 2021-01-29 --- ## Abstract + This EIP defines a standard format for transmitting the deposit contract Merkle tree in a compressed form during weak subjectivity sync. This allows newly syncing consensus clients to reconstruct the deposit tree much faster than downloading all historical deposits. The format proposed also allows clients to prune deposits that are no longer needed to participate fully in consensus (see [Deposit Finalization Flow](#deposit-finalization-flow)). ## Motivation -Most client implementations require beacon nodes to download and store every deposit log since the launch of the deposit contract in order to reconstruct the deposit Merkle tree. This approach requires nodes to store far more deposits than necessary to fully participate in consensus. It also needlessly increases the time it takes for new nodes to fully sync, which is especially noticeable during weak subjectivity sync. Furthermore, if [EIP-4444](./eip-4444.md) is adopted, it will not always be possible to download all historical deposit logs from full nodes. + +To reconstruct the deposit Merkle tree, most client implementations require beacon nodes to download and store every deposit log since the launch of the deposit contract. However, this approach requires beacon nodes to store far more deposits than necessary to participate in consensus. Additionally, this leads to increased sync times for new nodes, which is particularly evident during weak subjectivity sync. This simplistic approach also prevents historical contract logs from being pruned from full nodes, a prospect frequently discussed in the context of limiting state growth. ## Specification + Consensus clients MAY continue to implement the deposit Merkle tree however they choose. However, when transmitting the tree to newly syncing nodes, clients MUST use the following format: ```python @@ -29,6 +32,7 @@ class DepositTreeSnapshot: ``` Where `finalized` is a variable-length list (of maximum size `DEPOSIT_CONTRACT_DEPTH`) containing the hashes defined in the [Deposit Finalization Flow](#deposit-finalization-flow) section below. The fields `deposit_root`, `deposit_count`, and `execution_block_hash` store the same information as the [`Eth1Data`](https://github.com/ethereum/consensus-specs/blob/2b45496fe48fa75450ad29a05bdd48866f86528a/specs/phase0/beacon-chain.md#eth1data) object that corresponds to the snapshot, and `execution_block_height` is the height of the execution block with hash `execution_block_hash`. Consensus clients MUST make this structure available via the Beacon Node API endpoint: + ``` /eth/v1/beacon/deposit_snapshot ``` @@ -37,13 +41,13 @@ Where `finalized` is a variable-length list (of maximum size `DEPOSIT_CONTRACT_D During deposit processing, the beacon chain requires deposits to be submitted along with a Merkle path to the deposit root. This is required exactly once for each deposit. When a deposit has been processed by the beacon chain and the [deposit finalization conditions](#deposit-finalization-conditions) have been met, many of the hashes along the path to the deposit root will never be required again to construct Merkle proofs on chain. These unnecessary hashes MAY be pruned to save space. The image below illustrates the evolution of the deposit Merkle tree under this process alongside the corresponding `DepositTreeSnapshot` as new deposits are added and older deposits become finalized: - +![deposit tree evolution](../assets/eip-4881/deposit_tree_evolution.svg) ## Rationale The format in this specification was chosen to achieve several goals simultaneously: -1. Enable reconstruction of the deposit contract Merkle tree under the adoption of [EIP-4444](./eip-4444.md) +1. Enable reconstruction of the deposit contract Merkle tree without requiring full nodes to store all historical contract logs 2. Avoid requiring consensus nodes to retain more deposits than necessary to fully participate in consensus 3. Simplicity of implementation (see [Reference Implementation](#reference-implementation) section) 4. Increase speed of weak subjectivity sync @@ -81,6 +85,7 @@ class DepositTestCase: ``` This EIP also includes other files for testing: + * [deposit_snapshot.py](../assets/eip-4881/deposit_snapshot.py) contains the same code as the [Reference Implementation](#reference-implementation) * [eip_4881.py](../assets/eip-4881/eip_4881.py) contains boilerplate declarations * [test_deposit_snapshot.py](../assets/eip-4881/test_deposit_snapshot.py) includes code for running test cases against the reference implementation @@ -88,9 +93,11 @@ This EIP also includes other files for testing: If these files are downloaded to the same directory, the test cases can be run by executing `pytest` in that directory. ## Reference Implementation + This implementation lacks full error checking and is optimized for readability over efficiency. If `tree` is a `DepositTree`, then the `DepositTreeSnapshot` can be obtained by calling `tree.get_snapshot()` and a new instance of the tree can be recovered from the snapshot by calling `DepositTree.from_snapshot()`. See the [Deposit Finalization Conditions](#deposit-finalization-conditions) section for discussion on when the tree can be pruned by calling `tree.finalize()`. Generating proofs for deposits against an earlier version of the tree is relatively fast in this implementation; just create a copy of the finalized tree with `copy = DepositTree.from_snapshot(tree.get_snapshot())` and then append the remaining deposits to the desired count with `copy.push_leaf(deposit)`. Proofs can then be obtained with `copy.get_proof(index)`. + ```python from __future__ import annotations from typing import List, Optional, Tuple @@ -123,6 +130,9 @@ class DepositTreeSnapshot: execution_block: Tuple[Hash32, uint64]) -> DepositTreeSnapshot: snapshot = DepositTreeSnapshot( finalized, zerohashes[0], deposit_count, execution_block[0], execution_block[1]) + # A real implementation should store the deposit_root from the eth1_data passed to + # DepositTree.finalize() instead of relying on calculate_root() here. This allows + # the snapshot to be validated using calculate_root(). snapshot.deposit_root = snapshot.calculate_root() return snapshot @@ -305,10 +315,6 @@ Care must be taken not to send a snapshot which includes deposits that haven't b When these conditions are met, the tree can be pruned in the [reference implementation](#reference-implementation) by calling `tree.finalize(eth1data, execution_block_height)` -### Deposit Queue Exceeds EIP-4444 Pruning Period - -The proposed design could fail if the deposit queue becomes so large that deposits cannot be processed within the [EIP-4444 Pruning Period](./eip-4444.md) (currently set to 1 year). The beacon chain can process `MAX_DEPOSITS/SECONDS_PER_SLOT` deposits/second without skipped slots. Even under extreme conditions where 25% of slots are skipped, the deposit queue would need to be >31.5 million to hit this limit. This is more than 8x the total supply of ether assuming each deposit is a full validator. The minimum deposit is 1 ETH so an attacker would need to burn >30 Million ETH to create these conditions. - - ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-4883.md b/EIPS/eip-4883.md index 22c8c6debf121c..ccaf2633e9c6c6 100644 --- a/EIPS/eip-4883.md +++ b/EIPS/eip-4883.md @@ -1,71 +1,7 @@ --- eip: 4883 -title: Composable SVG NFT -description: Compose an SVG NFT by concatenating the SVG with the rendered SVG of another NFT. -author: Andrew B Coathup (@abcoathup), Alex (@AlexPartyPanda), Damian Martinelli (@damianmarti), blockdev (@0xbok), Austin Griffith (@austintgriffith) -discussions-to: https://ethereum-magicians.org/t/eip-4883-composable-svg-nft/8765 -status: Draft -type: Standards Track category: ERC -created: 2022-03-08 -requires: 165, 721 +status: Moved --- -## Abstract - -Compose an SVG (Scalable Vector Graphics) NFT by concatenating the SVG with the SVG of another NFT rendered as a string for a specific token ID. - -## Motivation - -On-chain SVG NFTs allow for NFTs to be entirely on-chain by returning artwork as SVG in a data URI of the `tokenUri` function. Composability allows on-chain SVG NFTs to be crafted. e.g. adding glasses & hat NFTs to a profile pic NFT or a fish NFT to a fish tank NFT. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// @title EIP-4883 Non-Fungible Token Standard -interface IERC4883 is IERC165 { - function renderTokenById(uint256 id) external view returns (string memory); -} -``` - -`renderTokenById` must return the SVG body for the specified token `id` and must either be an empty string or valid SVG element(s). - -## Rationale - -SVG elements can be string concatenated to compose an SVG. - -### Ordering of concatenation - -SVG uses a "painters model" of rendering. - -**Scalable Vector Graphics (SVG) 1.1 (Second Edition)**, section: **3.3 Rendering Order** ->Elements in an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements. - -The ordering of the SVG concatenation determines the drawing order rather than any concept of a z-index. - -This EIP only specifies the rendering of the rendered SVG NFT and does not require any specific ordering when composing. This allows the SVG NFT to use a rendered SVG NFT as a foreground or a background as required. - -### Alternatives to concatenation - -SVG specifies a `link` tag. Linking could allow for complex SVGs to be composed but would require creating a URI format and then getting ecosystem adoption. As string concatenation of SVG's is already supported, the simpler approach of concatenation is used. - -### Sizing - -This EIP doesn't specify any requirements on the size of the rendered SVG. Any scaling based on sizing can be performed by the SVG NFT as required. - -### Render function name - -The render function is named `renderTokenById` as this function name was first used by Loogies and allows existing deployed NFTs to be compatible with this EIP. - -## Backwards Compatibility -This EIP has no backwards compatibility concerns - - -## Security Considerations - -- SVG uses a "painters model" of rendering. A rendered SVG body could be added and completely obscure the existing SVG NFT artwork. -- SVG is XML and can contain malicious content, and while it won't impact the contract, it could impact the use of the SVG. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4883.md diff --git a/EIPS/eip-4885.md b/EIPS/eip-4885.md index 5c543c18c78691..4893c605f95460 100644 --- a/EIPS/eip-4885.md +++ b/EIPS/eip-4885.md @@ -1,201 +1,7 @@ --- eip: 4885 -title: Subscription NFTs and Multi Tokens -description: An interface for subscription tokens that gives holders subscriptions to NFTs and multi tokens -author: Jules Lai (@julesl23) -discussions-to: https://ethereum-magicians.org/t/eip-subscription-token-standard/8531 -status: Draft -type: Standards Track category: ERC -created: 2022-03-08 -requires: 165, 721, 1155 +status: Moved --- -## Abstract - -The following standard allows for the implementation of a standard API for subscribing to non-fungible and multi tokens. [EIP-20](./eip-20.md) tokens are deposited in exchange for subscription tokens that give the right to use said non-fungible and multi tokens for a specified time limited or unlimited period. - -## Motivation - -This standard offers a flexible, general purpose way to subscribe to the use of assets or services offered by [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md) contracts. From here on in, for the sake of simplicity, these contracts will be known as NFTs; the provider is the issuer of said NFTs and the subscriber(s) uses them. - -This proposal was originally conceived from the want to give creators of music and film, back control. The distribution and delivery of digital content is currently the purview of centralised tech corporations who offer homogeneous subscription models to their customers. This proposal specifies a standard for dapp developers to give creators the ability to set their own custom subscription models and hence, open up new revenue streams that can lead to decentralised distribution and delivery models. - -Use cases include any sort of periodic (e.g. daily, weekly, monthly, quarterly, yearly/annual, or seasonal) use of or access to assets or services such as: - -- Subscriptions for streaming music, video, e-learning or book/news services -- Sharing of digital assets among subscribers -- Club memberships such as health clubs -- Season tickets for sports and e-sports -- Agreement between parties to exchange fixed rate subscription stream with variable income in DeFi -- Renting in-game assets -- Etc. - -The subscription token borrows a few functions from the EIP-20 specification. An implementer is free to implement the rest of the standard; allowing for example subscription tokens to be transferred in secondary markets, sent as gifts or for refunds etc. - -## Specification - -The subscriber deposits EIP-20 to receive an NFT and subscription. Subscription tokens balance automatically decreases linearly over the lifetime of usage of the NFT, and use of the NFT is disabled once the subscription token balance falls to zero. The subscriber can top up the balance to extend the lifetime of the subscription by depositing EIP-20 tokens in exchange for more subscription tokens. - -Smart contracts implementing this EIP standard MUST implement the [EIP-165](./eip-165.md) supportsInterface function and MUST return the constant value true if 0xC1A48422 is passed through the interfaceID argument. Note that revert in this document MAY mean a require, throw (not recommended as depreciated) or revert solidity statement with or without error messages. - -```solidity -interface ISubscriptionToken { - /** - @dev This emits when the subscription token constructor or initialize method is - executed. - @param name The name of the subscription token - @param symbol The symbol of the subscription token - @param provider The provider of the subscription whom receives the deposits - @param subscriptionToken The subscription token contract address - @param baseToken The ERC-20 compatible token to use for the deposits. - @param nft Address of the `nft` contract that the provider mints/transfers from. - All tokenIds referred to in this interface MUST be token instances of this `nft` contract. - */ - event InitializeSubscriptionToken( - string name, - string symbol, - address provider, - address indexed subscriptionToken, - address indexed baseToken, - address indexed nft, - string uri - ); - - /** - @dev This emits for every new subscriber to `nft` contract of token `tokenId`. - `subscriber` MUST have received `nft` of token `tokenId` in their account. - @param subscriber The subscriber account - @param tokenId MUST be token id of `nft` sent to `subscriber` - @param uri MUST be uri of the `nft` that was sent to `subscriber` or empty string - */ - event SubscribeToNFT( - address indexed subscriber, - uint256 indexed tokenId, - string uri - ); - - /** - @dev Emits when `subscriber` deposits ERC-20 of token type `baseToken` via the `deposit method. - This tops up `subscriber` balance of subscription tokens - @param depositAmount The amount of ERC-20 of type `baseToken` deposited - @param subscriptionTokenAmount The amount of subscription tokens sent in exchange to `subscriber` - @param subscriptionPeriod Amount of additional time in seconds subscription is extended - */ - event Deposit( - address indexed subscriber, - uint256 indexed tokenId, - uint256 depositAmount, - uint256 subscriptionTokenAmount, - uint256 subscriptionPeriod - ); - - /** - @return The name of the subscription token - */ - function name() external view returns (string memory); - - /** - @return The symbol of the subscription token - */ - function symbol() external view returns (string memory); - - /** - @notice Subscribes `subscriber` to `nft` of 'tokenId'. `subscriber` MUST receive `nft` - of token `tokenId` in their account. - @dev MUST revert if `subscriber` is already subscribed to `nft` of 'tokenId' - MUST revert if 'nft' has not approved the `subscriptionToken` contract address as operator. - @param subscriber The subscriber account. MUST revert if zero address. - @param tokenId MUST be token id of `nft` contract sent to `subscriber` - `tokenId` emitted from event `SubscribeToNFT` MUST be the same as tokenId except when - tokenId is zero; allows OPTIONAL tokenid that is then set internally and minted by - `nft` contract - @param uri The OPTIONAL uri of the `nft`. - `uri` emitted from event `SubscribeToNFT` MUST be the same as uri except when uri is empty. - */ - function subscribeToNFT( - address subscriber, - uint256 tokenId, - string memory uri - ) external; - - /** - @notice Top up balance of subscription tokens held by `subscriber` - @dev MUST revert if `subscriber` is not subscribed to `nft` of 'tokenId' - MUST revert if 'nft' has not approved the `subscriptionToken` contract address as operator. - @param subscriber The subscriber account. MUST revert if zero address. - @param tokenId The token id of `nft` contract to subscribe to - @param depositAmount The amount of ERC-20 token of contract address `baseToken` to deposit - in exchange for subscription tokens of contract address `subscriptionToken` - */ - function deposit( - address subscriber, - uint256 tokenId, - uint256 depositAmount - ) external payable; - - /** - @return The balance of subscription tokens held by `subscriber`. - RECOMMENDED that the balance decreases linearly to zero for time limited subscriptions - RECOMMENDED that the balance remains the same for life long subscriptions - MUST return zero balance if the `subscriber` does not hold `nft` of 'tokenId' - MUST revert if subscription has not yet started via the `deposit` function - When the balance is zero, the use of `nft` of `tokenId` MUST NOT be allowed for `subscriber` - */ - function balanceOf(address subscriber) external view returns (uint256); -} -``` - -### Subscription token balances - -An example implementation mints an amount of subscription token that totals to one subscription token per day of the subscription period length paid for by the subscriber; for example a week would be for seven subscription tokens. The subscription token balance then decreases automatically at a rate of one token per day continuously and linearly over time until zero. The `balanceOf` function can be implemented lazily by calculating the amount of subscription tokens left only when it is called as a view function, thus has no gas cost. - -### Subscription token price - -Subscription token price paid per token per second can be calculated from the `Deposit` event parameters as -`depositAmount` / (`subscriptionTokenAmount` \* `subscriptionPeriod`) - -### NFT metadata - -The NFT's metadata can store information of the asset/service offered to the subscriber by the provider for the duration of the subscription. This MAY be the terms and conditions of the agreed subscription service offered by the provider to the subscriber. It MAY also be the metadata of the NFT asset if this is offered directly. This standard is kept purposely general to cater for many different use cases of NFTs. - -### Subscription expiry - -When the subscription token balance falls to zero for a subscriber (signifying that the subscription has expired) then it is up to the implementer on how to handle this for their particular use case. For example, a provider may stop streaming media service to a subscriber. For an NFT that represents an image stored off-chain, perhaps the NFT's `uri` function no longer returns back a link to its metadata. - -### Caveats - -With some traditional subscription models based on fiat currencies, the subscribers' saved payment credentials are used to automatically purchase to extend the subscription period, at or just before expiry. This feature is not possible in this proposal specification as recurring payments will have to have allowance approved for signed by a subscriber for each payment when using purely cryptocurrencies. - -This proposal does not deal with pausing subscriptions directly, implementers can write their own or inherit off 3rd party smart contract abstractions such as OpenZeppelin's Pausable. In that case, `balanceOf` method would need extra logic and storage to account for the length of time the subscription tokens were paused. - -## Rationale - -### Tokenisation of subscriptions - -The subscription itself has value when it is exchanged for a deposit. This proposal enables subscriptions to be 'tokenised' thus secondary markets can exist where the subscription tokens can be bought and sold. For example, a fan might want to sell their season ticket, that gives access to live sporting events, on to another fan. This would not be as easily possible if there was only a date expiry extension feature added to NFTs. -An implementer can simply implement the rest of the EIP-20 functions for subscription tokens to be traded. It is left to the implementer to decide if the subscription service offered is non-fungible or fungible. If non-fungible then buying the subscription tokens would simply give the same period left to expiration. If fungible and the purchaser already had an existing subscription for the same service then their total subscription period can be extended by the amount of subscription tokens bought. - -### Cater for current and future uses of NFTs - -This proposal purposely keeps `tokenId` and `uri` optional in the `subcribeToNFT` method to keep the specification general purpose. Some use cases such as pre-computed image NFT collections don't require a different 'uri', just a different `tokenId` for each NFT. However, in other use cases such as those that require legal contracts between both parties, individual `uri` links are probably required as the NFT's metadata may require information from both parties to be stored on immutable storage. - -### Giving back users control - -Traditional subscription models, particularly with streaming services, control of the subscription model is totally with that of the central service provider. This proposal gives decentralised services a standard way to give control back to their users. Hence each user is able to develop their own subscription eco system and administer it towards one that suits theirs and their subscribers' needs. - -## Backwards Compatibility - -A subscription token contract can be fully compatible with EIP-20 specification to allow, for example, transfers from one subscriber to another subscriber or user. EIP-20 methods `name`, `symbol` and `balanceOf` are already part of the specification of this proposal, and it is left to the implementer to choose whether to implement the rest of EIP-20's interface by considering their own use case. - -Use of subscription tokens is in effect an indirect way to control the lifetime of an NFT. As such it is assumed that this arrangement would work best when the NFTs and subscription token contracts subscribing to the NFTs, are deployed by the same platform or decentralised app. It MUST NOT have an impact or dependencies to existing NFTs that have not approved the subscription token as an operator. Indeed in this case, any other parties wouldn't be aware of and any NFT lifetime dependencies will be ignored, hence should not work anyway. To this end, this proposal specifies that the 'nft' MUST have approved the `subscriptionToken` contract address as operator. - -## Security Considerations - -It is normal for service providers to receive subscriber payments upfront before the subscriber gets to use the service. Indeed this proposal via the `deposit` method follows this remit. It would therefore be possible that a service provider sets up, receives the deposits and then does not provide or provides the service poorly to its subscribers. This happens in the traditional world too and this proposal does not cover how to resolve this. - -The `subscribeToNFT` method takes a parameter `uri` link to the `nft` metadata. It is possible if stored on centralised storage that the owners can change the metadata, or perhaps the metadata is hacked which is an issue with vanilla NFT contracts too. But because the `uri` is provided at the time of subscription rather then deployment, it is RECOMMENDED that where the use case requires, implementers ensure that the `uri` link is to immutable storage. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4885.md diff --git a/EIPS/eip-4886.md b/EIPS/eip-4886.md index 1bddf3cdcdc44e..9bf28952e4beb5 100644 --- a/EIPS/eip-4886.md +++ b/EIPS/eip-4886.md @@ -1,295 +1,7 @@ --- eip: 4886 -title: Proxy Ownership Register -description: A proxy ownership register allowing trustless proof of ownership between Ethereum addresses, with delegated asset delivery -author: Omnus Sunmo (@omnus) -discussions-to: https://ethereum-magicians.org/t/eip-4886-a-proxy-ownership-and-asset-delivery-register/8559 -status: Draft -type: Standards Track category: ERC -created: 2022-09-03 +status: Moved --- -## Abstract - -A proxy protocol that allows users to nominate a proxy address to act on behalf of another wallet address, together with a delivery address for new assets. Smart contracts and applications making use of the protocol can take a proxy address and lookup holding information for the nominator address. This has a number of practical applications, including allowing users to store valuable assets safely in a cold wallet and interact with smart contracts using a proxy address of low value. The assets in the nominator are protected as all contract interactions take place with the proxy address. This eliminates a number of exploits seen recently where users' assets are drained through a malicious contract interaction. In addition, the register holds a delivery address, allowing new assets to be delivered directly to a cold wallet address. - -## Motivation - -To make full use of Ethereum users often need to prove their ownership of existing assets. For example: - * Discord communities require users to sign a message with their wallet to prove they hold the tokens or NFTs of that community. - * Whitelist events (for example recent airdrops, or NFT mints), require the user to interact using a given address to prove eligibility. - * Voting in DAOs and other protocols require the user to sign using the address that holds the relevant assets. - - There are more examples, with the unifying theme being that the user must make use of the address with the assets to derive the platform benefit. This means the addresses holding these assets cannot be truly 'cold', and is a gift to malicious developers seeking to steal valuable assets. For example, a new project can offer free NFTs to holders of an existing NFT asset. The existing holders have to prove ownership by minting from the wallet with the asset that determined eligibility. This presents numerous possible attack vectors for a malicious developer who knows that all users interacting with the contract have an asset of that type. - - Possibly even more damaging is the effect on user confidence across the whole ecosystem. Users become reluctant to interact with apps and smart contracts for fear of putting their assets at risk. They may also decide not to store assets in cold wallet addresses as they need to prove they own them on a regular basis. A pertinent example is the user trying to decide whether to 'vault' their NFT and lose access to a discord channel, or keep their NFT in another wallet, or even to connect their 'vault' to discord. - - Ethereum is amazing at providing trustless proofs. The *only* time a user should need to interact using the wallet that holds an asset is if they intend to sell or transfer that asset. If a user merely wishes to prove ownership (to access a resource, get an airdrop, mint an NFT, or vote in a DAO), they should do this through a trustless proof stored on-chain. - - Furthermore, users should be able to decide where new assets are delivered, rather than them being delivered to the wallet providing the interaction. This allows hot wallets to acquire assets sent directly to a cold wallet 'vault', possibly even the one they are representing in terms of asset ownership. - - The aim of this EIP is to provide a convenient method to avoid this security concern and empower more people to feel confident leveraging the full scope of Ethereum functionality. Our vision is an Ethereum where users setup a new hardware wallet for assets they wish to hold long-term, then make one single contract interaction with that wallet: to nominate a hot wallet proxy. That user can always prove they own assets on that address, and they can specify it as a delivery address for new asset delivery. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Definitions - - * Delivery address: The address that assets will be delivered to for the current Proxy Record, i.e. a new NFT minted by the Proxy address, representing the Nominator address, should be delivered to the Delivery address. - * Nomination: Where a Nominator has nominated a Proxy address. Will only be active when the Proxy has accepted the nomination. - * Nominator address: The address that proposes a proxy relationship. This address nominates another address to act as its proxy, representing it and its holdings in all interactions. - * Proxy address: The address that will represent a Nominator on-chain. - * Proxy Record: An active proxy relationship encompassing a Nominator, Proxy and Delivery. - * Register: The main EPS contract, which holds details of both Nominations and Proxy Records. - -### EPS Specification - -There are two main parts to the register - a nomination and a proxy record: - - Contract / Dapp Register - - Nominator: 0x1234.. Nominator: 0x1234.. - Proxy: 0x5678.. ---------> Proxy: 0x4567.. - Delivery: 0x9876.. - -The first step to creating a proxy record is for an address to nominate another address as its proxy. This creates a nomination that maps the nominator (the address making the nomination) to the proposed proxy address. - -This is not a proxy record on the register at this stage, as the proxy address needs to first accept the nomination. Until the nomination is accepted it can be considered to be pending. Once the proxy address has accepted the nomination a proxy record is added to the register. - -When accepting a nomination the proxy address sets the delivery address for that proxy record. The proxy address remains in control of updating that delivery address as required. Both the nominator and proxy can delete the proxy record and nomination at any time. The proxy will continue forever if not deleted - it is eternal. - -The register is a single smart contract that stores all nomination and register records. The information held for each is as follows: - * Nomination: - * The address of the Nominator - * The address of the Proposed Proxy - -* Proxy Record: - * The address of the Nominator - * The address of the Proxy - * The delivery address for proxied deliveries - -Any address can act as a Nominator or a Proxy. A Nomination must have been made first in order for an address to accept acting as a Proxy. - -A Nomination cannot be made to an address that is already active as either a Proxy or a Nominator, i.e. that address is already in an active proxy relationship. - -The information for both Nominations and Proxy records is held as a mapping. For the Nomination this is address => address for the Nominator to the Proxy address. For the Proxy Record the mapping is from address => struct for the Proxy Address to a struct containing the Nominator and Delivery address. - -Mapping between an address and its Nominator and Delivery address is a simple process as shown below: - - Contract / Dapp Register - - | | - |------------- 0x4567..---------------> | - | | - | <-------nominator: 0x1234..---------- | - | delivery: 0x9876.. | - | | - -The protocol is fully backwards compatible. If it is passed an address that does not have an active mapping it will pass back the received address as both the Nominator and Delivery address, thereby preserving functionality as the address is acting on its own behalf. - - Contract / Dapp Register - - | | - |------------- 0x0222..---------------> | - | | - | <-------nominator: 0x0222..---------- | - | delivery: 0x0222.. | - | | - -If the EPS register is passed the address of a Nominator it will revert. This is of vital importance. The purpose of the proxy is that the Proxy address is operating on behalf of the Nominator. The Proxy address therefore can derive the same benefits as the Nominator (for example discord roles based on the Nominator's holdings, or mint NFTs that require another NFT to be held). It is therefore imperative that the Nominator in an active proxy cannot also interact and derive these benefits, otherwise two addresses represent the same holding. A Nominator can of course delete the Proxy Record at any time and interact on it's own behalf, with the Proxy address instantly losing any benefits associated with the proxy relationship. - -### Solidity Interface Definition - -**Nomination Exists** - - function nominationExists(address _nominator) external view returns (bool); - -Returns true if a Nomination exists for the address specified. - -**Nomination Exists for Caller** - - function nominationExistsForCaller() external view returns (bool); - -Returns true if a Nomination exists for the msg.sender. - -**Proxy Record Exists** - - function proxyRecordExists(address _proxy) external view returns (bool); - -Returns true if a Proxy Record exists for the passed Proxy address. - -**Proxy Record Exists for Caller** - - function proxyRecordExistsForCaller() external view returns (bool); - -Returns true if a Proxy Record exists for the msg.sender. - -**Nominator Record Exists** - - function nominatorRecordExists(address _nominator) external view returns (bool); - -Returns true if a Proxy Record exists for the passed Nominator address. - -**Nominator Record Exists for Caller** - - function nominatorRecordExistsForCaller() external view returns (bool); - -Returns true if a Proxy Record exists for the msg.sender. - -**Get Proxy Record** - - function getProxyRecord(address _proxy) external view returns (address nominator, address proxy, address delivery); - -Returns Nominator, Proxy and Delivery address for a passed Proxy address. - -**Get Proxy Record for Caller** - - function getProxyRecordForCaller() external view returns (address nominator, address proxy, address delivery); - -Returns Nominator, Proxy and Delivery address for msg.sender as Proxy address. - -**Get Nominator Record** - - function getNominatorRecord(address _nominator) external view returns (address nominator, address proxy, address delivery); - -Returns Nominator, Proxy and Delivery address for a passed Nominator address. - -**Get Nominator Record for Caller** - - function getNominatorRecordForCaller() external view returns (address nominator, address proxy, address delivery); - -Returns Nominator, Proxy and Delivery address for msg.sender address as Nominator. - -**Address Is Active** - - function addressIsActive(address _receivedAddress) external view returns (bool); - -Returns true if the passed address is Nominator or Proxy address on an active Proxy Record. - -**Address Is Active for Caller** - - function addressIsActiveForCaller() external view returns (bool); - -Returns true if msg.sender is Nominator or Proxy address on an active Proxy Record. - -**Get Nomination** - -function getNomination(address _nominator) external view returns (address proxy); - -Returns the proxy address for a Nomination when passed a Nominator. - -**Get Nomination for Caller** - -function getNominationForCaller() external view returns (address proxy); - -Returns the proxy address for a Nomination if msg.sender is a Nominator - -**Get Addresses** - - function getAddresses(address _receivedAddress) external view returns (address nominator, address delivery, bool isProxied); - -Returns the Nominator, Proxy, Delivery and a boolean isProxied for the passed address. If you pass an address that is not a Proxy address it will return address(0) for the Nominator, Proxy and Delivery address and isProxied of false. If you pass an address that is a Proxy address it will return the relvant addresses and isProxied of true. - -**Get Addresses for Caller** - - function getAddressesForCaller() external view returns (address nominator, address delivery, bool isProxied); - -Returns the Nominator, Proxy, Delivery and a boolean isProxied for msg.sender. If msg.sender is not a Proxy address it will return address(0) for the Nominator, Proxy and Delivery address and isProxied of false. If msg.sender is a Proxy address it will return the relvant addresses and isProxied of true. - -**Get Role** - - function getRole(address _roleAddress) external view returns (string memory currentRole); - -Returns a string value with a role for the passed address. Possible roles are: - -None The address does not appear on the Register as either a Record or a Nomination. - -Nominator - Pending The address is the Nominator on a Nomination which has yet to be accepted by the nominated Proxy address. - -Nominator - Active The address is a Nominator on an active Proxy Record (i.e. the Nomination has been accepted). - -Proxy - Active The address is a Proxy on an active Proxy Record. - -**Get Role for Caller** - - function getRoleForCaller() external view returns (string memory currentRole); - -Returns a string value with a role for msg.sender. Possible roles are: - -None The msg.sender does not appear on the Register as either a Record or a Nomination. - -Nominator - Pending The msg.sender is the Nominator on a Nomination which has yet to be accepted by the nominated Proxy address. - -Nominator - Active The msg.sender is a Nominator on an active Proxy Record (i.e. the Nomination has been accepted). - -Proxy - Active The msg.sender is a Proxy on an active Proxy Record. - -**Make Nomination** - - function makeNomination(address _proxy, uint256 _provider) external payable; - -Can be passed a Proxy address to create a Nomination for the msg.sender. - -Provider is a required argument. If you do not have a Provider ID you can pass 0 as the default EPS provider. For details on the EPS Provider Program please see . - -**Accept Nomination** - - function acceptNomination(address _nominator, address _delivery, uint256 _provider) external; - -Can be passed a Nominator and Delivery address to accept a Nomination for a msg.sender. Note that to accept a Nomination the Nomination needs to exists with the msg.sender as the Proxy. The Nominator passed to the function and that on the Nomination must match. - -Provider is a required argument. If you do not have a Provider ID you can pass 0 as the default EPS provider. For details on the EPS Provider Program please see . - -**Update Delivery Record** - - function updateDeliveryAddress(address _delivery, uint256 _provider) external; - -Can be passed a new Delivery address where the msg.sender is the Proxy on a Proxy Record. - -Provider is a required argument. If you do not have a Provider ID you can pass 0 as the default EPS provider. For details on the EPS Provider Program please see . - -**Delete Record by Nominator** - - function deleteRecordByNominator(uint256 _provider) external; - -Can be called to delete a Record and Nomination when the msg.sender is a Nominator. - -Note that when both a Record and Nomination exist both are deleted. If no Record exists (i.e. the Nomination hasn't been accepted by the Proxy address) the Nomination is deleted. - -Provider is a required argument. If you do not have a Provider ID you can pass 0 as the default EPS provider. For details on the EPS Provider Program please see . - -**Delete Record by Proxy** - - function deleteRecordByProxy(uint256 _provider) external; - -Can be called to delete a Record and Nomination when the msg.sender is a Proxy. - -## Rationale - -The rationale for this EIP was to provide a way for all existing and future Ethereum assets to be have a 'beneficial owner' (the proxy) that is different to the address custodying the asset. The use of a register to achieve this ensures that changes to existing tokens are not required. The register stores a trustless proof, signed by both the nominator and proxy, that can be relied upon as a true representation of asset ownership. - -## Backwards Compatibility - -The EIP is fully backwards compatible. - -## Test Cases - -The full SDLC for this proposal has been completed and it is operation at 0xfa3D2d059E9c0d348dB185B32581ded8E8243924 on mainnet, ropsten and rinkeby. The contract source code is validated and available on etherscan. The full unit test suite is available in `../assets/eip-4886/`, as is the source code and example implementations. - -## Reference Implementation - -Please see `../assets/eip-4886/contracts` - -## Security Considerations - -The core intention of the EIP is to improve user security by better safeguarding assets and allowing greater use of cold wallet storage. - -Potential negative security implications have been considered and none are envisaged. The proxy record can only become operational when a nomination has been confirmed by a proxy address, both addresses therefore having provided signed proof. - -From a usability perspective the key risk is in users specifying the incorrect asset delivery address, though it is noted that this burden of accuracy is no different to that currently on the network. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4886.md diff --git a/EIPS/eip-4895.md b/EIPS/eip-4895.md index 0966bbc3ff9212..81af3b60b632bc 100644 --- a/EIPS/eip-4895.md +++ b/EIPS/eip-4895.md @@ -4,7 +4,7 @@ title: Beacon chain push withdrawals as operations description: Support validator withdrawals from the beacon chain to the EVM via a new "system-level" operation type. author: Alex Stokes (@ralexstokes), Danny Ryan (@djrtwo) discussions-to: https://ethereum-magicians.org/t/eip-4895-beacon-chain-withdrawals-as-system-level-operations/8568 -status: Review +status: Final type: Standards Track category: Core created: 2022-03-10 @@ -31,7 +31,7 @@ Moreover, this approach is more complex than "pull"-based alternatives with resp | constants | value | units |--- |--- |--- -| `FORK_TIMESTAMP` | TBD | +| `FORK_TIMESTAMP` | 1681338455 | Beginning with the execution timestamp `FORK_TIMESTAMP`, execution clients **MUST** introduce the following extensions to payload validation and processing: diff --git a/EIPS/eip-4906.md b/EIPS/eip-4906.md index 93e6492058a451..8cd9b57407120c 100644 --- a/EIPS/eip-4906.md +++ b/EIPS/eip-4906.md @@ -1,93 +1,7 @@ --- eip: 4906 -title: EIP-721 Metadata Update Extension -description: Add a MetadataUpdate event to EIP-721. -author: Anders (@0xanders), Lance (@LanceSnow), Shrug , Nathan -discussions-to: https://ethereum-magicians.org/t/eip4906-erc-721-erc-1155-metadata-update-extension/8588 -status: Final -type: Standards Track category: ERC -created: 2022-03-13 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It adds a `MetadataUpdate` event to EIP-721 tokens. - -## Motivation - -Many [EIP-721](./eip-721.md) contracts emit an event when one of its tokens' metadata are changed. While tracking changes based on these different events is possible, it is an extra effort for third-party platforms, such as an NFT marketplace, to build individualized solutions for each NFT collection. - -Having a standard `MetadataUpdate` event will make it easy for third-party platforms to timely update the metadata of many NFTs. - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -The **metadata update extension** is OPTIONAL for EIP-721 contracts. - - -```solidity -/// @title EIP-721 Metadata Update Extension -interface IERC4906 is IERC165, IERC721 { - /// @dev This event emits when the metadata of a token is changed. - /// So that the third-party platforms such as NFT market could - /// timely update the images and related attributes of the NFT. - event MetadataUpdate(uint256 _tokenId); - - /// @dev This event emits when the metadata of a range of tokens is changed. - /// So that the third-party platforms such as NFT market could - /// timely update the images and related attributes of the NFTs. - event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId); -} -``` - -The `MetadataUpdate` or `BatchMetadataUpdate` event MUST be emitted when the JSON metadata of a token, or a consecutive range of tokens, is changed. - -Not emitting `MetadataUpdate` event is RECOMMENDED when a token is minted. - -Not emitting `MetadataUpdate` event is RECOMMENDED when a token is burned. - -Not emitting `MetadataUpdate` event is RECOMMENDED when the tokenURI changes but the JSON metadata does not. - -The `supportsInterface` method MUST return `true` when called with `0x49064906`. - -## Rationale - -Different NFTs have different metadata, and metadata generally has multiple fields. `bytes data` could be used to represents the modified value of metadata. It is difficult for third-party platforms to identify various types of `bytes data`, so as to avoid unnecessary complexity, arbitrary metadata is not included in the `MetadataUpdate` event. - -After capturing the `MetadataUpdate` event, a third party can update the metadata with information returned from the `tokenURI(uint256 _tokenId)` of EIP-721. When a range of token ids is specified, the third party can query each token URI individually. - -## Backwards Compatibility - -No backwards compatibility issues were found - -## Reference Implementation - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./IERC4906.sol"; - -contract ERC4906 is ERC721, IERC4906 { - - constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) { - } - - /// @dev See {IERC165-supportsInterface}. - function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { - return interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations - -If there is an off-chain modification of metadata, a method that triggers `MetadataUpdate` can be added, but ensure that the function's permission controls are correct. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4906.md diff --git a/EIPS/eip-4907.md b/EIPS/eip-4907.md old mode 100755 new mode 100644 index ed02d6cc76169a..59a08349daa26a --- a/EIPS/eip-4907.md +++ b/EIPS/eip-4907.md @@ -1,249 +1,7 @@ --- eip: 4907 -title: Rental NFT, an Extension of EIP-721 -description: Add a time-limited role with restricted permissions to EIP-721 tokens. -author: Anders (@0xanders), Lance (@LanceSnow), Shrug -discussions-to: https://ethereum-magicians.org/t/idea-erc-721-user-and-expires-extension/8572 -status: Final -type: Standards Track category: ERC -created: 2022-03-11 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes an additional role (`user`) which can be granted to addresses, and a time where the role is automatically revoked (`expires`). The `user` role represents permission to "use" the NFT, but not the ability to transfer it or set users. - -## Motivation - -Some NFTs have certain utilities. For example, virtual land can be "used" to build scenes, and NFTs representing game assets can be "used" in-game. In some cases, the owner and user may not always be the same. There may be an owner of the NFT that rents it out to a “user”. The actions that a “user” should be able to take with an NFT would be different from the “owner” (for instance, “users” usually shouldn’t be able to sell ownership of the NFT).  In these situations, it makes sense to have separate roles that identify whether an address represents an “owner” or a “user” and manage permissions to perform actions accordingly. - -Some projects already use this design scheme under different names such as “operator” or “controller” but as it becomes more and more prevalent, we need a unified standard to facilitate collaboration amongst all applications. - -Furthermore, applications of this model (such as renting) often demand that user addresses have only temporary access to using the NFT. Normally, this means the owner needs to submit two on-chain transactions, one to list a new address as the new user role at the start of the duration and one to reclaim the user role at the end. This is inefficient in both labor and gas and so an “expires” function is introduced that would facilitate the automatic end of a usage term without the need of a second transaction. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Contract Interface -Solidity Interface with NatSpec & OpenZeppelin v4 Interfaces (also available at [`IERC4907.sol`](../assets/eip-4907/contracts/IERC4907.sol)): - -```solidity -interface IERC4907 { - - // Logged when the user of an NFT is changed or expires is changed - /// @notice Emitted when the `user` of an NFT or the `expires` of the `user` is changed - /// The zero address for user indicates that there is no user address - event UpdateUser(uint256 indexed tokenId, address indexed user, uint64 expires); - - /// @notice set the user and expires of an NFT - /// @dev The zero address indicates there is no user - /// Throws if `tokenId` is not valid NFT - /// @param user The new user of the NFT - /// @param expires UNIX timestamp, The new user could use the NFT before expires - function setUser(uint256 tokenId, address user, uint64 expires) external; - - /// @notice Get the user address of an NFT - /// @dev The zero address indicates that there is no user or the user is expired - /// @param tokenId The NFT to get the user address for - /// @return The user address for this NFT - function userOf(uint256 tokenId) external view returns(address); - - /// @notice Get the user expires of an NFT - /// @dev The zero value indicates that there is no user - /// @param tokenId The NFT to get the user expires for - /// @return The user expires for this NFT - function userExpires(uint256 tokenId) external view returns(uint256); -} -``` - -The `userOf(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `userExpires(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `setUser(uint256 tokenId, address user, uint64 expires)` function MAY be implemented as `public` or `external`. - -The `UpdateUser` event MUST be emitted when a user address is changed or the user expires is changed. - -The `supportsInterface` method MUST return `true` when called with `0xad092b5c`. - -## Rationale - -This model is intended to facilitate easy implementation. Here are some of the problems that are solved by this standard: - -### Clear Rights Assignment - -With Dual “owner” and “user” roles, it becomes significantly easier to manage what lenders and borrowers can and cannot do with the NFT (in other words, their rights). Additionally, owners can control who the user is and it’s easy for other projects to assign their own rights to either the owners or the users. - -### Simple On-chain Time Management - -Once a rental period is over, the user role needs to be reset and the “user” has to lose access to the right to use the NFT. This is usually accomplished with a second on-chain transaction but that is gas inefficient and can lead to complications because it’s imprecise. With the `expires` function, there is no need for another transaction because the “user” is invalidated automatically after the duration is over. - -### Easy Third-Party Integration - -In the spirit of permission less interoperability, this standard makes it easier for third-party protocols to manage NFT usage rights without permission from the NFT issuer or the NFT application. Once a project has adopted the additional `user` role and `expires`, any other project can directly interact with these features and implement their own type of transaction. For example, a PFP NFT using this standard can be integrated into both a rental platform where users can rent the NFT for 30 days AND, at the same time, a mortgage platform where users can use the NFT while eventually buying ownership of the NFT with installment payments. This would all be done without needing the permission of the original PFP project. - -## Backwards Compatibility - -As mentioned in the specifications section, this standard can be fully EIP-721 compatible by adding an extension function set. - -In addition, new functions introduced in this standard have many similarities with the existing functions in EIP-721. This allows developers to easily adopt the standard quickly. - -## Test Cases - -### Test Contract -`ERC4907Demo` Implementation: [`ERC4907Demo.sol`](../assets/eip-4907/contracts/ERC4907Demo.sol) - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "./ERC4907.sol"; - -contract ERC4907Demo is ERC4907 { - - constructor(string memory name, string memory symbol) - ERC4907(name,symbol) - { - } - - function mint(uint256 tokenId, address to) public { - _mint(to, tokenId); - } - -} -``` - -### Test Code -[test.js](../assets/eip-4907/test/test.js) - -```JavaScript -const { assert } = require("chai"); - -const ERC4907Demo = artifacts.require("ERC4907Demo"); - -contract("test", async accounts => { - - it("should set user to Bob", async () => { - // Get initial balances of first and second account. - const Alice = accounts[0]; - const Bob = accounts[1]; - - const instance = await ERC4907Demo.deployed("T", "T"); - const demo = instance; - - await demo.mint(1, Alice); - let expires = Math.floor(new Date().getTime()/1000) + 1000; - await demo.setUser(1, Bob, BigInt(expires)); - - let user_1 = await demo.userOf(1); - - assert.equal( - user_1, - Bob, - "User of NFT 1 should be Bob" - ); - - let owner_1 = await demo.ownerOf(1); - assert.equal( - owner_1, - Alice , - "Owner of NFT 1 should be Alice" - ); - }); -}); - - -``` - -run in Terminal: -``` -truffle test ./test/test.js -``` - -## Reference Implementation -Implementation: [`ERC4907.sol`](../assets/eip-4907/contracts/ERC4907.sol) -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./IERC4907.sol"; - -contract ERC4907 is ERC721, IERC4907 { - struct UserInfo - { - address user; // address of user role - uint64 expires; // unix timestamp, user expires - } - - mapping (uint256 => UserInfo) internal _users; - - constructor(string memory name_, string memory symbol_) - ERC721(name_, symbol_) - { - } - - /// @notice set the user and expires of an NFT - /// @dev The zero address indicates there is no user - /// Throws if `tokenId` is not valid NFT - /// @param user The new user of the NFT - /// @param expires UNIX timestamp, The new user could use the NFT before expires - function setUser(uint256 tokenId, address user, uint64 expires) public virtual{ - require(_isApprovedOrOwner(msg.sender, tokenId), "ERC4907: transfer caller is not owner nor approved"); - UserInfo storage info = _users[tokenId]; - info.user = user; - info.expires = expires; - emit UpdateUser(tokenId, user, expires); - } - - /// @notice Get the user address of an NFT - /// @dev The zero address indicates that there is no user or the user is expired - /// @param tokenId The NFT to get the user address for - /// @return The user address for this NFT - function userOf(uint256 tokenId) public view virtual returns(address){ - if( uint256(_users[tokenId].expires) >= block.timestamp){ - return _users[tokenId].user; - } - else{ - return address(0); - } - } - - /// @notice Get the user expires of an NFT - /// @dev The zero value indicates that there is no user - /// @param tokenId The NFT to get the user expires for - /// @return The user expires for this NFT - function userExpires(uint256 tokenId) public view virtual returns(uint256){ - return _users[tokenId].expires; - } - - /// @dev See {IERC165-supportsInterface}. - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC4907).interfaceId || super.supportsInterface(interfaceId); - } - - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override{ - super._beforeTokenTransfer(from, to, tokenId); - - if (from != to && _users[tokenId].user != address(0)) { - delete _users[tokenId]; - emit UpdateUser(tokenId, address(0), 0); - } - } -} -``` - -## Security Considerations - -This EIP standard can completely protect the rights of the owner, the owner can change the NFT user and expires at any time. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4907.md diff --git a/EIPS/eip-4910.md b/EIPS/eip-4910.md index b453799c9b7eb9..df0a7cb9a97ff1 100644 --- a/EIPS/eip-4910.md +++ b/EIPS/eip-4910.md @@ -1,693 +1,7 @@ --- eip: 4910 -title: Royalty Bearing NFTs -description: Extension of EIP-721 to correctly define, process, and pay (hierarchical) onchain NFT royalties. -author: Andreas Freund (@Therecanbeonlyone1969) -discussions-to: https://ethereum-magicians.org/t/royalty-bearing-nfts/8453 -status: Review -type: Standards Track category: ERC -created: 2022-03-14 -requires: 165, 721 +status: Moved --- -## Abstract -The proposal directly connects NFTs and royalties in a smart contract architecture extending the [EIP-721](./eip-721.md) standard, with the aim of precluding central authorities from manipulating or circumventing payments to those who are legally entitled to them. - -The proposal builds upon the OpenZeppelin Smart Contract Toolbox architecture, and extends it to include royalty account management (CRUD), royalty balance and payments management, simple trading capabilities -- Listing/De-Listing/Buying -- and capabilities to trace trading on exchanges. The royalty management capabilities allow for hierarchical royalty structures, referred to herein as royalty trees, to be established by logically connecting a "parent" NFT to its "children", and recursively enabling NFT "children" to have more children. - -## Motivation -The management of royalties is an age-old problem characterized by complex contracts, opaque management, plenty of cheating and fraud. - -The above is especially true for a hierarchy of royalties, where one or more assets is derived from an original asset such as a print from an original painting, or a song is used in the creation of another song, or distribution rights and compensation are managed through a series of affiliates. - -In the example below, the artist who created the original is eligible to receive proceeds from every sale, and resale, of a print. - -![Fig1](../assets/eip-4910/eip-4910-print-families.png) - -The basic concept for hierarchical royalties utilizing the above "ancestry concept" is demonstrated in the figure below. - -![Fig2](../assets/eip-4910/eip-4910-royalties.png) - - -In order to solve for the complicated inheritance problem, this proposal breaks down the recursive problem of the hierarchy tree of depth N into N separate problems, one for each layer. This allows us to traverse the tree from its lowest level upwards to its root most efficiently. - -This affords creators, and the distributors of art derived from the original, the opportunity to achieve passive income from the creative process, enhancing the value of an NFT, since it now not only has intrinsic value but also comes with an attached cash flow. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Outline - -This proposal introduces several new concepts as extensions to the EIP-721 standard that warrant explanation: -* **Royalty Account (RA)** - * A Royalty Account is attached to each NFT through its `tokenId` and consists of several sub-accounts which can be accounts of individuals or other RAs. A Royalty Account is identified by an account identifier. -* **Account Type** - * This specifies if an RA Sub Account belongs to an individual (user) or is another RA. If there is another RA as an RA Sub Account, the allocated balance needs to be reallocated to the Sub Accounts making up the referenced RA. -* **Royalty Split** - * The percentage each Sub Account receives based on a sale of an NFT that is associated with an RA -* **Royalty Balance** - * The royalty balance associated with an RA -* **Sub Account Royalty Balance** - * The royalty balance associated to each RA Sub Account. Note that only individual accounts can carry a balance that can be paid out. That means that if an RA Sub Account is an RA, its final Sub Account balance must be zero, since all RA balances must be allocated to individual accounts. -* **Token Type** - * Token Type is given as either ETH or the symbol of the supported utility tokens such as `DAI` -* **Asset ID** - * This is the `tokenId` the RA belongs to. -* **Parent** - * This indicates which `tokenId` is the immediate parent of the `tokenId` to which an RA belongs. - -Below a non-normative overview is given of the data structures and functionality that are covered by the requirements in this document. - -#### Data Structures - -In order to create an interconnected data structure linking NFTs to RAs certain global data structures are required: - -* A Royalty Account and associated Royalty Sub Accounts to establish the concept of a Royalty Account with sub accounts. -* Connecting a `tokenId` to a Royalty Account identifier. -* A structure mapping parent-to-child NFT relationships. -* A listing of token types and last validated balance (for trading and royalty payment purposes) -* A listing of registered payments to be made in the `executePayment` function and validated in `safeTransferFrom`. This is sufficient, because a payment once received and distributed in the `safeTransferFrom` function will be removed from the listing. -* A listing of NFTs to be sold - -#### Royalty Account Functions - -Definitions and interfaces for the Royalty Account RUD (Read-Update-Delete) functions. Because the RA is created in the minting function, there is no need to have a function to create a royalty account separately. - -#### Minting of a Royalty Bearing NFT - -When an NFT is minted, an RA must be created and associated with the NFT and the NFT owner, and, if there is an ancestor, with the ancestor's RA. To this end the specification utilizes the `_safemint` function in a newly defined `mint` function and applies various business rules on the input variables. - -#### Listing NFTs for Sale and removing a Listing - -Authorized user addresses can list NFTs for sale for non-exchange mediated NFT purchases. - -#### Payment Function from Buyer to Seller - -To avoid royalty circumvention, a buyer will always pay the NFT contract directly and not the seller. The seller is paid through the royalty distribution and can later request a payout. - -The payment process depends on whether the payment is received in ETH or an [EIP-20](./eip-20.md) token: -* EIP-20 Token - 1. The Buyer must `approve` the NFT contract for the purchase price, `payment` for the selected payment token (EIP-20 contract address). - 2. For an EIP-20 payment token, the Buyer must then call the `executePayment` in the NFT contract -- the EIP-20 is not directly involved. -* For a non-EIP-20 payment, the Buyer must send a protocol token (ETH) to the NFT contract, and is required to send `msg.data` encoded as an array of purchased NFTs `uint256[] tokenId`. - -#### Modified NFT Transfer Function including required Trade data to allocate Royalties - -The input parameters must satisfy several requirements for the NFT to be transferred AFTER the royalties have been properly distributed. Furthermore, the ability to transfer more than one token at a time is also considered. - -The proposal defines: -* Input parameter validation -* Payment Parameter Validation -* Distributing Royalties -* Update Royalty Account ownership with payout -* Transferring Ownership of the NFT -* Removing the Payment entry in `registeredPayment` after successful transfer - -Lastly, the approach to distributing royalties is to break down the hierarchical structure of interconnected Royalty Accounts into layers and then process one layer at time, where each relationship between a token and its ancestor is utilized to traverse the Royalty Account chain until the root ancestor and associated RA is reached. - -#### Paying out Royalties to the NFT Owner -- `from` address in `safeTransferFrom` Function - -This is the final part of the proposal. - -There are two versions of the payout function -- a `public` function and an `internal` function. - -The public function has the following interface: -``` -function royaltyPayOut (uint256 tokenId, address RAsubaccount, address payable payoutAccount, uint256 amount) public virtual nonReentrant returns (bool) -``` -where we only need the `tokenId`, the RA Sub Account address, `_RAsubaccount` which is the `owner`, and the amount to be paid out, `_amount`. Note that the function has `nonReentrant` modifier protection, because funds are being payed out. - -To finally send a Payout payment, the following steps need to be taken: -* find the RA Sub Account based on `RAaccount` and the `subaccountPos` and extract the balance -* extract `tokenType` from the Sub Account -* based on the token type, send the payout payment (not exceeding the available balance) - -### Data Structures - -#### Royalty Account and Royalty Sub Accounts - -In order to create an interconnected data structure linking NFTs to RAs that is search optimized requires to make the following additions to the global data structures of an EIP-721. - -Note, a Royalty Account is defined as a collection of Royalty Sub Accounts linked to a meta account. This meta account is comprised of general account identifiers particular to the NFT it is linked to such as asset identifier, parent identifier etc. - -**[R1]** *One or more Royalty Sub-Account MUST be linked to a Royalty Account.* - -**[R2]** *The account identifier of a Royalty Account, `raAccountId`, MUST be unique.* - -**[R3]** *The `tokenId` of a NFT MUST be linked to a `raAccountID` in order to connect an `raAccountId` to a `tokenId`.* - - -#### Print (Child) NFTs - -The set of requirement to manage Parent-Child NFT Relationships and constraints at each level of the NFT (family) tree e.g. number of children permitted, NFT parents have to be linked to their immediate NFT children are as follows. - -**[R4]** *There MUST be a link for direct parent-child relationships* - -#### NFT Payment Tokens - -In order to capture royalties, an NFT contract must be involved in NFT trading. Therefore, the NFT contract needs to be aware of NFT payments, which in turn requires the NFT contract to be aware which tokens can be used for trading. - -**[R5]** *There MUST be a listing of supported token types* - -Since the NFT contract is managing royalty distributions and payouts as well as sales, it needs to track the last available balances of the allowed token types owned by the contract. - -**[R6]** *There MUST be a link of the last validated balance of an allowed token type in the contract to the respective allowed token contract.* - -#### NFT Listings and Payments - -Since the contract is directly involved in the sales process, a capability to list one or more NFTs for sale is required. - -**[R7]** *There MUST be a list of NFTs for sale.* - -**[R8]** *A sales listing MUST have a unique identifier.* - -Besides listings, the contract is required to manage sales as well. This requires the capability to register a payment, either for immediate execution or for later payment such as in an auction situation. - -**[R9]** *There MUST be a listing for registered payments* - -**[R10]** *A registered payment MUST have a unique identifier.* - -#### Contract Constructor and Global Variables and their update functions - -This standard extends the current EIP-721 constructor, and adds several global variables to recognize the special role of the creator of an NFT, and the fact that the contract is now directly involved in managing sales and royalties. - -**[R11]** *The minimal contract constructor MUST contain the following input elements.* - -``` -/// -/// @dev Definition of the contract constructor -/// -/// @param name as in EIP-721 -/// @param symbol as in EIP-721 -/// @param baseTokenURI as in EIP-721 -/// @param allowedTokenTypes is the array of allowed tokens for payment - -constructor( - string memory name, - string memory symbol, - string memory baseTokenURI, - address[] memory allowedTokenTypes - ) EIP-721(name, symbol) {...} -``` - - -### Royalty Account Management - -Below are the definitions and interfaces for the Royalty Account RUD (Read-Update-Delete) functions. Since a Royalty Account is created in the NFT minting function, there is no need to have a separate function to create a royalty account. - -#### Get a Royalty Account - -There is only one get function required because a Royalty Account and its sub accounts can be retrieved through the `tokenId` in the `ancestry` field of the Royalty Account. - -**[R12]** *The `getRoyaltyAccount` function interface MUST adhere to the definition below:* -``` -/// @dev Function to fetch a Royalty Account for a given tokenId -/// @param tokenId is the identifier of the NFT to which a Royalty Account is attached -/// @param RoyaltyAccount is a data structure containing the royalty account information -/// @param RASubAccount[] is an array of data structures containing the information of the royalty sub accounts associated with the royalty account - -function getRoyaltyAccount (uint256 tokenId) public view virtual returns (address, - RoyaltyAccount memory, - RASubAccount[] memory); -``` - - -**[R13]** *The following business rules MUST be enforced in the `getRoyaltyAccount` function:* -* *`tokenId` exists and is not burned* - -#### Update a Royalty Account - -In order to update a Royalty Account, the caller must have both the 'tokenId' and the `RoyaltyAccount` itself which can be obtained from the Royalty Account getter function. - - -**[R14]** *The `updateRoyaltyAccount` function interface MUST adhere to the definition below:* -``` -/// @dev Function to update a Royalty Account and its Sub Accounts -/// @param tokenId is the identifier of the NFT to which the Royalty Account to be updated is attached -/// @param RoyaltyAccount is the Royalty Account and associated Royalty Sub Accounts with updated values - -function updateRoyaltyAccount (uint256 _tokenId, `RoyaltyAccount memory _raAccount) public virtual returns (bool) -``` - -The update functionality of a Royalty Account, while straightforward, is also highly nuanced. To avoid complicated change control rules such as multi-signature rules, Royalty Account changes are kept simple. - -**[R15]** *The business rules for the update function are as follows:* -1. *An NFTs asset identifier MUST NOT be changed.* -2. *An NFTs ancestor MUST NOT be updated.* -3. *An NFTs token type accepted for payment MUST NOT be updated.* -4. *The royalty balance in a Royalty Sub Account MUST NOT be changed.* -5. *The royalty split inherited by the children from the NFT parent MUST NOT be changed.* -6. *New royalty split values MUST be larger than, or less than, or equal to any established boundary value for royalty splits, if it exists.* -7. *The number of existing Royalty Sub Account plus the number of new Royalty Sub Accounts to be added MUST be smaller or equal to an established boundary value, if it exists.* -8. *The sum of all royalty splits across all existing and new Royalty Sub Accounts MUST equal to 1 or its equivalent numerical value at all times.* -9. *'msg.sender` MUST be equal to an account identifier in the Royalty Sub Account of the Royalty Account to be modified and that royalty sub account must be identified as not belonging to the parent NFT* - - 9.1 *the Sub Account belonging to the account identifier MUST NOT be removed* - - 9.2 * A royalty split MUST only be decreased, and either the existing sub account's royalty split MUST be increased accordingly such that the sum of all royalty splits remains equal to 1 or its numerical equivalent, or one or more new Royalty Sub Accounts MUST be added according to rule 10.* - - 9.3 * a royalty balance MUST NOT be changed* - - 9.4 * an account identifier MUST NOT be NULL* - -10. *If `msg.sender` is equal to the account identifier of one of the Sub Account owners which is not the parent NFT, an additional Royalty Sub Accounts MAY be added* - - 10.1 *if the royalty split of the Royalty Sub Account belonging to `msg.sender` is reduced* - - 10.1.1 *then the royalty balance in each new Royalty Sub Account MUST be zero* - - 10.1.2 *the sum of the new royalty splits data MUST be equal to the royalty split of the Royalty Sub Account of `msg.sender` before it was modified* - - 10.2 *new account identifier MUST not be NULL* - -11. *If the Royalty Account update is correct, the function returns `true`, otherwise `false`.* - -#### Deleting a Royalty Account - -While sometimes deleting a Royalty Account is necessary, even convenient, it is a very costly function in terms of gas, and should not be used unless one is absolutely sure that the conditions enumerated below are met. - -**[R16]** *The `deleteRoyaltyAccount` function interface MUST adhere to the definition below:* -``` -/// @dev Function to delete a Royalty Account -/// @param tokenId is the identifier of the NFT to which the Royalty Account to be updated is attached - -function deleteRoyaltyAccount (uint256 _tokenId) public virtual returns (bool) -``` - -**[R17]** *The business rules for this function are as follows:* -* *`_tokenId` MUST be burned, i.e., have owner `address(0)`.* -* *all `tokenId` numbers genealogically related to `_tokenId` either as ancestors or offspring MUST also be burnt.* -* *all balances in the Royalty Sub Accounts MUST be zero.* - -### NFT Minting - -In extension to the EIP-721 minting capability, a Royalty Account with Royalty Sub Accounts are required to be added during the minting, besides establishing the NFT token specific data structures supporting constraints such as the maximum number of children an NFT can have. - -**[R18]** *When a new NFT is minted a Royalty Account with one or more Royalty Sub Accounts MUST be created and associated with the NFT and the NFT owner, and, if there is an ancestor, with the ancestor's Royalty Account.* - -To this end the specification utilizes the EIP-721 `_safemint` function in a newly defined `mint` function, and applies various business rules on the function's input variables. - -**[D1]** *Note, that the `mint` function SHOULD have the ability to mint more than one NFT at a time.* - -**[R19]** *Also, note that the `owner` of a new NFT MUST be the NFT contract itself.* - -**[R20]** *The non-contract owner of the NFT MUST be set as `isApproved` which allows the non-contract owner to operate just like the `owner`.* - -This strange choice in the two requirements above is necessary, because the NFT contract functions as an escrow for payments and royalties, and, hence, needs to be able to track payments received from buyers and royalties due to recipients, and to associate them with a valid `tokenId`. - -**[R21]** *For compactness of the input, and since the token meta data might vary from token to token the MUST be a minimal data structure containing:* -``` -/// @param parent is the parent tokenId of the (child) token, and if set to 0 then there is no parent. -/// @param canBeParent indicates if a tokenId can have children or not. -/// @param maxChildren defines how many children an NFT can have. -/// @param royaltySplitForItsChildren is the royalty percentage split that a child has to pay to its parent. -/// @param uri is the unique token URI of the NFT -``` - -**[R22]** *The `mint` function interface MUST adhere to the definition below:* -``` -/// @dev Function creates one or more new NFTs with its relevant meta data necessary for royalties, and a Royalty Account with its associated met data for `to` address. The tokenId(s) will be automatically assigned (and available on the emitted {IEIP-721-Transfer} event). -/// @param to is the address to which the NFT(s) are minted -/// @param nfttoken is an array of struct type NFTToken for the meta data of the minted NFT(s) -/// @param tokenType is the type of allowed payment token for the NFT - -function mint(address to, NFTToken[] memory nfttoken, address tokenType) public virtual -``` - -**[R23]** *The following business rules for the `mint` function's input data MUST be fulfilled:* -- *The number of tokens to be minted MUST NOT be zero.* -- *`msg.sender` MUST have either the `MINTER_ROLE` or the `CREATOR_Role` identifying the creator of the first NFT.* -- *`to` address MUST NOT be the zero address.* -- *`to` address MUST NOT be a contract, unless it has been whitelisted -- see [Security Considerations](#security-considerations) for more details.* -- *`tokenType` MUST be a token type supported by the contract.* -- *`royaltySplitForItsChildren` MUST be less or equal to 100% or numerical equivalent thereof less any constraints such as platform fees* -- *If the new NFT(s) cannot have children, `royaltySplitForItsChildren` MUST be zero.* -- *If the new NFT(s) has a parent, the parent NFT `tokenId` MUST exist.* -- *The ancestry level of the parent MUST be less than the maximum number of allowed NFT generations, if specified.* -- *The number of allowed children for an NFT to be minted MUST be less than the maximum number of allowed children, if specified.* - -### Listing and De-Listing of NFTs for Direct Sales - -In the sales process, we need to minimally distinguish two types of transactions -- Exchange-mediated sales -- Direct sales - -The first type of transaction does not require that the smart contract is aware of a sales listing since the exchange contract will trigger payment and transfer transactions directly with the NFT contract as the owner. However, for the latter transaction type it is essential, since direct sales are required to be mediated at every step by the smart contract. - -**[R24]** *For direct sales, NFT listing, und de-listing, transactions MUST be executed through the NFT smart contract.* - -Exchange-mediated sales will be discussed when this document discusses payments. - -In direct sales, authorized user addresses can list NFTs for sale, see the business rules below. - -**[R25]** *The `listNFT` function interface MUST adhere to the definition below:* -``` -/// @dev Function to list one or more NFTs for direct sales -/// @param tokenIds is the array of tokenIds to be included in the listing -/// @param price is the price set by the owner for the listed NFT(s) -/// @param tokenType is the payment token type allowed for the listing - -function listNFT (uint256[] calldata tokenIds, uint256 price, address tokenType) public virtual returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -**[R26]** *The business rules of the `listNFT` function are as follows:* -- there MUST NOT already be a listing for one or more NFTs in the `listedNFT` mapping of the proposed listing. -- `seller` MUST be equal to `getApproved(tokenId[i])` for all NFTs in the proposed listing. -- `tokenType` MUST be supported by the smart contract. -- `price` MUST be larger than `0`. - -**[R27]** *If the conditions in [**[R26]**](#r26) are met, then the NFT sales list MUST be updated.* - -Authorized user addresses can also remove a direct sale listing of NFTs. - -**[R28]** *The `removeNFTListing` function interface MUST adhere to the definition below:* -``` -/// @dev Function to de-list one or more NFTs for direct sales -/// @param listingId is the identifier of the NFT listing - -function removeNFTListing (uint256 listingId) public virtual returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -**[R29]** *The business rules of the `removeNFTListing` function below MUST be adhered to:* -- * the registered payment entry MUST be NULL* -- *`msg.sender = getApproved(tokenId)` for the NFT listing* - -**[R30]** *If the conditions in [**[R29]**](#r29) are met, then the NFT sales listing MUST be removed.* - -### Payments for NFT Sales - -As noted before, a buyer will always pay the NFT contract directly and not the seller. The seller is paid through the royalty distribution and can later request a payout to their wallet. - -**[R31]** *The payment process requires either one or two steps:* -1. *For an EIP-20 token* - - *The buyer MUST `approve` the NFT contract for the purchase price, `payment`, for the selected payment token type.* - - *The buyer MUST call the `executePayment` function.* -2. *For a protocol token* - - *The buyer MUST call a payment fallback function with `msg.data` not NULL.* - -**[R32]** *For an EIP-20 token type, the required `executePayment` function interface MUST adhere to the definition below*: -``` -/// @dev Function to make a NFT direct sales or exchange-mediate sales payment -/// @param receiver is the address of the receiver of the payment -/// @param seller is the address of the NFT seller -/// @param tokenIds are the tokenIds of the NFT to be bought -/// @param payment is the amount of that payment to be made -/// @param tokenType is the type of payment token -/// @param trxnType is the type of payment transaction -- minimally direct sales or exchange-mediated - -function executePayment (address receiver, address seller, uint 256[] tokenIds, uint256 payment, string tokenType, int256 trxnType) public virtual nonReentrant returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -**[R33]** *Independent of `trxnType`, the business rules for the input data are as follows:* -- *All purchased NFTs in the `tokenIds` array MUST exist and MUST NOT be burned.* -- *`tokenType` MUST be a supported token.* -- *`trxnType` MUST be set to either `0` (direct sale) or `1` (exchange-mediate sale), or another supported type.* -- *`receiver` MAY be NULL but MUST NOT be the Zero Address.* -- *`seller` MUST be the address in the corresponding listing.* -- *`msg.sender` MUST not be a contract, unless it is whitelisted in the NFT contract.* - -In the following, this document will only discuss the differences between the two minimally required transaction types. - -**[R34]** *For `trxnType = 0`, the payment data MUST to be validated against the listing, based on the following rules:* -- *NFT(s) MUST be listed* -- *`payment` MUST be larger or equal to the listing price.* -- *The listed NFT(s) MUST match the NFT(s) in the payment data.* -- *The listed NFT(s) MUST be controlled by `seller`.* - -**[R35]** *If all checks in [**[R33]**](#r33), and in [**[R34]**](#r34) for `trxnType = 0`, are passed, the `executePayment` function MUST call the `transfer` function in the EIP-20 contract identified by `tokenType` with `recipient = address(this)` and `amount = payment`.* - -Note the NFT contract pays itself from the available allowance set in the `approve` transaction from the buyer. - -**[R36]** *For `trxnType = 1`, and for a successful payment, the `registeredPayment` mapping MUST updated with the payment, such that it can be validated when the NFT is transferred in a separate `safeTransferFrom` call, and `true` MUST be returned as the return value of the function, if successful, `false` otherwise.* - -**[R37]** *For `trxnType = 0`, an `internal` version of the `safeTransferFrom` function with message data MUST be called to transfer the NFTs to the buyer, and upon success, the buyer MUST be given the `MINTER_ROLE`, unless the buyer already has that role.* - -Note, the `_safeTransferFrom` function has the same structure as `safeTransferFrom` but skips the input data validation. - -**[R38]** *For `trxnType = 0`, and if the NFT transfer is successful, the listing of the NFT MUST be removed.* - -**[R39]** *For a protocol token as a payment token, and independent of `trxnType`, the buyer MUST send protocol tokens to the NFT contract as the escrow, and `msg.data` MUST encode the array of paid for NFTs `uint256[] tokenIds`.* - -**[R40]** *For the NFT contract to receive a protocol token, a payable fallback function (`fallback() external payable`) MUST be implemented.* - -Note that since the information for which NFTs the payment was for must be passed, a simple `receive()` fallback function cannot be allowed since it does not allow for `msg.data` to be sent with the transaction. - -**[R41]** *`msg.data` for the fallback function MUST minimally contain the following data: -`address memory seller, uint256[] memory _tokenId, address memory receiver, int256 memory trxnType`* - -**[R42]** *If `trxnType` is not equal to either '0' or '1', or another supported type, then the fallback function MUST `revert`.* - -**[R43]** *For `trxnType` equal to either '0' or '1', the requirements [**[R33]**](#r33) through [**[R38]**](#r38) MUST be satisfied for the fallback function to successfully execute, otherwise the fallback function MUST `revert`.* - -**[R44]** *In case of a transaction failure (for direct sales, `trxnType = 0`), or the buyer of the NFT listing changing their mind (for exchange-mediated sales, `trxnType = 1`), the submitted payment MUST be able to revert using the `reversePayment` function where the function interface is defined below:* -``` -/// @dev Definition of the function enabling the reversal of a payment before the sale is complete -/// @param paymentId is the unique identifier for which a payment was made -/// @param tokenType is the type of payment token used in the payment -function reversePayment(uint256 paymentId, string memory tokenType) public virtual returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -Note, `reentrancy` protection through e.g. `nonReentrant` from the Open Zeppelin library is strongly advised since funds are being paid out. - -**[R45]** *The business rules for the `reversePayment` function are as follows:* -- *There MUST be registered payment for a given `paymentId` and `tokenType`.* -- *`msg.sender` MUST be the buyer address in the registered payment.* -- *The payment amount must be larger than `0`.* -- *The registered payment MUST be removed when the payment has been successfully reverted, otherwise the function must fail.* - - -### Modified NFT Transfer function - -This document adheres to the EIP-721 interface format for the `safeTransferFrom` function as given below: -``` -function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external virtual override -``` - -Note, that the input parameters must satisfy several requirements for the NFT(s) to be transferred AFTER royalties have been properly distributed. Note also, that the ability to transfer more than one token at a time is required. However, the standard interface only allows one token to be transferred at a time. In order to remain compliant with the EIP-721 standard, this document uses `tokenId` only for the first NFT to be transferred. All other transfer relevant data is encoded in `_data`. - -The high-level requirements are as follows: -* The payment parameters of the trade encoded in `_data` must be validated. -* The seller and the sold NFT token(s) must exist, and the seller must be the owner of the token. -* `msg.sender` must be the seller address or an approved address. -* the payment of the trade received by the NFT smart contract is correctly disbursed to all Royalty Sub Account owners. -* the NFT token is transferred after all Royalty Sub Accounts and their holders associated with the NFT token(s) have been properly credited. - -Also, note that in order to avoid royalty circumvention attacks, there is only one NFT transfer function. - -**[R46]** *Therefore, `transferFrom` and `safeTransferFrom` without `data` MUST be disabled.* - -This can be achieved through for example a `revert` statement in an `override` function. - -**[R47]** *The requirements on input parameters of the function are as follows*: -* *`from` MUST not be `address(0)`.* -* *`from` MUST be the owner or `approved` for `tokenId` and the other tokens included in `_data`.* -* *`from` MUST not be a smart contract unless whitelisted.* -* *a Royalty Account MUST be associated to `tokenId` and the other tokens included in `_data`.* -* *`_data` MUST NOT be NULL.* -* *`msg.sender` MUST be equal to `from` or an `approved` address, or a whitelisted contract.* - -Note, that in the context of this document only the scenario where the calling contract is still being created, i.e., the constructor being executed is a possible attack vector, and should to be carefully treated in the transfer scenario. - -Turning to the `_data` object. - -**[R48]** *The `_data` object MUST minimally contain the following payment parameters:* -* *Seller Address as `address`.* -* *Buyer Address as `address`.* -* *Receiver Address as `address.* -* *Token identifiers as `uint256[]`.* -* *Token type used for payment.* -* *Payment amount paid to NFT contract as `uint256`.* -* *a registered payment identifier.* -* *blockchain ID, `block.chainid`, of the underlying blockchain.* - -**[R49]** *The following business rules MUST be met for the payment data in '_data':* -* *`seller == from`.* -* *`tokenId[0] == tokenId`.* -* *Each token in `_tokenId` has an associated Royalty Account.* -* *`chainid == block.chainid`.* -* *`buyer` is equal to the buyer address in the registered payment for the given ``paymentId.* -* *`receiver == to`.* -* *the receiver of the token is not the seller.* -* *the receiver of the token is not a contract or is a whitelisted contract* -* *For all NFTs in the payment, `tokenId[i] = registeredPayment[paymentId].boughtTokens[i]`.* -* *`tokenType` is supported in the contract.* -* *`allowedToken[tokenType]` is not NULL.* -* *`tokenType = registeredPayment[paymentId].tokenType`.* -* *`payment > lastBalanceAllowedToken[allowedToken[listingId]]`.* -* *`payment = registeredPayment[paymentId].payment`.* - -### Distributing Royalties in the Transfer Function - -The approach to distributing royalties is to break down the hierarchical structure of interconnected Royalty Accounts into layers, and then process one layer at time, where each relationship between a NFT and its ancestor is utilized to traverse the Royalty Account chain until the root ancestor and its associated Royalty Account. - -Note, that the distribution function assumes that the payment made is for ALL tokens in the requested transfer. That means, that `payment` for the distribution function is equally divided between all NFTs included in the payment. - -**[R50]** *The `distributePayment` function interface MUST adhere to the definition below: -``` -/// @dev Function to distribute a payment as royalties to a chain of Royalty Accounts -/// @param tokenId is a tokenId included in the sale and used to look up the associated Royalty Account -/// @param payment is the payment (portion) to be distributed as royalties - -function distributePayment (uint256 tokenId, uint265 payment) internal virtual returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -As mentioned before, the internal `distributePayment` function is called within the modified `safeTransferFrom` function. - -Note, that it is necessary to multiply two `uint256` numbers with each other -- the payment amount with the royalty split percentage expressed as a whole number e.g. `10000 = 100%`. And then divide the result by the whole number representing `100%` in order to arrive at the correct application of the royalty split percentage to the payment amount. This requires careful treatment of numbers in the implementation to prevent issues such as buffer over or under runs. - -**[R51]** *The processing logic of `distributePayment` function MUST be as follows:* -* *Load the Royalty Account (`RA`) and associated Royalty Sub Accounts using the passed `tokenId`.* -* *For each Royalty Sub Account in `RA` apply the following rules:* - * *If a Royalty Sub Account in `RA` has `isIndividual` set to `true` then* - * *apply the royalty percentage of that Royalty Sub Account to `payment` and add the calculated amount, e.g. `royaltyAmountTemp`, to the `royaltybalance` of that Royalty Sub Account.* - * *emit an event as a notification of payment to the `accountId` of the Royalty Sub Account containing: assetId, accountId, tokenType, royaltybalance.* - * *in the RA add `royaltyamountTemp` amount to `balance`* - * *If a Royalty Sub Account in `RA` has `isIndividual` set to `false` then* - * *apply the royalty percentage of that Royalty Sub Account to `payment` and store temporarily in a new variable e.g. `RApaymenttemp`, but do not update the `royaltybalance` of the Royalty Sub Account which remains `0`.* - * *then use `ancestor` to obtain the `RA` connected to `ancestor` e.g. via a look up through a Royalty Account mapping.* - * *load the new RA* - * *if `isIndividual` of the Royalty Sub Account is set to `true`, pass through the Royalty Sub Accounts of the next `RA`, and apply the rule for `isIndividual = true`.* - * *if `isIndividual` of the Royalty Sub Account is set to `false`, pass through the Royalty Sub Accounts of the next `RA`, and apply the rule for `isIndividual = false`.* - * *Repeat the procedures for `isIndividual` equal to `true` and `false` until a `RA` is reached that does not have an `ancestor`, and where all Royalty Sub Accounts have`isIndividual` set to `true`, and apply the rule for a Royalty Sub Account that has `isIndividual` set to `true` to all Royalty Sub Accounts in that `RA`.* - -### Update Royalty Sub Account Ownership with Payout to approved Address (`from`) - -In order to simplify the ownership transfer, first the approved address -- the non-contract NFT owner --, `from`, is paid out its share of the royalties. And then the Royalty Sub Account is updated with the new owner, `to`. This step repeats for each token to be transferred. - -**[R52]** *The business rules are as follows:* -* *the internal version of the`royaltyPayOut` function MUST pay out the entire royalty balance of the Royalty Sub Account owned by the `from` address to the `from` address.* -* *the Royalty Sub Account MUST only be updated with the new owner only once the payout function has successfully completed and the `royaltybalance = 0`.* - -The last step in the process chain is transferring the NFTs in the purchase to the `to` address. - -**[R53]** *For every NFT (in the batch) the 'to' address MUST be `approved' (EIP-721 function) to complete the ownership transfer:* - -``` -_approve(to, tokenId[i]); -``` - -The technical NFT owner remains the NFT contract. - -### Removing the Payment Entry after successful Transfer - -Only after the real ownership of the NFT, the approved address, has been updated, the payment registry entry can be removed to allow the transferred NFTs to be sold again. - -**[R54]** *After the `approve` relationship has been successfully updated to the `to` address, the registered payment MUST be removed.* - -### Paying out Royalties to the `from` Address in `safeTransferFrom` Function - -There are two versions of the payout function -- a `public` and an `internal` function -- depending on whether there is a payout during a purchase, or a payout is requested by a Royalty Sub Account owner. - -**[R55]** *The public `royaltyPayOut` function interface MUST adhere to the definition below:* -``` -/// @dev Function to payout a royalty payment -/// @param tokenId is the identifier of the NFT token -/// @param RAsubaccount is the address of the Royalty Sub Account from which the payout should happen -/// @param receiver is the address to receive the payout -/// @param amount is the amount to be paid out - -function royaltyPayOut (uint256 tokenId, address RAsubaccount, address payable payoutAccount, uint256 amount) public virtual nonReentrant returns (bool) -``` -The Boolean return value is `true` for a successful function execution, and `false` for an unsuccessful function execution. - -Note, that the function has `reentrancy` protection through `nonReentrant` from the Open Zeppelin library since funds are being paid out. - -**[R56]** *The input parameters of the `royaltyPayOut` function MUST satisfy the following requirements:* -* *`msg.sender == RAsubaccount`.* -* *`tokenId` must exist and must not be burned.* -* *`tokenId` must be associated with a Royalty Account.* -* *`RAsubaccount` must be a valid `accountId` in a Royalty Sub Account of the Royalty Account of the `tokenId'.* -* *`isIndividual == true` for the Royalty Sub Account, `RAsubaccount`.* -* *`amount <= royaltybalance` of the Royalty Sub Account, `RAsubaccount.*` - -**[R57]** *The internal `_royaltyPayOut` function interface MUST adhere to the definition below*: -``` -function _royaltyPayOut (uint256 tokenId, address RAsubaccount, address payable payoutAccount, uint256 amount) public virtual returns (bool) -``` - -**[R58]** *The internal `_royaltyPayOut` function MUST perform the following actions: -* *send the payment to the `payoutaccount`.* -* *update the `royaltybalance` of the `RAsubaccount` of the Royalty Account upon successful transfer.* - -**[R59]** *The following steps MUST be taken to send out a royalty payment to its recipient:* -* *find the Royalty Sub Account.* -* *extract `tokenType` from the Royalty Sub Account.* -* *based on the token type send to the `payoutAccount` either* - * *'ETH' / relevant protocol token or* - * *another token based on token type* -* *and only if the payout transaction is successful, deduct `amount` from `royaltybalance` of the Royalty Sub Account,`RAsubaccount`, and then return `true` as the function return parameter, otherwise return `false`.* - -## Rationale - -Royalties for NFTs is at its core a distribution licensing problem. A buyer obtains the right to an asset/content which might or might not be reproducible, alterable etc. by the buyer or agents of the buyer. Therefore, a comprehensive specification must address a hierarchy of royalties, where one or more assets are derived from an original asset as described in the Motivation section in detail. Consequently, a design must solve for a multi-level inheritance, and thus, recursion problem. - -In order to solve for the complicated inheritance problem, this proposal design breaks down the recursive problem of the hierarchy first into a tree of depth N. And the further breaks down the tree structure into N separate problems, one for each layer. This design allows one to traverse the tree from its lowest level upwards to its root most efficiently. This is achieved with the design for the `distributePayment` function and the NFT data structures allowing for the tree structure e.g. `ancestry`,`royaltyAccount`, `RAsubaccount`. - -In order to avoid massive gas costs during the payout of royalties, possibly exceeding block gas limits for large royalty trees, the design needed to create a royalty accounting system to maintain royalty balances for recipients as done with the `royaltyAccount`, 'RAsubaccount' data structures and the associated CRUD operations, as well as require that royalty payouts are done by indvidual and by request, only, as is achieved with the `royaltyPayout` function design. - -Furthermore, the design had to ensure that in order to account for and payout royalties the smart contract must be in the "know" of all buying and selling of an NFT including the exchange of monies. This buying and selling can be either direct through the NFT contract or can be exchange-mediated as is most often the case today -- which is a centralizing factor! The chosen design for purchasing is accounting for those two modes. - -Keeping the NFT contract in the "know" at the beginning of the purchase process requires that authorized user addresses can list NFTs for sale for direct sales , whereas for exchange-mediated purchases, a payment must be registered with the NFT contract before the purchase can be completed. - -The design needed to avoid royalty circumvention during the purchase process, therefore, the NFT must be kept in the "know", a buyer will always have to pay the NFT contract directly and not the seller for both purchasing modes. The seller is subsequently paid through the royalty distribution function in the NFT contract. As a consequence, and a key design choice, and to stay compliant with EIP-721, the NFT contract must be the owner of the NFT, and the actual owner is an `approved` address. - -The specification design also needed to account for that the payment process depends on whether the payment is received in ETH or an EIP-20 token: -* EIP-20 Token - 1. The Buyer must `approve` the NFT contract for the purchase price, `payment` for the selected payment token (EIP-20 contract address). - 2. For an EIP-20 payment token, the Buyer must then call the `executePayment` in the NFT contract -- the EIP-20 is not directly involved. -* For a non-EIP-20 payment, the Buyer must send a protocol token (ETH) to the NFT contract, and is required to send encoded listing and payment information. - -In addition, the `executePayment` function had to be designed to handle both direct sales (through the NFT contract) and exchange-mediated sales which required the introduction of an indicator whether the purchase is direct or exchange-mediated. - -The `executePayment` function also has to handle the NFT transfer and purchase clean up -- removal of a listing, or removal of a registered payment, distribution of royalties, payment to the seller, and finally transfer to the seller. - -To stay compliant with the EIP-721 design but avoid royalty circumvention, all transfer functions must be disabled save the one that allows for additional information to be submitted with the function in order to manage the complicated purchase cleanup process -- `safeTransferFrom`. To ensure safety, the design enforces that input parameters must satisfy several requirements for the NFT to be transferred AFTER the royalties have been properly distributed, not before. The design accounts for the fact that we need to treat transfer somewhat differently for direct sales versus exchange mediated sales. - -Finally the specification needed to take into account that NFTs must be able to be `minted` and `burned` to maintain compliance with the EIP-721 specification while also having to set up all the data structures for the tree. - -The design enforces that when an NFT is minted, a royalty account for that NFT must be created and associated with the NFT and the NFT owner, and, if there is an ancestor of the NFT with the ancestor's royalty account to enforces the tree structure. To this end the specification utilizes the EIP-721 `_safemint` function in a newly defined `mint` function and applies various business rules on the input variables required to ensure proper set-up. - -An NFT with a royalty account can be burned. However, several things have to be true to avoid locking funds not only for the royalty account of the NFT but also its descendants, if they exist. That means that all royalties for the NFT and its descendants, if they exists, must be paid out. Furthermore, if descendants exist, they must have been burned before an ancestor can be burned. If those rules are not enforced the cleanly, the hierarchical royalty structure in part of the tree can break down and lead to lost funds, not paid out royalties etc. - - -## Backwards Compatibility -This EIP is backwards compatible to the EIP-721 standard introducing new interfaces and functionality but retaining the core interfaces and functionality of the EIP-721 standard. - -## Test Cases -A full test suite is part of the reference implementation. - -## Reference Implementation -The Treetrunk reference implementation of the standard can be found in the public treetrunkio Github repo under treetrunk-nft-reference-implementation. - -## Security Considerations -Given that this EIP introduces royalty collection, distribution, and payouts to the EIP-721 standard, the number of attack vectors increases. The most important attack vector categories and their mitigation are discussed below: - -- **Payments and Payouts**: - - Reentrancy attacks are mitigated through a reentrancy protection on all payment functions. See for example the Open Zeppelin reference implementation . - - Payouts from unauthorized accounts. Mitigation: Royalty Sub Accounts require at least that `msg.sender` is the Royalty Sub Account owner. - - Payments could get stuck in the NFT contract if the `executePayment` function fails. Mitigation: For exchange-mediated sales, a buyer can always reverse a payment with `reversePayment` if the `executePayment` function fails. For direct sales, `reversePayment` will be directly triggered in the `executePayment` function. -- **Circumventing Royalties**: - - Offchain Key exchanges - - Exchanging a private key for money off chain can not be prevented in any scenario. - - Smart Contract Wallets as NFT owners - - A Smart Contract Wallet controlled by multiple addresses could own an NFT and the owners could transfer the asset within the wallet with an off chain money exchange. Mitigation: Prohibit that Smart Contracts can own an NFT unless explicitly allowed to accommodate special scenarios such as collections. - - Denial of Royalty Disbursement - - An attacker who has purchased one or more NFTs in a given generation of an NFT family can cause out of gas errors or run time errors for the contract, if they add many spurious royalty sub-accounts with very low royalty split percentages, and then mint more prints of those purchased NFTs, and then repeat that step until the set `maxGeneration` limit is reached. An NFT trade at the bottom of the hierarchy will then require a lot of code cycles because of the recursive nature of the royalty distribution function. Mitigation: Limit the number of royalty sub-accounts per NFT and impose a royalty split percentage limit. - - Following the same approach as above but now targeting the `addListNFT` function, an attacker can force an out of gas error or run time errors in the `executePayment` function by listing many NFTs at a low price, and then performing a purchase from another account. Mitigation: Limit the number of NFTs that can be included in one listing. - - The creator of the NFT family could set the number of generations too high such that the royalty distribution function could incur and out of gas or run time error because of the recursive nature of the function. Mitigation: Limiting the `maxNumberGeneration` by the creator. - - General Considerations: The creator of an NFT family must carefully consider the business model for the NFT family and then set the parameters such as maximum number of generations, royalty sub-accounts, number of prints per print, number of NFTs in a listing, and the maximum and minimum royalty split percentage allowed. - -- **Phishing Attacks** - - NFT phishing attacks often target the `approve` and `setApprovalForAll` functions by tricking owners of NFTs to sign transactions adding the attacker account as approved for one or all NFTs of the victim. Mitigation: This contract is not vulnerable to these type of phishing attacks because all NFT transfers are sales, and the NFT contract itself is the owner of all NFTs. This means that transfers after a purchase are achieved by setting the new owner in the `_approve` function. Calling the public `approve` function will cause the function call to error out because `msg.sender` of the malicious transaction cannot be the NFT owner. - - NFT phishing attack targeting the `addListNFT` function to trick victim to list one or more NFTs at a very low price and the attacker immediately registering a payment, and executing that payment right away. Mitigation: Implement a waiting period for a purchase can be affected giving the victim time to call the `removeListNFT` function. In addition, an implementer could require Two-Factor-Authentication either built into the contract or by utilizing an authenticator app such as Google Authenticator built into a wallet software. - -Besides the usage of professional security analysis tools, it is also recommended that each implementation performs a security audit of its implementation. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4910.md diff --git a/EIPS/eip-4931.md b/EIPS/eip-4931.md index 5fbf719b18072a..479459fd3765bd 100644 --- a/EIPS/eip-4931.md +++ b/EIPS/eip-4931.md @@ -1,350 +1,7 @@ --- eip: 4931 -title: Generic Token Upgrade Standard -description: Create a standard interface for upgrading ERC20 token contracts. -author: John Peterson (@John-peterson-coinbase), Roberto Bayardo (@roberto-bayardo), David Núñez (@cygnusv) -discussions-to: https://ethereum-magicians.org/t/eip-4931-generic-token-upgrade-standard/8687 -status: Stagnant -type: Standards Track category: ERC -created: 2021-11-02 -requires: 20 +status: Moved --- - -## Abstract - -The following standard allows for the implementation of a standard API for [ERC-20](./eip-20.md) token upgrades. This standard specifies an interface that supports the conversion of tokens from one contract (called the "source token") to those from another (called the "destination token"), as well as several helper methods to provide basic information about the token upgrade (i.e. the address of the source and destination token contracts, the ratio that source will be upgraded to destination, etc.). - -## Motivation - -Token contract upgrades typically require each asset holder to exchange their old tokens for new ones using a bespoke interface provided by the developers. This standard interface will allow asset holders as well as centralized and decentralized exchanges to conduct token upgrades more efficiently since token contract upgrade scripts will be essentially reusable. Standardization will reduce the security overhead involved in verifying the functionality of the upgrade contracts. It will also provide asset issuers clear guidance on how to effectively implement a token upgrade. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Please Note: Methods marked with (Optional Ext.) are a part of the optional extension for downgrade functionality and may remain unimplemented if downgrade functionality is not required. -### Token Upgrade Interface Contract -``` solidity -interface IEIP4931 { -``` -#### Methods - -##### upgradeSource - -Returns the address of the original (source) token that will be upgraded. - -``` solidity -/// @dev A getter to determine the contract that is being upgraded from ("source contract") -/// @return The address of the source token contract -function upgradeSource() external view returns(address) -``` - -##### upgradeDestination - -Returns the address of the token contract that is being upgraded to. - -``` solidity -/// @dev A getter to determine the contract that is being upgraded to ("destination contract") -/// @return The address of the destination token contract -function upgradeDestination() external view returns(address) -``` - -##### isUpgradeActive - -Returns the current status of the upgrade functionality. Status MUST return `true` when the upgrade contract is functional and serving upgrades. It MUST return `false` when the upgrade contract is not currently serving upgrades. - -``` solidity -/// @dev The method will return true when the contract is serving upgrades and otherwise false -/// @return The status of the upgrade as a boolean -function isUpgradeActive() external view returns(bool) -``` -##### isDowngradeActive - -Returns the current status of the downgrade functionality. Status MUST return `true` when the upgrade contract is functional and serving downgrades. It MUST return `false` when the upgrade contract is not currently serving downgrades. When the downgrade Optional Ext. is not implemented, this method will always return `false` to signify downgrades are not available. - -``` solidity -/// @dev The method will return true when the contract is serving downgrades and otherwise false -/// @return The status of the downgrade as a boolean -function isDowngradeActive() external view returns(bool) -``` -##### ratio - -Returns the ratio of destination token to source token, expressed as a 2-tuple, that the upgrade will use. E.g. `(3, 1)` means the upgrade will provide 3 destination tokens for every 1 source token being upgraded. - -``` solidity -/// @dev A getter for the ratio of destination tokens to source tokens received when conducting an upgrade -/// @return Two uint256, the first represents the numerator while the second represents -/// the denominator of the ratio of destination tokens to source tokens allotted during the upgrade -function ratio() external view returns(uint256, uint256) -``` - -##### totalUpgraded - -Returns the total number of tokens that have been upgraded from source to destination. If the downgrade Optional Ext. is implemented, calls to `downgrade` will reduce the `totalUpgraded` return value making it possible for the value to decrease between calls. The return value will be strictly increasing if downgrades are not implemented. - -``` solidity -/// @dev A getter for the total amount of source tokens that have been upgraded to destination tokens. -/// The value may not be strictly increasing if the downgrade Optional Ext. is implemented. -/// @return The number of source tokens that have been upgraded to destination tokens -function totalUpgraded() external view returns(uint256) -``` -##### computeUpgrade - -Computes the `destinationAmount` of destination tokens that correspond to a given `sourceAmount` of source tokens, according to the predefined conversion ratio, as well as the `sourceRemainder` amount of source tokens that can't be upgraded. For example, let's consider a (3, 2) ratio, which means that 3 destination tokens are provided for every 2 source tokens; then, for a source amount of 5 tokens, `computeUpgrade(5)` must return `(6, 1)`, meaning that 6 destination tokens are expected (in this case, from 4 source tokens) and 1 source token is left as remainder. -``` solidity -/// @dev A method to mock the upgrade call determining the amount of destination tokens received from an upgrade -/// as well as the amount of source tokens that are left over as remainder -/// @param sourceAmount The amount of source tokens that will be upgraded -/// @return destinationAmount A uint256 representing the amount of destination tokens received if upgrade is called -/// @return sourceRemainder A uint256 representing the amount of source tokens left over as remainder if upgrade is called -function computeUpgrade(uint256 sourceAmount) external view - returns (uint256 destinationAmount, uint256 sourceRemainder) -``` - -##### computeDowngrade (Optional Ext.) - -Computes the `sourceAmount` of source tokens that correspond to a given `destinationAmount` of destination tokens, according to the predefined conversion ratio, as well as the `destinationRemainder` amount of destination tokens that can't be downgraded. For example, let's consider a (3, 2) ratio, which means that 3 destination tokens are provided for every 2 source tokens; for a destination amount of 13 tokens, `computeDowngrade(13)` must return `(4, 1)`, meaning that 4 source tokens are expected (in this case, from 12 destination tokens) and 1 destination token is left as remainder. -``` solidity -/// @dev A method to mock the downgrade call determining the amount of source tokens received from a downgrade -/// as well as the amount of destination tokens that are left over as remainder -/// @param destinationAmount The amount of destination tokens that will be downgraded -/// @return sourceAmount A uint256 representing the amount of source tokens received if downgrade is called -/// @return destinationRemainder A uint256 representing the amount of destination tokens left over as remainder if upgrade is called -function computeDowngrade(uint256 destinationAmount) external view - returns (uint256 sourceAmount, uint256 destinationRemainder) -``` - - -##### upgrade - -Upgrades the `amount` of source token to the destination token in the specified ratio. The destination tokens will be sent to the `_to` address. The function MUST lock the source tokens in the upgrade contract or burn them. If the downgrade Optional Ext. is implemented, the source tokens MUST be locked instead of burning. The function MUST `throw` if the caller's address does not have enough source token to upgrade or if `isUpgradeActive` is returning `false`. The function MUST also fire the `Upgrade` event. `approve` MUST be called first on the source contract. -``` solidity -/// @dev A method to conduct an upgrade from source token to destination token. -/// The call will fail if upgrade status is not true, if approve has not been called -/// on the source contract, or if sourceAmount is larger than the amount of source tokens at the msg.sender address. -/// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the upgrade call will -/// only upgrade the nearest whole amount of source tokens returning the excess to the msg.sender address. -/// Emits the Upgrade event -/// @param _to The address the destination tokens will be sent to upon completion of the upgrade -/// @param sourceAmount The amount of source tokens that will be upgraded -function upgrade(address _to, uint256 sourceAmount) external -``` - - -##### downgrade (Optional Ext.) -Downgrades the `amount` of destination token to the source token in the specified ratio. The source tokens will be sent to the `_to` address. The function MUST unwrap the destination tokens back to the source tokens. The function MUST `throw` if the caller's address does not have enough destination token to downgrade or if `isDowngradeActive` is returning `false`. The function MUST also fire the `Downgrade` event. `approve` MUST be called first on the destination contract. -``` solidity -/// @dev A method to conduct a downgrade from destination token to source token. -/// The call will fail if downgrade status is not true, if approve has not been called -/// on the destination contract, or if destinationAmount is larger than the amount of destination tokens at the msg.sender address. -/// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the downgrade call will only downgrade -/// the nearest whole amount of destination tokens returning the excess to the msg.sender address. -/// Emits the Downgrade event -/// @param _to The address the source tokens will be sent to upon completion of the downgrade -/// @param destinationAmount The amount of destination tokens that will be downgraded -function downgrade(address _to, uint256 destinationAmount) external -``` - -#### Events - -##### Upgrade - -MUST trigger when tokens are upgraded. - -``` solidity -/// @param _from Address that called upgrade -/// @param _to Address that destination tokens were sent to upon completion of the upgrade -/// @param sourceAmount Amount of source tokens that were upgraded -/// @param destinationAmount Amount of destination tokens sent to the _to address -event Upgrade(address indexed _from, address indexed _to, uint256 sourceAmount, uint256 destinationAmount) -``` - -##### Downgrade (Optional Ext.) - -MUST trigger when tokens are downgraded. - -``` solidity -/// @param _from Address that called downgrade -/// @param _to Address that source tokens were sent to upon completion of the downgrade -/// @param sourceAmount Amount of source tokens sent to the _to address -/// @param destinationAmount Amount of destination tokens that were downgraded -event Downgrade(address indexed _from, address indexed _to, uint256 sourceAmount, uint256 destinationAmount) -} -``` - -## Rationale -There have been several notable ERC20 upgrades (Ex. Golem: GNT -> GLM) where the upgrade functionality is written directly into the token contracts. We view this as a suboptimal approach to upgrades since it tightly couples the upgrade with the existing tokens. This EIP promotes the use of a third contract to facilitate the token upgrade to decouple the functionality of the upgrade from the functionality of the token contracts. Standardizing the upgrade functionality will allow asset holders and exchanges to write simplified reusable scripts to conduct upgrades which will reduce the overhead of conducting upgrades in the future. The interface aims to be intentionally broad leaving much of the specifics of the upgrade to the implementer, so that the token contract implementations do not interfere with the upgrade process. Finally, we hope to create a greater sense of security and validity for token upgrades by enforcing strict means of disposing of the source tokens during the upgrade. This is achieved by the specification of the `upgrade` method. The agreed upon norm is that burnable tokens shall be burned. Otherwise, tokens shall be effectively burned by being sent to the `0x00` address. When downgrade Optional Ext. is implemented, the default is instead to lock source tokens in the upgrade contract to avoid a series of consecutive calls to `upgrade` and `downgrade` from artificially inflating the supply of either token (source or destination). - -## Backwards Compatibility -There are no breaking backwards compatibility issues. There are previously implemented token upgrades that likely do not adhere to this standard. In these cases, it may be relevant for the asset issuers to communicate that their upgrade is not EIP-4931 compliant. - -## Reference Implementation -``` solidity -//SPDX-License-Identifier: Apache-2.0 -pragma solidity 0.8.9; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "./IEIP4931.sol"; - -contract SourceUpgrade is IEIP4931 { - using SafeERC20 for IERC20; - - uint256 constant RATIO_SCALE = 10**18; - - IERC20 private source; - IERC20 private destination; - bool private upgradeStatus; - bool private downgradeStatus; - uint256 private numeratorRatio; - uint256 private denominatorRatio; - uint256 private sourceUpgradedTotal; - - mapping(address => uint256) public upgradedBalance; - - constructor(address _source, address _destination, bool _upgradeStatus, bool _downgradeStatus, uint256 _numeratorRatio, uint256 _denominatorRatio) { - require(_source != _destination, "SourceUpgrade: source and destination addresses are the same"); - require(_source != address(0), "SourceUpgrade: source address cannot be zero address"); - require(_destination != address(0), "SourceUpgrade: destination address cannot be zero address"); - require(_numeratorRatio > 0, "SourceUpgrade: numerator of ratio cannot be zero"); - require(_denominatorRatio > 0, "SourceUpgrade: denominator of ratio cannot be zero"); - - source = IERC20(_source); - destination = IERC20(_destination); - upgradeStatus = _upgradeStatus; - downgradeStatus = _downgradeStatus; - numeratorRatio = _numeratorRatio; - denominatorRatio = _denominatorRatio; - } - - /// @dev A getter to determine the contract that is being upgraded from ("source contract") - /// @return The address of the source token contract - function upgradeSource() external view returns(address) { - return address(source); - } - - /// @dev A getter to determine the contract that is being upgraded to ("destination contract") - /// @return The address of the destination token contract - function upgradeDestination() external view returns(address) { - return address(destination); - } - - /// @dev The method will return true when the contract is serving upgrades and otherwise false - /// @return The status of the upgrade as a boolean - function isUpgradeActive() external view returns(bool) { - return upgradeStatus; - } - - /// @dev The method will return true when the contract is serving downgrades and otherwise false - /// @return The status of the downgrade as a boolean - function isDowngradeActive() external view returns(bool) { - return downgradeStatus; - } - - /// @dev A getter for the ratio of destination tokens to source tokens received when conducting an upgrade - /// @return Two uint256, the first represents the numerator while the second represents - /// the denominator of the ratio of destination tokens to source tokens allotted during the upgrade - function ratio() external view returns(uint256, uint256) { - return (numeratorRatio, denominatorRatio); - } - - /// @dev A getter for the total amount of source tokens that have been upgraded to destination tokens. - /// The value may not be strictly increasing if the downgrade Optional Ext. is implemented. - /// @return The number of source tokens that have been upgraded to destination tokens - function totalUpgraded() external view returns(uint256) { - return sourceUpgradedTotal; - } - - /// @dev A method to mock the upgrade call determining the amount of destination tokens received from an upgrade - /// as well as the amount of source tokens that are left over as remainder - /// @param sourceAmount The amount of source tokens that will be upgraded - /// @return destinationAmount A uint256 representing the amount of destination tokens received if upgrade is called - /// @return sourceRemainder A uint256 representing the amount of source tokens left over as remainder if upgrade is called - function computeUpgrade(uint256 sourceAmount) - public - view - returns (uint256 destinationAmount, uint256 sourceRemainder) - { - sourceRemainder = sourceAmount % (numeratorRatio / denominatorRatio); - uint256 upgradeableAmount = sourceAmount - (sourceRemainder * RATIO_SCALE); - destinationAmount = upgradeableAmount * (numeratorRatio / denominatorRatio); - } - - /// @dev A method to mock the downgrade call determining the amount of source tokens received from a downgrade - /// as well as the amount of destination tokens that are left over as remainder - /// @param destinationAmount The amount of destination tokens that will be downgraded - /// @return sourceAmount A uint256 representing the amount of source tokens received if downgrade is called - /// @return destinationRemainder A uint256 representing the amount of destination tokens left over as remainder if upgrade is called - function computeDowngrade(uint256 destinationAmount) - public - view - returns (uint256 sourceAmount, uint256 destinationRemainder) - { - destinationRemainder = destinationAmount % (denominatorRatio / numeratorRatio); - uint256 upgradeableAmount = destinationAmount - (destinationRemainder * RATIO_SCALE); - sourceAmount = upgradeableAmount / (denominatorRatio / numeratorRatio); - } - - /// @dev A method to conduct an upgrade from source token to destination token. - /// The call will fail if upgrade status is not true, if approve has not been called - /// on the source contract, or if sourceAmount is larger than the amount of source tokens at the msg.sender address. - /// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the upgrade call will - /// only upgrade the nearest whole amount of source tokens returning the excess to the msg.sender address. - /// Emits the Upgrade event - /// @param _to The address the destination tokens will be sent to upon completion of the upgrade - /// @param sourceAmount The amount of source tokens that will be upgraded - function upgrade(address _to, uint256 sourceAmount) external { - require(upgradeStatus == true, "SourceUpgrade: upgrade status is not active"); - (uint256 destinationAmount, uint256 sourceRemainder) = computeUpgrade(sourceAmount); - sourceAmount -= sourceRemainder; - require(sourceAmount > 0, "SourceUpgrade: disallow conversions of zero value"); - - upgradedBalance[msg.sender] += sourceAmount; - source.safeTransferFrom( - msg.sender, - address(this), - sourceAmount - ); - destination.safeTransfer(_to, destinationAmount); - sourceUpgradedTotal += sourceAmount; - emit Upgrade(msg.sender, _to, sourceAmount, destinationAmount); - } - - /// @dev A method to conduct a downgrade from destination token to source token. - /// The call will fail if downgrade status is not true, if approve has not been called - /// on the destination contract, or if destinationAmount is larger than the amount of destination tokens at the msg.sender address. - /// If the ratio would cause an amount of tokens to be destroyed by rounding/truncation, the downgrade call will only downgrade - /// the nearest whole amount of destination tokens returning the excess to the msg.sender address. - /// Emits the Downgrade event - /// @param _to The address the source tokens will be sent to upon completion of the downgrade - /// @param destinationAmount The amount of destination tokens that will be downgraded - function downgrade(address _to, uint256 destinationAmount) external { - require(upgradeStatus == true, "SourceUpgrade: upgrade status is not active"); - (uint256 sourceAmount, uint256 destinationRemainder) = computeDowngrade(destinationAmount); - destinationAmount -= destinationRemainder; - require(destinationAmount > 0, "SourceUpgrade: disallow conversions of zero value"); - require(upgradedBalance[msg.sender] >= sourceAmount, - "SourceUpgrade: can not downgrade more than previously upgraded" - ); - - upgradedBalance[msg.sender] -= sourceAmount; - destination.safeTransferFrom( - msg.sender, - address(this), - destinationAmount - ); - source.safeTransfer(_to, sourceAmount); - sourceUpgradedTotal -= sourceAmount; - emit Downgrade(msg.sender, _to, sourceAmount, destinationAmount); - } -} -``` - - -## Security Considerations -The main security consideration is ensuring the implementation of the interface handles the source tokens during the upgrade in such a way that they are no longer accessible. Without careful handling, the validity of the upgrade may come into question since source tokens could potentially be upgraded multiple times. This is why EIP-4931 will strictly enforce the use of `burn` for source tokens that are burnable. For non-burnable tokens, the accepted method is to send the source tokens to the `0x00` address. When the downgrade Optional Ext. is implemented, the constraint will be relaxed, so that the source tokens can be held by the upgrade contract. - -## Copyright -Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4931.md diff --git a/EIPS/eip-4938.md b/EIPS/eip-4938.md index 2879fcad8ff78f..fed17608d31f8a 100644 --- a/EIPS/eip-4938.md +++ b/EIPS/eip-4938.md @@ -4,7 +4,7 @@ title: "eth/67 - Removal of GetNodeData" description: "Remove GetNodeData and NodeData messages from the wire protocol" author: Marius van der Wijden (@MariusVanDerWijden), Felix Lange , Gary Rong discussions-to: https://ethereum-magicians.org/t/eip-4938-removal-of-getnodedata/8893 -status: Review +status: Final type: Standards Track category: Networking created: 2022-03-23 diff --git a/EIPS/eip-4944.md b/EIPS/eip-4944.md index 95ba3a80bb18f6..54629461207dba 100644 --- a/EIPS/eip-4944.md +++ b/EIPS/eip-4944.md @@ -1,71 +1,7 @@ --- eip: 4944 -title: Contract with Exactly One Non-fungible Token -description: An ERC721-compatible single-token NFT -author: Víctor Muñoz (@victormunoz), Josep Lluis de la Rosa (@peplluis7), Andres El-Fakdi (@Bluezfish) -discussions-to: https://ethereum-magicians.org/t/erc721-minting-only-one-token/8602/2 -status: Stagnant -type: Standards Track category: ERC -created: 2022-03-25 -requires: 721 +status: Moved --- -## Abstract -The following describes standard functions for an [ERC-721](./eip-721.md) compatible contract with a total supply of one. -This allows an NFT to be associated uniquely with a single contract address. - -## Motivation -If the ERC721 was modified to mint only 1 token (per contract), then the contract address could be identified uniquely with that minted token (instead of the tuple contract address + token id, as ERC721 requires). -This change would enable automatically all the capabilities of composable tokens ERC-998 (own other ERC721 or ERC20) natively without adding any extra code, just forbidding to mint more than one token per deployed contract. -Then the NFT minted with this contract could operate with his "budget" (the ERC20 he owned) and also trade with the other NFTs he could own. Just like an autonomous agent, that could decide what to do with his properties (sell his NFTs, buy other NFTs, etc). - -The first use case that is devised is for value preservation. Digital assets, as NFTs, have value that has to be preserved in order to not be lost. If the asset has its own budget (in other ERC20 coins), could use it to autopreserve itself. - -## Specification -The constructor should mint the unique token of the contract, and then the mint function should add a restriction to avoid further minting. - -Also, a `tokenTransfer` function should be added in order to allow the contract owner to transact with the ERC20 tokens owned by the contract/NFT itself. So that if the contract receives a transfer of ERC20 tokens, the owner of the NFT could spend it from the contract wallet. - -## Rationale -The main motivation is to keep the contract compatible with current ERC721 platforms. - -## Backwards Compatibility -There are no backwards compatibility issues. - -## Reference Implementation -Add the variable `_minted` in the contract: - -``` solidity - bool private _minted; -``` - -In the constructor, automint the first token and set the variable to true: - -``` solidity - constructor(string memory name, string memory symbol, string memory base_uri) ERC721(name, symbol) { - baseUri = base_uri; - mint(msg.sender,0); - _minted = true; - } -``` - -Add additional functions to interact with the NFT properties (for instance, ERC20): - -``` solidity - modifier onlyOwner() { - require(balanceOf(msg.sender) > 0, "Caller is not the owner of the NFT"); - _; - } - - function transferTokens(IERC20 token, address recipient, uint256 amount) public onlyOwner { - token.transfer(recipient, amount); - } -``` - - -## Security Considerations -No security issues found. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4944.md diff --git a/EIPS/eip-4950.md b/EIPS/eip-4950.md index d74ccdbe250b67..4ea0a1fe066128 100644 --- a/EIPS/eip-4950.md +++ b/EIPS/eip-4950.md @@ -1,90 +1,7 @@ --- eip: 4950 -title: Entangled Tokens -description: EIP-721 extension with two tokens minted that are tied together -author: Víctor Muñoz (@victormunoz), Josep Lluis de la Rosa (@peplluis7), Easy Innova (@easyinnova) -discussions-to: https://ethereum-magicians.org/t/entangled-tokens/8702 -status: Stagnant -type: Standards Track category: ERC -created: 2022-03-28 -requires: 20, 721, 1155 +status: Moved --- -## Abstract -This EIP defines an interface for delegating control of a smart contract wallet to pairs of users using entangled [EIP-721](./eip-721.md) non-fungible tokens. - -## Motivation -The motivation is to provide an easy way to share a wallet through NFTs, so that the act of buying an NFT (in a marketplace) gives the buyer the privilege to have access to a given wallet. This wallet could have budget in many tokens, or even be the owner of other NFTs. - - -A use case is to keep contact between an artist and an buyer of its NFTs. If an artist T has created a digital piece of art P with an NFT, then T creates 2 entangled tokens A and B so that he keeps A and transfer B to P. By construction of entangled tokens, only one transfer is possible for them, thus the artist proofs he’s been the creator of P by sending a transaction to A that is visible from B. Otherwise, the owner of P might check the authenticity of the artist by sending a transaction to B so that the artist might proof by showing the outcome out of A. - -A version of this use case is when one user U mints his piece of art directly in the form of an entangled token A; then the user U sells/transfers it while keeping the entangled token B in the U's wallet. The piece of art and the artists will be entangled whoever is the A's owner. - -These applications of entangled tokens are envisaged to be useful for -1. NFT authorship / art creation -2. Distribution of royalties by the creator. -3. Authenticity of a work of art: creation limited to the author (e.g. only 1000 copies if there are 1000 1000 entangled tokens in that NFT). -4. Usowners (users that consume an NFT also become -partial- owners of the NFT) -5. Reformulation of property rights: the one who owns the property receives it without having to follow in the footsteps of the owners. -6. Identity: Only those credentials that have an entangled token with you are related to you. -7. Vreservers (value-reservers). - - -## Specification -An entangled token contract implements [EIP-721](./eip-721.md) with the additional restriction that it only ever mints exactly two tokens at contract deployment: one with a `tokenId` of `0`, the other with a `tokenId` of `1`. The entangled token contract also implements a smart contract wallet that can be operated by the owners of those two tokens. - - -Also, a `tokenTransfer` function is to be be added in order to allow the token owners to transact with the [EIP-20](./eip-20.md) tokens owned by the contract/NFT itself. The function signature is as follows: - -```solidity - function tokenTransfer(IERC20 token, address recipient, uint256 amount) public onlyOwners; -``` - -## Rationale -We decide to extend [EIP-721](./eip-721.md) ([EIP-1155](./eip-1155.md) could be also possible) because the main purpose of this is to be compatible with current marketplaces platforms. This entangled NFTs will be listed in a marketplace, and the user who buys it will have then the possibility to transact with the wallet properties (fungible and non fungible tokens). - - -## Backwards Compatibility -No backwards compatibility issues. - -## Reference Implementation -Mint two tokens, and only two, at the contract constructor, and set the `minted` property to true: - -```solidity -bool private _minted; - -constructor(string memory name, string memory symbol, string memory base_uri) ERC721(name, symbol) { - baseUri = base_uri; - _mint(msg.sender,0); - _mint(msg.sender,1); - _minted = true; - } - -function _mint(address to, uint256 tokenId) internal virtual override { - require(!_minted, "ERC4950: already minted"); - super._mint(to, tokenId); -} -``` - -Add additional functions to allow both NFT user owners to operate with other EIP-20 tokens owned by the contract: - - -```solidity - modifier onlyOwners() { - require(balanceOf(msg.sender) > 0, "Caller does not own any of the tokens"); - _; - } - -function tokenTransfer(IERC20 token, address recipient, uint256 amount) public onlyOwners { - token.transfer(recipient, amount); - } -``` - -## Security Considerations -There are no security considerations. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4950.md diff --git a/EIPS/eip-4955.md b/EIPS/eip-4955.md index ee650ebae1e776..c1b433ff16912c 100644 --- a/EIPS/eip-4955.md +++ b/EIPS/eip-4955.md @@ -1,198 +1,7 @@ --- eip: 4955 -title: Vendor Metadata Extension for NFTs -description: Add a new field to NFT metadata to store vendor specific data -author: Ignacio Mazzara (@nachomazzara) -discussions-to: https://ethereum-magicians.org/t/eip-4955-non-fungible-token-metadata-namespaces-extension/8746 -status: Final -type: Standards Track category: ERC -created: 2022-03-29 -requires: 721, 1155 +status: Moved --- -## Abstract - -This EIP standardizes a schema for NFTs metadata to add new field namespaces to the JSON schema for [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) NFTs. - -## Motivation - -A standardized NFT metadata schema allows wallets, marketplaces, metaverses, and sililar applications to interoperate with any NFT. Applications such as NFT marketplaces and metaverses could usefully leverage NFTs by rendering them using custom 3D representations or any other new attributes. - -Some projects like Decentraland, TheSandbox, Cryptoavatars, etc. need their own 3D model in order to represent an NFT. These models are not cross-compatible because of distinct aesthetics and data formats. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Schema - -(subject to "caveats" below) - -A new property called `namespaces` is introduced. This property expects one object per project as shown in the example below. - -```jsonc -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset that this NFT represents" - }, - "description": { - "type": "string", - "description": "Describes the asset that this NFT represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset that this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "namespaces": { - "type": "object", - "description": "Application-specific NFT properties" - } - } -} -``` - -### Example - -```jsonc -{ - "name": "My NFT", - "description": "NFT description", - "image": "ipfs://QmZfmRZHuawJDtDVMaEaPWfgWFV9iXoS9SzLvwX76wm6pa", - "namespaces": { - "myAwesomeCompany": { - "prop1": "value1", - "prop2": "value2", - }, - "myAwesomeCompany2": { - "prop3": "value3", - "prop4": "value4", - }, - } -} - -// Or by simply using a `URI` to reduce the size of the JSON response. - -{ - "name": "My NFT", - "description": "NFT description", - "image": "ipfs://QmZfmRZHuawJDtDVMaEaPWfgWFV9iXoS9SzLvwX76wm6pa", - "namespaces": { - "myAwesomeCompany": "URI", - "myAwesomeCompany2": "URI", - } -} -``` - -## Rationale - -There are many projects which need custom properties in order to display a current NFT. Each project may have its own way to render the NFTs and therefore they need different values. An example of this is the metaverses like Decentraland or TheSandbox where they need different 3d models to render the NFT based on the visual/engine of each. NFTs projects like Cryptopunks, Bored Apes, etc. can create the 3d models needed for each project and therefore be supported out of the box. - -The main differences between the projects that are rendering 3d NFTs (models) are: - -### Armatures - -Every metaverse uses its own armature. There is a standard for humanoids but it is not being used for every metaverse and not all the metaverses use humanoids. For example, Decentraland has a different aesthetic than Cryptovoxels and TheSandbox. It means that every metaverse will need a different model and they may have the same extension (GLB, GLTF) - -![](../assets/eip-4955/different-renders.jpeg) - -### Metadata (Representations Files) - -For example, every metaverse uses its own metadata representation files to make it work inside the engine depending on its game needs. - -This is the JSON config of a wearable item in Decentraland: - -```jsonc -"data": { - "replaces": [], - "hides": [], - "tags": [], - "category": "upper_body", - "representations": [ - { - "bodyShapes": [ - "urn:decentraland:off-chain:base-avatars:BaseMale" - ], - "mainFile": "male/Look6_Tshirt_A.glb", - "contents": [ - { - "key": "male/Look6_Tshirt_A.glb", - "url": "https://peer-ec2.decentraland.org/content/contents/QmX3yMhmx4AvGmyF3CM5ycSQB4F99zXh9rL5GvdxTTcoCR" - } - ], - "overrideHides": [], - "overrideReplaces": [] - }, - { - "bodyShapes": [ - "urn:decentraland:off-chain:base-avatars:BaseFemale" - ], - "mainFile": "female/Look6_Tshirt_B (1).glb", - "contents": [ - { - "key": "female/Look6_Tshirt_B (1).glb", - "url": "https://peer-ec2.decentraland.org/content/contents/QmcgddP4L8CEKfpJ4cSZhswKownnYnpwEP4eYgTxmFdav8" - } - ], - "overrideHides": [], - "overrideReplaces": [] - } - ] -}, -"image": "https://peer-ec2.decentraland.org/content/contents/QmPnzQZWAMP4Grnq6phVteLzHeNxdmbRhKuFKqhHyVMqrK", -"thumbnail": "https://peer-ec2.decentraland.org/content/contents/QmcnBFjhyFShGo9gWk2ETbMRDudiX7yjn282djYCAjoMuL", -"metrics": { - "triangles": 3400, - "materials": 2, - "textures": 2, - "meshes": 2, - "bodies": 2, - "entities": 1 -} -``` - -`replaces`, `overrides`, `hides`, and different body shapes representation for the same asset are needed for Decentraland in order to render the 3D asset correctly. - -Using `namespaces` instead of objects like the ones below make it easy for the specific vendor/third-parties to access and index the required models. Moreover, `styles` do not exist because there are no standards around for how an asset will be rendered. As I mentioned above, each metaverse for example uses its own armature and aesthetic. There is no Decentraland-style or TheSandbox-style that other metaverses use. Each of them is unique and specific for the sake of the platform's reason of being. Projects like Cryptoavatars are trying to push different standards but without luck for the same reasons related to the uniquity of the armature/animations/metadata. - -```jsonc -{ - "id": "model", - "type": "model/gltf+json", - "style": "Decentraland", - "uri": "..." -}, - -// Or - -{ - "id": "model", - "type": "model/gltf+json", - "style": "humanoide", - "uri": "..." -}, -``` - -With `namespaces`, each vendor will know how to render an asset by doing: - -```ts -fetch(metadata.namespaces["PROJECT_NAME"].uri).then(res => render(res)) -``` - -The idea behind extending the [EIP-721](./eip-721.md) metadata schema is for backward compatibility. Most projects on Ethereum use non-upgradeable contracts. If this EIP required new implementations of those contracts, they would have to be re-deployed. This is time-consuming and wastes money. Leveraging EIP-721's existing metadata field minimizes the number of changes necessary. Finally, the JSON metadata is already used to store representations using the `image` field. It seems reasonable to have all the representations of an asset in the same place. - -## Backwards Compatibility - -Existing projects that can't modify the metadata response (schema), may be able to create a new smart contract that based on the `tokenId` returns the updated metadata schema. Of course, the projects may need to accept these linked smart contracts as valid in order to fetch the metadata by the `tokenURI` function. - -## Security Considerations - -The same security considerations as with [EIP-721](./eip-721.md) apply related to using http gateways or IPFS for the tokenURI method. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4955.md diff --git a/EIPS/eip-4972.md b/EIPS/eip-4972.md index 31cee4a429350c..4a7501934239cb 100644 --- a/EIPS/eip-4972.md +++ b/EIPS/eip-4972.md @@ -1,162 +1,7 @@ --- eip: 4972 -title: Name-Owned Account -description: Name-Owned Account for Social Identity -author: Shu Dong (@dongshu2013), Qi Zhou (@qizhou) -discussions-to: https://ethereum-magicians.org/t/eip-4972-name-owned-account/8822 -status: Draft -type: Standards Track category: ERC -created: 2022-04-04 -requires: 20, 721 +status: Moved --- -## Abstract - -This ERC proposes a new type of account - name-owned account (NOA) that is controlled by the owner of the name besides existing externally-owned account (EOA) and contract account (CA). With the new account type, users will be able to transfer/receive tokens using the name-derived address directly instead of the address of the name owner. A NOA can be as a social identity with all states on-chain even under 3rd-party or self custody. It also simplifies porting the social identity from one custody to another. - -## Motivation - -A popular way to onboard Web2 users to the Web3 world is custody. However, current custody models have severe drawbacks. Considering the following widely adopted custody models: -1. The custodian uses one EOA/CA to hold the assets of all users. This is not compatible with on-chain social protocols since all user activities are off-chain. -2. One EOA per user. The social identity is not portable, which means there is no way for users to migrate their social identity across different custody platforms. -3. One CA (e.g. Gnosis Safe) per user. The one time deployment cost is super high and the user experience is not good. - -To solve all these problems, this ERC proposes a new type of account - name-owned account (NOA). Using NOA as social identity instead of EOA/CA brings huge benefits for users: -- **Easy Web2 user onboarding**. We are providing standard Web2 user experiences with human readable names and 3rd-party custody. Every user of a centralized platform can immediately have a NOA by using the username as the name of NOA custodied by the platform. -- **On-chain states**. All user states are on-chain even under custody so it’s 100% compatible with social protocols. -- **Portable Account**. A NOA can be easily ported to different custody platforms by changing the owner. -- **Flexible Account Management**. We can use one EOA/CA to control any number of NOAs. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Name-Owned Account - -An NOA has -1. a name for social identity; and -2. an address derived from the name to receive tokens; and -3. owner(s) of the name that can transfer the token. - -The name should be human-readable and can be easily recognized socially. An example is the username of a centralized platform such as FB, Twitter. The name-derived address (NDA) is a normal Ethereum address that should not collide with the existing addresses of EOA/CA. Since we cannot use NDA as msg.sender, the right to transfer the tokens of the NDA is controlled by the owner/owners of the name. The name to owner/owners mapping is managed by an on-chain name service, and the owner/owners are EOA/CA, which can be the addresses of 3-rd custodians (e.g. FB) or self-custodian. By changing the owner of the name to the EOA of the user (can be done by requesting the custodian), the NDA becomes self-custodian, and no one should be able to transfer the assets unless the approved by the self-custodian user. - - -### Name Representation - -A name is represented by a bytes array which is ABI encoded. It **MAY** contain metadata of the name such as the name service the name belongs to. Examples of the name are "vitalik.eth", "vitalik@0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", or "qizhou.fb". - -### Interface -#### INameOwnedAccount -```solidity -interface INameOwnedAccount { - /// @notice This function resolves the _name to its derived address - /// @dev The implementation SHOULD avoid collision between name - /// derived address and EOA/CA - function addressOfName(bytes memory _name) public view returns(address); - - /// @notice This function returns true if and only if the operator is the owner of the _name - /// @dev The ownership MAY be defined by a name service such as ENS - function isNameOwner(bytes memory _from, address operator) public view returns(bool); -} -``` - -#### `IERC721NOA` - -```solidity -interface IERC721NOA is IERC721, INameOwnedAccount { - /// @notice Transfers the ownership of an NFT from a name to an address - /// @dev Throws unless `msg.sender` is the owner of _from. Throw if _from is - /// not the current owner. Throws if `_to` is the zero address. Throws if - /// `_tokenId` is not a valid NFT. When transfer is complete, this function - /// checks if `_to` is a smart contract (code size > 0). If so, it calls - /// `onERC721Received` on `_to` and throws if the return value is not - /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. - function safeTransferFromName(bytes memory _from, address _to, uint256 _tokenId, bytes _data) public returns(bool); - - /// @notice Transfers the ownership of an NFT from a name to another address - /// @dev This works identically to the other function with an extra data parameter, - /// except this function just sets data to "". - function safeTransferFromName(bytes memory _from, address _to, uint256 _tokenId) public returns(bool); - - /// @notice Change or reaffirm the approved address for an NFT - /// @dev The zero address indicates there is no approved address. - /// Throws unless `msg.sender` is the owner of _owner. Throw if _owner is not - /// the current owner. - function approveFromName(bytes memory _owner, address _operator, uint256 _tokenId) public returns(bool); - - /// @notice Enable or disable approval for a third party ("operator") to manage - /// all of _owner’s assets - /// @dev Throws unless `msg.sender` is the owner of _owner. Throw if _owner is not - /// the current owner. Emits the ApprovalForAll event. The contract MUST allow - /// multiple operators per owner. - function setApprovalForAllFromName(bytes memory _owner, address _operator, bool _approved) public returns(bool); - - /// @notice This function returns true if interfaceId is the id of IERC721NOA - /// @dev see {IERC165-supportsInterface} - function supportsInterface(bytes4 interfaceId) external view returns(bool); -} -``` - -#### `IERC20NOA` - -```solidity -interface IERC20NOA is IERC20, INameOwnedAccount { - /// @notice Transfers _value amount of tokens from name _from to address _to, - /// @dev Throws unless `msg.sender` is the owner of _owner. Throw if _owner is not - /// the current owner. Throw if the balance of _from does not have enough tokens to - /// spend. Emits the Transfer event. - function transferFromName(bytes memory _from, address _to, uint256 _value) public returns(bool); - - /// @notice Allows _spender to withdraw from _owner multiple times, up to - /// the _value amount. - /// @dev Throws unless `msg.sender` is the owner of _owner. Throw if _owner is - /// not the current owner. If this function is called again it overwrites the current - /// allowance with _value. - function approveFromName(bytes memory _owner, address _spender, uint256 _value) public returns(bool); - - /// @notice This function returns true if interfaceId is the id of IERC721NOA - /// @dev see {IERC165-supportsInterface} - function supportsInterface(bytes4 interfaceId) external view returns(bool); -} -``` - -### Authentication - -The transfer and approve function is authenticated if and only if the message sender is the owner of the name. - -## Rationale - -We use bytes array to represent a name to ensure it’s flexible enough to deal with different use cases. E.g. one can encode the name service contract address the name belongs to into the bytes array. One can also encode extra authentication data, such as zero knowledge proofs, into the bytes array. In the future, we may propose a standard to formalize the name for wider adoption. - -The isNameOwner function is sufficient for authenticating the message sender. One can verify the owner by looking up the name owner from a name service, or check zero knowledge proofs encoded in name to prove the ownership directly without looking up anything. - -The addressOfName interface decouples the implementation from specific hashing algorithms, as long as the generated address doesn’t collide with EOA/CA address space. - -## Backwards Compatibility - -The new account type is compatible with existing ERC token standards. - -## Reference Implementation -### Name Format - -The decoded format of bytes name is not defined at this standard. One straightforward implementation would be: -```solidity -bytes memory name = abi.encode((string, ‘address’), (username, nameService)) -``` -where the username is the string representation of the username and nameService is the name service contract address. This will decouple the implementation from specific name services such as ENS. - -### Name Derived Address (INameOwnedAccount.addressOfName()) - -With the bytes format mentioned above, we can follow the similar rule of CREATE2 opcode to compute the NOA address from nameService and hash of the username as `address(keccak256(0xff, keccak256(“eip-4972.addressOfName”), nameService, keccak256(username)))`. This can ensure it won’t collide with existing smart contract account addresses. - -### Ownership of a Name (INameOwnedAccount.isNameOwner()) - -Normally we can get the owner from the name service and compare it with the message sender. We recommend the name service to define an owner function in the same format as ENS. - -## Security Considerations - -No security considerations were found. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4972.md diff --git a/EIPS/eip-4973.md b/EIPS/eip-4973.md index 7a8f4e89cc1b9b..47684e3c3913ee 100644 --- a/EIPS/eip-4973.md +++ b/EIPS/eip-4973.md @@ -1,197 +1,7 @@ --- eip: 4973 -title: Account-bound Tokens -description: An interface for non-transferrable NFTs binding to an Ethereum account like a legendary World of Warcraft item binds to a character. -author: Tim Daubenschütz (@TimDaub) -discussions-to: https://ethereum-magicians.org/t/eip-4973-non-transferrable-non-fungible-tokens-soulbound-tokens-or-badges/8825 -status: Review -type: Standards Track category: ERC -created: 2022-04-01 -requires: 165, 712, 721, 1271 +status: Moved --- -## Abstract - -Proposes a standard API for account-bound Tokens (ABT) within smart contracts. An ABT is a non-fungible token bound to a single account. ABTs don't implement a canonical interface for transfers. This EIP defines basic functionality to mint, assign, revoke and track ABTs. - -## Motivation - -In the popular MMORPG World of Warcraft, its game designers intentionally took some items out of the world's auction house market system to prevent them from having a publicly-discovered price and limit their accessibility. - -Vanilla WoW's "Thunderfury, Blessed Blade of the Windseeker" was one such legendary item, and it required a forty-person raid, among other sub-tasks, to slay the firelord "Ragnaros" to gain the "Essence of the Firelord," a material needed to craft the sword once. - -Upon voluntary pickup, the sword permanently **binds** to a character's "soul," making it impossible to trade, sell or even swap it between a player's characters. - -In other words, "Thunderfury"'s price was the aggregate of all social costs related to completing the difficult quest line with friends and guild members. Other players spotting Thunderfuries could be sure their owner had slain "Ragnaros," the blistering firelord. - -World of Warcraft players could **trash** legendary and soulbound items like the Thunderfury to permanently remove them from their account. It was their choice to visibly **equip** or **unequip** an item and hence show their achievements to everyone. - -The Ethereum community has expressed a need for non-transferrable, non-fungible, and socially-priced tokens similar to WoW's soulbound items. Popular contracts implicitly implement account-bound interaction rights today. A principled standardization helps interoperability and improves on-chain data indexing. - -The purpose of this document is to make ABTs a reality on Ethereum by creating consensus around a **maximally backward-compatible** but otherwise **minimal** interface definition. - -## Specification - -### Solidity Interface - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -ABTs _must_ implement the interfaces: - -- [EIP-165](./eip-165.md)'s `ERC165` (`0x01ffc9a7`) -- [EIP-721](./eip-721.md)'s `ERC721Metadata` (`0x5b5e139f`) - -ABTs _must not_ implement the interfaces: - -- [EIP-721](./eip-721.md)'s `ERC721` (`0x80ac58cd`) - -An ABT receiver must be able to always call `function unequip(address _tokenId)` to take their ABT off-chain. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.6; - -/// @title Account-bound tokens -/// @dev See https://eips.ethereum.org/EIPS/eip-4973 -/// Note: the ERC-165 identifier for this interface is 0xeb72bb7c -interface IERC4973 { - /// @dev This emits when ownership of any ABT changes by any mechanism. - /// This event emits when ABTs are given or equipped and unequipped - /// (`to` == 0). - event Transfer( - address indexed from, address indexed to, uint256 indexed tokenId - ); - /// @notice Count all ABTs assigned to an owner - /// @dev ABTs assigned to the zero address are considered invalid, and this - /// function throws for queries about the zero address. - /// @param owner An address for whom to query the balance - /// @return The number of ABTs owned by `address owner`, possibly zero - - function balanceOf(address owner) external view returns (uint256); - /// @notice Find the address bound to an ERC4973 account-bound token - /// @dev ABTs assigned to zero address are considered invalid, and queries - /// about them do throw. - /// @param tokenId The identifier for an ABT. - /// @return The address of the owner bound to the ABT. - function ownerOf(uint256 tokenId) external view returns (address); - /// @notice Removes the `uint256 tokenId` from an account. At any time, an - /// ABT receiver must be able to disassociate themselves from an ABT - /// publicly through calling this function. After successfully executing this - /// function, given the parameters for calling `function give` or - /// `function take` a token must be re-equipable. - /// @dev Must emit a `event Transfer` with the `address to` field pointing to - /// the zero address. - /// @param tokenId The identifier for an ABT. - function unequip(uint256 tokenId) external; - /// @notice Creates and transfers the ownership of an ABT from the - /// transaction's `msg.sender` to `address to`. - /// @dev Throws unless `bytes signature` represents a signature of the - // EIP-712 structured data hash - /// `Agreement(address active,address passive,bytes metadata)` expressing - /// `address to`'s explicit agreement to be publicly associated with - /// `msg.sender` and `bytes metadata`. A unique `uint256 tokenId` must be - /// generated by type-casting the `bytes32` EIP-712 structured data hash to a - /// `uint256`. If `bytes signature` is empty or `address to` is a contract, - /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must - /// be made to `address to`. A successful execution must result in the - /// `event Transfer(msg.sender, to, tokenId)`. Once an ABT exists as an - /// `uint256 tokenId` in the contract, `function give(...)` must throw. - /// @param to The receiver of the ABT. - /// @param metadata The metadata that will be associated to the ABT. - /// @param signature A signature of the EIP-712 structured data hash - /// `Agreement(address active,address passive,bytes metadata)` signed by - /// `address to`. - /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` - /// EIP-712 structured data hash to a `uint256`. - function give(address to, bytes calldata metadata, bytes calldata signature) - external - returns (uint256); - /// @notice Creates and transfers the ownership of an ABT from an - /// `address from` to the transaction's `msg.sender`. - /// @dev Throws unless `bytes signature` represents a signature of the - /// EIP-712 structured data hash - /// `Agreement(address active,address passive,bytes metadata)` expressing - /// `address from`'s explicit agreement to be publicly associated with - /// `msg.sender` and `bytes metadata`. A unique `uint256 tokenId` must be - /// generated by type-casting the `bytes32` EIP-712 structured data hash to a - /// `uint256`. If `bytes signature` is empty or `address from` is a contract, - /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must - /// be made to `address from`. A successful execution must result in the - /// emission of an `event Transfer(from, msg.sender, tokenId)`. Once an ABT - /// exists as an `uint256 tokenId` in the contract, `function take(...)` must - /// throw. - /// @param from The origin of the ABT. - /// @param metadata The metadata that will be associated to the ABT. - /// @param signature A signature of the EIP-712 structured data hash - /// `Agreement(address active,address passive,bytes metadata)` signed by - /// `address from`. - /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` - /// EIP-712 structured data hash to a `uint256`. - function take(address from, bytes calldata metadata, bytes calldata signature) - external - returns (uint256); - /// @notice Decodes the opaque metadata bytestring of an ABT into the token - /// URI that will be associated with it once it is created on chain. - /// @param metadata The metadata that will be associated to an ABT. - /// @return A URI that represents the metadata. - function decodeURI(bytes calldata metadata) external returns (string memory); -} -``` - -See [EIP-721](./eip-721.md) for a definition of its metadata JSON Schema. - -### [EIP-712](./eip-712.md) Typed Structured Data Hashing and Bytearray Signature Creation - -To invoke `function give(...)` and `function take(...)` a bytearray signature must be created using [EIP-712](./eip-712.md). A tested reference implementation in Node.js is attached at [../assets/eip-4973/sdk/src/index.mjs](../assets/eip-4973/sdk/src/index.mjs), [../assets/eip-4973/sdk/test/index_test.mjs](../assets/eip-4973/sdk/test/index_test.mjs) and [../assets/eip-4973/package.json](../assets/eip-4973/package.json). In Solidity, this bytearray signature can be created as follows: - -```solidity -bytes32 r = 0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90; -bytes32 s = 0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064; -uint8 v = 27; -bytes memory signature = abi.encodePacked(r, s, v); -``` - -## Rationale - -### Interface - -ABTs shall be maximally backward-compatible but still only expose a minimal and simple to implement interface definition. - -As [EIP-721](./eip-721.md) tokens have seen widespread adoption with wallet providers and marketplaces, using its `ERC721Metadata` interface with [EIP-165](./eip-165.md) for feature-detection potentially allows implementers to support ABTs out of the box. - -If an implementer of [EIP-721](./eip-721.md) properly built [EIP-165](./eip-165.md)'s `function supportsInterface(bytes4 interfaceID)` function, already by recognizing that [EIP-721](./eip-721.md)'s track and transfer interface component with the identifier `0x80ac58cd` is not implemented, transferring of a token should not be suggested as a user interface option. - -Still, since ABTs support [EIP-721](./eip-721.md)'s `ERC721Metadata` extension, wallets and marketplaces should display an account-bound token with no changes needed. - -Although other implementations of account-bound tokens are possible, e.g., by having all transfer functions revert, ABTs are superior as it supports feature detection through [EIP-165](./eip-165.md). - -We expose `function unequip(address _tokenId)` and require it to be callable at any time by an ABT's owner as it ensures an owner's right to publicly disassociate themselves from what has been issued towards their account. - -### Exception handling - -Given the non-transferable between accounts property of ABTs, if a user's keys to an account or a contract get compromised or rotated, a user may lose the ability to associate themselves with the token. In some cases, this can be the desired effect. Therefore, ABT implementers should build re-issuance and revocation processes to enable recourse. We recommend implementing strictly decentralized, permissionless, and censorship-resistant re-issuance processes. - -But this document is deliberately abstaining from offering a standardized form of exception handling in cases where user keys are compromised or rotated. - -In cases where implementers want to make account-bound tokens shareable among different accounts, e.g., to avoid losing access when keys get compromised, we suggest issuing the account-bound token towards a contract's account that implements a multi-signature functionality. - -### Provenance Indexing - -ABTs can be indexed by tracking the emission of `event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)`. As with [EIP-721](./eip-721.md), transfers between two accounts are represented by `address from` and `address to` being non-zero addresses. Unequipping a token is represented through emitting a transfer with `address to` being set to the zero address. Mint operations where `address from` is set to zero don't exist. To avoid being spoofed by maliciously-implemented `event Transfer` emitting contracts, an indexer should ensure that the transaction's sender is equal to `event Transfer`'s `from` value. - -## Backwards Compatibility - -We have adopted the [EIP-165](./eip-165.md) and `ERC721Metadata` functions purposefully to create a high degree of backward compatibility with [EIP-721](./eip-721.md). We have deliberately used [EIP-721](./eip-721.md) terminology such as `function ownerOf(...)`, `function balanceOf(...)` to minimize the effort of familiarization for ABT implementers already familiar with, e.g., [EIP-20](./eip-20.md) or [EIP-721](./eip-721.md). For indexers, we've re-used the widely-implemented `event Transfer` event signature. - -## Reference Implementation - -You can find an implementation of this standard in [../assets/eip-4973](../assets/eip-4973/ERC4973-flat.sol). - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4973.md diff --git a/EIPS/eip-4974.md b/EIPS/eip-4974.md index 304bbebb25a0fe..44ce64e47e8efe 100644 --- a/EIPS/eip-4974.md +++ b/EIPS/eip-4974.md @@ -1,161 +1,7 @@ --- eip: 4974 -title: Ratings -description: An interface for assigning and managing numerical ratings -author: Daniel Tedesco (@dtedesco1) -discussions-to: https://ethereum-magicians.org/t/8805 -status: Review -type: Standards Track category: ERC -created: 2022-04-02 -requires: 165 +status: Moved --- -## Abstract - -This standard defines a standardized interface for assigning and managing numerical ratings on the Ethereum blockchain. This allows ratings to be codified within smart contracts and recognized by other applications, enabling a wide range of new use cases for tokens. - -## Motivation - -Traditionally, blockchain applications have focused on buying and selling digital assets. However, the asset-centric model has often been detrimental to community-based blockchain projects, as seen in the pay-to-play dynamics of many EVM-based games and DAOs in 2021. - -This proposal addresses this issue by allowing ratings to be assigned to contracts and wallets, providing a new composable primitive for blockchain applications. This allows for a diverse array of new use cases, such as: - -- Voting weight in a DAO: Ratings assigned using this standard can be used to determine the voting weight of members in a decentralized autonomous organization (DAO). For example, a DAO may assign higher ratings to members who have demonstrated a strong track record of contributing to the community, and use these ratings to determine the relative influence of each member in decision-making processes. - -- Experience points in a decentralized game ecosystem: Ratings can be used to track the progress of players in a decentralized game ecosystem, and to reward them for achieving specific milestones or objectives. For example, a game may use ratings to assign experience points to players, which can be used to unlock new content or abilities within the game. - -- Loyalty points for customers of a business: Ratings can be used to track the loyalty of customers to a particular business or service, and to reward them for their continued support. For example, a business may use ratings to assign loyalty points to customers, which can be redeemed for special offers or discounts. - -- Asset ratings for a decentralized insurance company: Ratings can be used to evaluate the risk profile of assets in a decentralized insurance company, and to determine the premiums and coverage offered to policyholders. For example, a decentralized insurance company may use ratings to assess the risk of different types of assets, and to provide lower premiums and higher coverage to assets with lower risk ratings. - -This standard is influenced by the [EIP-20](./eip-20.md) and [EIP-721](./eip-721.md) token standards and takes cues from each in its structure, style, and semantics. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Every compliant contract MUST implement the following interfaces: - -``` -// SPDX-License-Identifier: CC0 - -pragma solidity ^0.8.0; - -/// @title EIP-4974 Ratings -/// @dev See https://eips.ethereum.org/EIPS/EIP-4974 -/// Note: the EIP-165 identifier for this interface is #######. -/// Must initialize contracts with an `operator` address that is not `address(0)`. -interface IERC4974 /* is ERC165 */ { - - /// @dev Emits when operator changes. - /// MUST emit when `operator` changes by any mechanism. - /// MUST ONLY emit by `setOperator`. - event NewOperator(address indexed _operator); - - /// @dev Emits when operator issues a rating. - /// MUST emit when rating is assigned by any mechanism. - /// MUST ONLY emit by `rate`. - event Rating(address _rated, int8 _rating); - - /// @dev Emits when operator removes a rating. - /// MUST emit when rating is removed by any mechanism. - /// MUST ONLY emit by `remove`. - event Removal(address _removed); - - /// @notice Appoint operator authority. - /// @dev MUST throw unless `msg.sender` is `operator`. - /// MUST throw if `operator` address is either already current `operator` - /// or is the zero address. - /// MUST emit an `Appointment` event. - /// @param _operator New operator of the smart contract. - function setOperator(address _operator) external; - - /// @notice Rate an address. - /// MUST emit a Rating event with each successful call. - /// @param _rated Address to be rated. - /// @param _rating Total EXP tokens to reallocate. - function rate(address _rated, int8 _rating) external; - - /// @notice Remove a rating from an address. - /// MUST emit a Remove event with each successful call. - /// @param _removed Address to be removed. - function removeRating(address _removed) external; - - /// @notice Return a rated address' rating. - /// @dev MUST register each time `Rating` emits. - /// SHOULD throw for queries about the zero address. - /// @param _rated An address for whom to query rating. - /// @return int8 The rating assigned. - function ratingOf(address _rated) external view returns (int8); -} - -interface IERC165 { - /// @notice Query if a contract implements an interface. - /// @dev Interface identification is specified in EIP-165. This function - /// uses less than 30,000 gas. - /// @param interfaceID The interface identifier, as specified in EIP-165. - /// @return bool `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise. - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -## Rationale - -### Rating Assignment - -Ratings SHALL be at the sole discretion of the contract operator. This party may be a sports team coach or a multisig DAO wallet. We decide not to specify how governance occurs, but only *that* governance occurs. This allows for a wider range of potential use cases than optimizing for particular decision-making forms. - -This proposal standardizes a control mechanism to allocate community reputation without encouraging financialization of that recognition. While it does not ensure meritocracy, it opens the door. - -### Choice of int8 - -It's signed: Reviewers should be able to give neutral and negative ratings for the wallets and contracts they interact with. This is especially important for decentralized applications that may be subject to malicious actors. - -It's 8bit: The objective here is to keep ratings within some fathomably comparable range. Longer term, this could encourage easy aggregation of ratings, versus using larger numbers where users might employ a great variety of scales. - -### Rating Changes - -Ratings SHOULD allow rating updates by contract operators. If Bob has contributed greatly to the community, but then is caught stealing from Alice, the community may decide this should lower Bob's standing and influence in the community. Again, while this does not ensure an ethical standard within the community, it opens the door. - -Relatedly, ratings SHOULD allow removal of ratings to rescind a rating if the rater does not have confidence in their ability to rate effectively. - -### Interface Detection - -We chose Standard Interface Detection ([EIP-165](./eip-165.md)) to expose the interfaces that a compliant smart contract supports. - -### Metadata Choices - -We have required `name` and `description` functions in the metadata extension. `name` common among major standards for blockchain-based primitives. We included a `description` function that may be helpful for games or other applications with multiple ratings systems. - -We remind implementation authors that the empty string is a valid response to `name` and `description` if you protest to the usage of this mechanism. We also remind everyone that any smart contract can use the same name and description as your contract. How a client may determine which ratings smart contracts are well-known (canonical) is outside the scope of this standard. - -### Drawbacks - -One potential drawback of using this standard is that ratings are subjective and may not always accurately reflect the true value or quality of a contract or wallet. However, the standard provides mechanisms for updating and removing ratings, allowing for flexibility and evolution over time. - -Users identified in the motivation section have a strong need to identify how a contract or community evaluates another. While some users may be proud of ratings they receive, others may rightly or wrongly receive negative ratings from certain contracts. Negative ratings may allow for nefarious activities such as bullying and discrimination. We implore all implementers to be mindful of the consequences of any ratings systems they create with this standard. - -## Backwards Compatibility - -We have adopted the `name` semantics from the EIP-20 and EIP-721 specifications. - -## Reference Implementation - -A reference implementation of this standard can be found in the assets folder. - - -## Security Considerations - -One potential security concern with this standard is the risk of malicious actors assigning false or misleading ratings to contracts or wallets. This could be used to manipulate voting weights in a DAO, or to deceive users into making poor decisions based on inaccurate ratings. - -To address this concern, the standard includes mechanisms for updating and removing ratings, allowing for corrections to be made in cases of false or misleading ratings. Additionally, the use of a single operator address to assign and update ratings provides a single point of control, which can be used to enforce rules and regulations around the assignment of ratings. - -Another potential security concern is the potential for an attacker to gain control of the operator address and use it to manipulate ratings for their own benefit. To mitigate this risk, it is recommended that the operator address be carefully managed and protected, and that multiple parties be involved in its control and oversight. - -Overall, the security of compliant contracts will depend on the careful management and protection of the operator address, as well as the development of clear rules and regulations around the assignment of ratings. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4974.md diff --git a/EIPS/eip-4987.md b/EIPS/eip-4987.md index 3b44d099a50ede..1677e968b51ebb 100644 --- a/EIPS/eip-4987.md +++ b/EIPS/eip-4987.md @@ -1,269 +1,7 @@ --- eip: 4987 -title: Held token interface -description: Interface to query ownership and balance of held tokens -author: Devin Conley (@devinaconley) -discussions-to: https://ethereum-magicians.org/t/eip-4987-held-token-standard-nfts-defi/7117 -status: Review -type: Standards Track category: ERC -created: 2021-09-21 -requires: 20, 165, 721, 1155 +status: Moved --- -## Abstract - -The proposed standard defines a lightweight interface to expose functional ownership and balances of held tokens. A held token is a token owned by a contract. This standard may be implemented by smart contracts which hold [EIP-20](./eip-20.md), [EIP-721](./eip-721.md), or [EIP-1155](./eip-1155.md) tokens and is intended to be consumed by both on-chain and off-chain systems that rely on ownership and balance verification. - -## Motivation - -As different areas of crypto (DeFi, NFTs, etc.) converge and composability improves, there will more commonly be a distinction between the actual owner (likely a contract) and the functional owner (likely a user) of a token. Currently, this results in a conflict between mechanisms that require token deposits and systems that rely on those tokens for ownership or balance verification. - -This proposal aims to address that conflict by providing a standard interface for token holders to expose ownership and balance information. This will allow users to participate in these DeFi mechanisms without giving up existing token utility. Overall, this would greatly increase interoperability across systems, benefiting both users and protocol developers. - -Example implementers of this ERC standard include - -- staking or farming contracts -- lending pools -- time lock or vesting vaults -- fractionalized NFT contracts -- smart contract wallets - -Example consumers of this ERC standard include - -- governance systems -- gaming -- PFP verification -- art galleries or showcases -- token based membership programs - -## Specification - -Smart contracts implementing the `ERC20` held token standard MUST implement all of the functions in the `IERC20Holder` interface. - -Smart contracts implementing the `ERC20` held token standard MUST also implement `ERC165` and return true when the interface ID `0x74c89d54` is passed. - -```solidity -/** - * @notice the ERC20 holder standard provides a common interface to query - * token balance information - */ -interface IERC20Holder is IERC165 { - /** - * @notice emitted when the token is transferred to the contract - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenAmount held token amount - */ - event Hold( - address indexed owner, - address indexed tokenAddress, - uint256 tokenAmount - ); - - /** - * @notice emitted when the token is released back to the user - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenAmount held token amount - */ - event Release( - address indexed owner, - address indexed tokenAddress, - uint256 tokenAmount - ); - - /** - * @notice get the held balance of the token owner - * @dev should throw for invalid queries and return zero for no balance - * @param tokenAddress held token address - * @param owner functional token owner - * @return held token balance - */ - function heldBalanceOf(address tokenAddress, address owner) - external - view - returns (uint256); -} - -``` - -Smart contracts implementing the `ERC721` held token standard MUST implement all of the functions in the `IERC721Holder` interface. - -Smart contracts implementing the `ERC721` held token standard MUST also implement `ERC165` and return true when the interface ID `0x16b900ff` is passed. - -```solidity -/** - * @notice the ERC721 holder standard provides a common interface to query - * token ownership and balance information - */ -interface IERC721Holder is IERC165 { - /** - * @notice emitted when the token is transferred to the contract - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenId held token ID - */ - event Hold( - address indexed owner, - address indexed tokenAddress, - uint256 indexed tokenId - ); - - /** - * @notice emitted when the token is released back to the user - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenId held token ID - */ - event Release( - address indexed owner, - address indexed tokenAddress, - uint256 indexed tokenId - ); - - /** - * @notice get the functional owner of a held token - * @dev should throw for invalid queries and return zero for a token ID that is not held - * @param tokenAddress held token address - * @param tokenId held token ID - * @return functional token owner - */ - function heldOwnerOf(address tokenAddress, uint256 tokenId) - external - view - returns (address); - - /** - * @notice get the held balance of the token owner - * @dev should throw for invalid queries and return zero for no balance - * @param tokenAddress held token address - * @param owner functional token owner - * @return held token balance - */ - function heldBalanceOf(address tokenAddress, address owner) - external - view - returns (uint256); -} -``` - -Smart contracts implementing the `ERC1155` held token standard MUST implement all of the functions in the `IERC1155Holder` interface. - -Smart contracts implementing the `ERC1155` held token standard MUST also implement `ERC165` and return true when the interface ID `0xced24c37` is passed. - -```solidity -/** - * @notice the ERC1155 holder standard provides a common interface to query - * token balance information - */ -interface IERC1155Holder is IERC165 { - /** - * @notice emitted when the token is transferred to the contract - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenId held token ID - * @param tokenAmount held token amount - */ - event Hold( - address indexed owner, - address indexed tokenAddress, - uint256 indexed tokenId, - uint256 tokenAmount - ); - - /** - * @notice emitted when the token is released back to the user - * @param owner functional token owner - * @param tokenAddress held token address - * @param tokenId held token ID - * @param tokenAmount held token amount - */ - event Release( - address indexed owner, - address indexed tokenAddress, - uint256 indexed tokenId, - uint256 tokenAmount - ); - - /** - * @notice get the held balance of the token owner - * @dev should throw for invalid queries and return zero for no balance - * @param tokenAddress held token address - * @param owner functional token owner - * @param tokenId held token ID - * @return held token balance - */ - function heldBalanceOf( - address tokenAddress, - address owner, - uint256 tokenId - ) external view returns (uint256); -} -``` - -## Rationale - -This interface is designed to be extremely lightweight and compatible with any existing token contract. Any token holder contract likely already stores all relevant information, so this standard is purely adding a common interface to expose that data. - -The token address parameter is included to support contracts that can hold multiple token contracts simultaneously. While some contracts may only hold a single token address, this is more general to either scenario. - -Separate interfaces are proposed for each token type (EIP-20, EIP-721, EIP-1155) because any contract logic to support holding these different tokens is likely independent. In the scenario where a single contract does hold multiple token types, it can simply implement each appropriate held token interface. - - -## Backwards Compatibility - -Importantly, the proposed specification is fully compatible with all existing EIP-20, EIP-721, and EIP-1155 token contracts. - -Token holder contracts will need to be updated to implement this lightweight interface. - -Consumer of this standard will need to be updated to respect this interface in any relevant ownership logic. - - -## Reference Implementation - -A full example implementation including [interfaces](../assets/eip-4987/IERC721Holder.sol), a vault [token holder](../assets/eip-4987/Vault.sol), and a [consumer](../assets/eip-4987/Consumer.sol), can be found at `assets/eip-4987/`. - -Notably, consumers of the `IERC721Holder` interface can do a chained lookup for the owner of any specific token ID using the following logic. - -```solidity - /** - * @notice get the functional owner of a token - * @param tokenId token id of interest - */ - function getOwner(uint256 tokenId) external view returns (address) { - // get raw owner - address owner = token.ownerOf(tokenId); - - // if owner is not contract, return - if (!owner.isContract()) { - return owner; - } - - // check for token holder interface support - try IERC165(owner).supportsInterface(0x16b900ff) returns (bool ret) { - if (!ret) return owner; - } catch { - return owner; - } - - // check for held owner - try IERC721Holder(owner).heldOwnerOf(address(token), tokenId) returns (address user) { - if (user != address(0)) return user; - } catch {} - - return owner; - } -``` - - -## Security Considerations - -Consumers of this standard should be cautious when using ownership information from unknown contracts. A bad actor could implement the interface, but report invalid or malicious information with the goal of manipulating a governance system, game, membership program, etc. - -Consumers should also verify the overall token balance and ownership of the holder contract as a sanity check. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-4987.md diff --git a/EIPS/eip-5000.md b/EIPS/eip-5000.md index 26804d486a18b9..5a87df3a007544 100644 --- a/EIPS/eip-5000.md +++ b/EIPS/eip-5000.md @@ -4,7 +4,7 @@ title: MULDIV instruction description: Introduce a new instruction to perform x * y / z in 512-bit precision author: Harikrishnan Mulackal (@hrkrshnn), Alex Beregszaszi (@axic), Paweł Bylica (@chfast) discussions-to: https://ethereum-magicians.org/t/muldiv-instruction/9930 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-03-14 @@ -12,7 +12,7 @@ created: 2022-03-14 ## Abstract -Introduce a new instruction, `MULDIV(x, y, z)`, to perform `((x * y) / z) % 2**256` in 512-bit precision. `z = 0` is a special case for `(x * y) % 2**256`. +Introduce a new instruction, `MULDIV(x, y, z)`, to perform `((x * y) / z) % 2**256` in 512-bit precision. `z = 0` is a special case for `(x * y) / 2**256`. ## Motivation @@ -76,7 +76,7 @@ The order of arguments matches `addmod` and `mulmod`. ## Backwards Compatibility -This is a new instruction not present pior. +This is a new instruction not present prior. ## Test Cases diff --git a/EIPS/eip-5003.md b/EIPS/eip-5003.md index b1112da454aa13..d42d650dd1276d 100644 --- a/EIPS/eip-5003.md +++ b/EIPS/eip-5003.md @@ -4,7 +4,7 @@ title: Insert Code into EOAs with AUTHUSURP description: Allow migrating away from ECDSA by deploying code in place of an externally owned account. author: Dan Finlay (@danfinlay), Sam Wilson (@SamWilsn) discussions-to: https://ethereum-magicians.org/t/eip-5003-auth-usurp-publishing-code-at-an-eoa-address/8979 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-03-26 diff --git a/EIPS/eip-5005.md b/EIPS/eip-5005.md index b37f5ff1e219e0..7accb63abae1da 100644 --- a/EIPS/eip-5005.md +++ b/EIPS/eip-5005.md @@ -1,233 +1,7 @@ --- eip: 5005 -title: Zodiac Modular Accounts -description: Composable interoperable programmable accounts -author: Auryn Macmillan (@auryn-macmillan), Kei Kreutler (@keikreutler) -discussions-to: https://ethereum-magicians.org/t/eip-zodiac-a-composable-design-philosophy-for-daos/8963 -status: Review -type: Standards Track category: ERC -created: 2022-04-14 -requires: 165 +status: Moved --- -## Abstract -This EIP standardizes interfaces for composable and interoperable tooling for programmable Ethereum accounts. These interfaces separate contract accounts ("avatars") from their authentication and execution logic ("guards" and "modules"). Avatars implement the `IAvatar` interface, and guards implement the `IGuard` interface. Modules may take any form. - -## Motivation -Currently, most programmable accounts (like DAO tools and frameworks) are built as monolithic systems where the authorization and execution logic are coupled, either within the same contract or in a tightly integrated system of contracts. This needlessly inhibits the flexibility of these tools and encourages platform lock-in via high switching costs. - -By using the this EIP standard to separate concerns (decoupling authentication and execution logic), users are able to: - -1. Enable flexible, module-based control of programmable accounts -2. Easily switch between tools and frameworks without unnecessary overhead. -3. Enable multiple control mechanism in parallel. -4. Enable cross-chain / cross-layer governance. -5. Progressively decentralize their governance as their project and community matures. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -This EIP consists of four key concepts: - -- **Avatars** are programmable Ethereum accounts. Avatars are the address that holds balances, owns systems, executes transaction, is referenced externally, and ultimately represents your DAO. Avatars MUST implement the `IAvatar` interface. -- **Modules** are contracts enabled by an avatar that implement some execution logic. -- **Modifiers** are contracts that sit between modules and avatars to modify the module's behavior. For example, they might enforce a delay on all functions a module attempts to execute or limit the scope of transactions that can be initiated by the module. Modifiers MUST implement the `IAvatar` interface. -- **Guards** are contracts that MAY be enabled on modules or modifiers and implement pre- or post-checks on each transaction executed by those modules or modifiers. This allows avatars to do things like limit the scope of addresses and functions that a module or modifier can call or ensure a certain state is never changed by a module or modifier. Guards MUST expose the `IGuard` interface. Modules, modifiers, and avatars that wish to be guardable MUST inherit `Guardable`, MUST call `checkTransaction()` before triggering execution on their target, and MUST call `checkAfterExecution()` after execution is complete. - -```solidity -/// @title Avatar - A contract that manages modules that can execute transactions via this contract. - -pragma solidity >=0.7.0 <0.9.0; - -import "./Enum.sol"; - - -interface IAvatar { - event EnabledModule(address module); - event DisabledModule(address module); - event ExecutionFromModuleSuccess(address indexed module); - event ExecutionFromModuleFailure(address indexed module); - - /// @dev Enables a module on the avatar. - /// @notice Can only be called by the avatar. - /// @notice Modules should be stored as a linked list. - /// @notice Must emit EnabledModule(address module) if successful. - /// @param module Module to be enabled. - function enableModule(address module) external; - - /// @dev Disables a module on the avatar. - /// @notice Can only be called by the avatar. - /// @notice Must emit DisabledModule(address module) if successful. - /// @param prevModule Address that pointed to the module to be removed in the linked list - /// @param module Module to be removed. - function disableModule(address prevModule, address module) external; - - /// @dev Allows a Module to execute a transaction. - /// @notice Can only be called by an enabled module. - /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. - /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. - /// @param to Destination address of module transaction. - /// @param value Ether value of module transaction. - /// @param data Data payload of module transaction. - /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. - function execTransactionFromModule( - address to, - uint256 value, - bytes memory data, - Enum.Operation operation - ) external returns (bool success); - - /// @dev Allows a Module to execute a transaction and return data - /// @notice Can only be called by an enabled module. - /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. - /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. - /// @param to Destination address of module transaction. - /// @param value Ether value of module transaction. - /// @param data Data payload of module transaction. - /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. - function execTransactionFromModuleReturnData( - address to, - uint256 value, - bytes memory data, - Enum.Operation operation - ) external returns (bool success, bytes memory returnData); - - /// @dev Returns if an module is enabled - /// @return True if the module is enabled - function isModuleEnabled(address module) external view returns (bool); - - /// @dev Returns array of modules. - /// @param start Start of the page. - /// @param pageSize Maximum number of modules that should be returned. - /// @return array Array of modules. - /// @return next Start of the next page. - function getModulesPaginated(address start, uint256 pageSize) - external - view - returns (address[] memory array, address next); -} -``` - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -import "./Enum.sol"; - -interface IGuard { - function checkTransaction( - address to, - uint256 value, - bytes memory data, - Enum.Operation operation, - uint256 safeTxGas, - uint256 baseGas, - uint256 gasPrice, - address gasToken, - address payable refundReceiver, - bytes memory signatures, - address msgSender - ) external; - - function checkAfterExecution(bytes32 txHash, bool success) external; -} - -``` - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -import "./Enum.sol"; -import "./BaseGuard.sol"; - -/// @title Guardable - A contract that manages fallback calls made to this contract -contract Guardable { - address public guard; - - event ChangedGuard(address guard); - - /// `guard_` does not implement IERC165. - error NotIERC165Compliant(address guard_); - - /// @dev Set a guard that checks transactions before execution. - /// @param _guard The address of the guard to be used or the 0 address to disable the guard. - function setGuard(address _guard) external { - if (_guard != address(0)) { - if (!BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId)) - revert NotIERC165Compliant(_guard); - } - guard = _guard; - emit ChangedGuard(guard); - } - - function getGuard() external view returns (address _guard) { - return guard; - } -} -``` - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -import "./Enum.sol"; -import "./IERC165.sol"; -import "./IGuard.sol"; - -abstract contract BaseGuard is IERC165 { - function supportsInterface(bytes4 interfaceId) - external - pure - override - returns (bool) - { - return - interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a - interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 - } - - /// @dev Module transactions only use the first four parameters: to, value, data, and operation. - /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. - function checkTransaction( - address to, - uint256 value, - bytes memory data, - Enum.Operation operation, - uint256 safeTxGas, - uint256 baseGas, - uint256 gasPrice, - address gasToken, - address payable refundReceiver, - bytes memory signatures, - address msgSender - ) external virtual; - - function checkAfterExecution(bytes32 txHash, bool success) external virtual; -} -``` - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -/// @title Enum - Collection of enums - -contract Enum { - - enum Operation {Call, DelegateCall} - -} -``` - -## Rationale -The interface defined in this standard is designed to be mostly compatible with most popular programmable accounts in use right now, to minimize the need for changes to existing tooling. - -## Backwards Compatibility -No backward compatibility issues are introduced by this standard. - -## Security Considerations -There are some considerations that module developers and users should take into account: -1. **Modules have absolute control:** Modules have absolute control over any avatar on which they are enabled, so any module implementation should be treated as security critical and users should be vary cautious about enabling new modules. ONLY ENABLE MODULES THAT YOU TRUST WITH THE FULL VALUE OF THE AVATAR. -2. **Race conditions:** A given avatar may have any number of modules enabled, each with unilateral control over the safe. In such cases, there may be race conditions between different modules and/or other control mechanisms. -3. **Don't brick your avatar:** There are no safeguards to stop you adding or removing modules. If you remove all of the modules that let you control an avatar, the avatar will cease to function and all funds will be stuck. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5005.md diff --git a/EIPS/eip-5006.md b/EIPS/eip-5006.md old mode 100755 new mode 100644 index 996afb18a72154..7780c11e3eacce --- a/EIPS/eip-5006.md +++ b/EIPS/eip-5006.md @@ -1,157 +1,7 @@ --- eip: 5006 -title: Rental NFT, NFT User Extension -description: Add a user role with restricted permissions to EIP-1155 tokens -author: Lance (@LanceSnow), Anders (@0xanders), Shrug -discussions-to: https://ethereum-magicians.org/t/eip5006-erc-1155-usage-rights-extension/8941 -status: Last Call -last-call-deadline: 2022-08-01 -type: Standards Track category: ERC -created: 2022-04-12 -requires: 165, 1155 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-1155](./eip-1155.md). It proposes an additional role (`user`) which can be granted to addresses that represent a `user` of the assets rather than an `owner`. - -## Motivation - -Like [EIP-721](./eip-721.md), [EIP-1155](./eip-1155.md) tokens may have utility of some kind. The people who “use” the token may be different than the people who own it (such as in a rental). Thus, it would be useful to have separate roles for the “owner” and the “user” so that the “user” would not be able to take actions that the owner could (for example, transferring ownership). - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.0; - -interface IERC5006 { - struct UserRecord { - uint256 tokenId; - address owner; - uint64 amount; - address user; - uint64 expiry; - } - - /** - * @dev Emitted when permission for `user` to use `amount` of `tokenId` token owned by `owner` - * until `expiry` are given. - */ - event CreateUserRecord( - uint256 recordId, - uint256 tokenId, - uint64 amount, - address owner, - address user, - uint64 expiry - ); - - /** - * @dev Emitted when record of `recordId` are deleted. - */ - event DeleteUserRecord(uint256 recordId); - - /** - * @dev Returns the usable amount of `tokenId` tokens by `account`. - */ - function usableBalanceOf(address account, uint256 tokenId) - external - view - returns (uint256); - - /** - * @dev Returns the amount of frozen tokens of token type `id` by `account`. - */ - function frozenBalanceOf(address account, uint256 tokenId) - external - view - returns (uint256); - - /** - * @dev Returns the `UserRecord` of `recordId`. - */ - function userRecordOf(uint256 recordId) - external - view - returns (UserRecord memory); - - /** - * @dev Gives permission to `user` to use `amount` of `tokenId` token owned by `owner` until `expiry`. - * - * Emits a {CreateUserRecord} event. - * - * Requirements: - * - * - If the caller is not `owner`, it must be have been approved to spend ``owner``'s tokens - * via {setApprovalForAll}. - * - `owner` must have a balance of tokens of type `id` of at least `amount`. - * - `user` cannot be the zero address. - * - `amount` must be greater than 0. - * - `expiry` must after the block timestamp. - */ - function createUserRecord( - address owner, - address user, - uint256 tokenId, - uint64 amount, - uint64 expiry - ) external returns (uint256); - - /** - * @dev Atomically delete `record` of `recordId` by the caller. - * - * Emits a {DeleteUserRecord} event. - * - * Requirements: - * - * - the caller must have allowance. - */ - function deleteUserRecord(uint256 recordId) external; -} - -``` - -The `supportsInterface` method MUST return `true` when called with `0xc26d96cc`. - -## Rationale - -This model is intended to facilitate easy implementation. The following are some problems that are solved by this standard: - -### Clear Rights Assignment - -With Dual “owner” and “user” roles, it becomes significantly easier to manage what lenders and borrowers can and cannot do with the NFT (in other words, their rights).  For example, for the right to transfer ownership, the project simply needs to check whether the address taking the action represents the owner or the user and prevent the transaction if it is the user.  Additionally, owners can control who the user is and it is easy for other projects to assign their own rights to either the owners or the users. - -### Easy Third-Party Integration - -In the spirit of permissionless interoperability, this standard makes it easier for third-party protocols to manage NFT usage rights without permission from the NFT issuer or the NFT application. Once a project has adopted the additional `user` role, any other project can directly interact with these features and implement their own type of transaction. For example, a PFP NFT using this standard can be integrated into both a rental platform where users can rent the NFT for 30 days AND, at the same time, a mortgage platform where users can use the NFT while eventually buying ownership of the NFT with installment payments. This would all be done without needing the permission of the original PFP project. - -## Backwards Compatibility - -As mentioned in the specifications section, this standard can be fully ERC compatible by adding an extension function set, and there are no conflicts between [EIP-5006](./eip-5006.md) and EIP-1155. - -In addition, new functions introduced in this standard have many similarities with the existing functions in EIP-1155. This allows developers to easily adopt the standard quickly. - -## Test Cases - -Test cases are included in [test.js](../assets/eip-5006/test/test.ts). - -Run in terminal: -1. ```cd ../assets/eip-5006``` -1. ```npm install``` -1. ```npx hardhat test``` - -## Reference Implementation - -See [`ERC5006.sol`](../assets/eip-5006/contracts/ERC5006.sol). - -## Security Considerations - -This EIP standard can completely protect the rights of the owner, the owner can change the NFT user, the user can not transfer the NFT. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5006.md diff --git a/EIPS/eip-5007.md b/EIPS/eip-5007.md old mode 100755 new mode 100644 index 007d2a65e756c0..f3125d18516401 --- a/EIPS/eip-5007.md +++ b/EIPS/eip-5007.md @@ -1,142 +1,7 @@ --- eip: 5007 -title: Time NFT, EIP-721 Time Extension -description: Add start time and end time to EIP-721 tokens. -author: Anders (@0xanders), Lance (@LanceSnow), Shrug -discussions-to: https://ethereum-magicians.org/t/eip-5007-eip-721-time-extension/8924 -status: Last Call -last-call-deadline: 2022-09-25 -type: Standards Track category: ERC -created: 2022-04-13 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes some additional functions (`startTime`, `endTime`) to help with on-chain time management. - -## Motivation - -Some NFTs have a defined usage period and cannot be used outside of that period. With traditional NFTs that do not include time information, if you want to mark a token as invalid or enable it at a specific time, you need to actively submit a transaction—a process both cumbersome and expensive. - -Some existing NFTs contain time functions, but their interfaces are not consistent, so it is difficult to develop third-party platforms for them. - -By introducing these functions (`startTime`, `endTime`), it is possible to enable and disable NFTs automatically on chain. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -```solidity -/** - * @dev the EIP-165 identifier for this interface is 0x7a0cdf92. - */ -interface IERC5007 /* is IERC721 */ { - /** - * @dev Returns the start time of the NFT as a UNIX timestamp. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function startTime(uint256 tokenId) external view returns (int64); - - /** - * @dev Returns the end time of the NFT as a UNIX timestamp. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function endTime(uint256 tokenId) external view returns (int64); - -} -``` - -The **composable extension** is OPTIONAL for this standard. This allows your NFT to be minted from an existing NFT or to merge two NFTs into one NFT. - -```solidity -/** - * @dev the EIP-165 identifier for this interface is 0x620063db. - */ -interface IERC5007Composable /* is IERC5007 */ { - /** - * @dev Returns the ancestor token id of the NFT. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function rootTokenId(uint256 tokenId) external view returns (uint256); - - /** - * @dev Mint a new token from an old token. - * The rootTokenId of the new token is the same as the rootTokenId of the old token - * - * Requirements: - * - * - `oldTokenId` must exist. - * - `newTokenId` must not exist. - * - `newTokenOwner` cannot be the zero address. - * - `newTokenStartTime` require(oldTokenStartTime < newTokenStartTime && newTokenStartTime <= oldTokenEndTime) - */ - function split( - uint256 oldTokenId, - uint256 newTokenId, - address newTokenOwner, - int64 newTokenStartTime - ) external; - - /** - * @dev Merge the first token and second token into the new token. - * - * Requirements: - * - * - `firstTokenId` must exist. - * - `secondTokenId` must exist. require((firstToken.endTime + 1) == secondToken.startTime) - * - `newTokenOwner` cannot be the zero address. - * - `newTokenId` must not exist. - */ - function merge( - uint256 firstTokenId, - uint256 secondTokenId, - address newTokenOwner, - uint256 newTokenId - ) external; -} -``` - -## Rationale - -### Time Data Type - -The max value of `int64` is 9,223,372,036,854,775,807. As a timestamp, 9,223,372,036,854,775,807 is about year 292,471,210,648. `uint256` is too big for C, C++, Java, Go, etc, and `int64` is natively supported by mainstream programming languages. - -## Backwards Compatibility - -This standard is fully EIP-721 compatible. - -## Test Cases - -Test cases are included in [test.js](../assets/eip-5007/test/test.js). - -Run in terminal: - -```shell -cd ../assets/eip-5007 -npm install -truffle test -``` - -## Reference Implementation - -See [`ERC5007.sol`](../assets/eip-5007/contracts/ERC5007.sol). - -## Security Considerations - -No security issues found. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5007.md diff --git a/EIPS/eip-5008.md b/EIPS/eip-5008.md old mode 100755 new mode 100644 index 2395dda2a321a2..8d6d0347cf4b45 --- a/EIPS/eip-5008.md +++ b/EIPS/eip-5008.md @@ -1,69 +1,7 @@ --- eip: 5008 -title: EIP-721 Nonce Extension -description: Add a `nonce` function to EIP-721. -author: Anders (@0xanders), Lance (@LanceSnow), Shrug -discussions-to: https://ethereum-magicians.org/t/eip5008-eip-721-nonce-and-metadata-update-extension/8925 -status: Review -type: Standards Track category: ERC -created: 2022-04-10 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes adding a `nonce` function to EIP-721 tokens. - -## Motivation - -Some orders of NFT marketplaces have been attacked and the NFTs sold at a lower price than the current market floor price. This can happen when users transfer an NFT to another wallet and, later, back to the original wallet. This reactivates the order, which may list the token at a much lower price than the owner would have intended. - -This EIP proposes adding a `nonce` property to EIP-721 tokens, and the `nonce` will be changed when a token is transferred. If a `nonce` is added to an order, the order can be checked to avoid attacks. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -```solidity -interface IERC5008 /* is IERC165 */ { - /// @notice Get the nonce of an NFT - /// Throws if `tokenId` is not a valid NFT - /// @param tokenId The id of the NFT - /// @return The nonce of the NFT - function nonce(uint256 tokenId) external view returns(uint256); -} -``` -The `nonce(uint256 tokenId)` function MUST be implemented as `view`. - -The `supportsInterface` method MUST return `true` when called with `0xce03fdab`. - -## Rationale - -At first `transferCount` was considered as function name, but there may some case to change the `nonce` besides transfer, such as important properties changed, then we changed `transferCount` to `nonce`. - -## Backwards Compatibility - -This standard is compatible with EIP-721. - -## Test Cases - -Test cases are included in [test.js](../assets/eip-5008/test/test.ts). - -Run: -```sh -cd ../assets/eip-5008 -npm install -npx hardhat test ./test/test.ts -``` - -## Reference Implementation - -See [`ERC5008.sol`](../assets/eip-5008/contracts/ERC5008.sol). - -## Security Considerations - -No security issues found. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5008.md diff --git a/EIPS/eip-5018.md b/EIPS/eip-5018.md index 8f1bc96acc30e5..603e39911cd48a 100644 --- a/EIPS/eip-5018.md +++ b/EIPS/eip-5018.md @@ -1,161 +1,7 @@ --- eip: 5018 -title: Filesystem-like Interface for Contracts -description: An interface to provide access to binary objects similar to filesystems. -author: Qi Zhou (@qizhou) -discussions-to: https://ethereum-magicians.org/t/eip-5018-directory-standard/8958 -status: Review -type: Standards Track category: ERC -created: 2022-04-18 +status: Moved --- - -## Abstract - -The following standardizes an API for directories and files within smart contracts, similar to traditional filesystems. -This standard provides basic functionality to read/write binary objects of any size, as well as allow reading/writing chunks of the object if the object is too large to fit in a single transaction. - -## Motivation - -A standard interface allows any binary objects on EVM-based blockchain to be re-used by other dApps. - -With [EIP-4804](./eip-4804.md), we are able to locate a Web3 resource on blockchain using HTTP-style URIs. One application of Web3 resources are web contents that are referenced within a directory using relative paths such as HTML/SVG. This standard proposes a contract-based directory to simplify the mapping between local web contents and on-chain web contents. Further, with relative paths referenced in the web contents and EIP-4804, the users will have a consistent view of the web contents locally and on-chain. - -## Specification - -### Directory - -#### Methods - -##### write - -Writes binary `data` to the file `name` in the directory by an account with write permission. - -``` -function write(bytes memory name, bytes memory data) external payable -``` - -##### read - -Returns the binary `data` from the file `name` in the directory and existence of the file. - -``` -function read(bytes memory name) external view returns (bytes memory data, bool exist) -``` - -##### fallback read - -Returns the binary `data` from the file `prefixedName` (prefixed with `/`) in the directory. - -``` -fallback(bytes calldata prefixedName) external returns (bytes memory data) -``` - -##### size - -Returns the size of the `data` from the file `name` in the directory and the number of chunks of the data. - -``` -function size(bytes memory name) external view returns (uint256 size, uint256 chunks) -``` - -##### remove - -Removes the file `name` in the directory and returns the number of chunks removed (0 means the file does not exist) by an account with write permission. - -``` -function remove(bytes memory name) external returns (uint256 numOfChunksRemoved) -``` - -##### countChunks - -Returns the number of chunks of the file `name`. - -``` -function countChunks(bytes memory name) external view returns (uint256 numOfChunks); -``` - -##### writeChunk - -Writes a chunk of data to the file by an account with write permission. The write will fail if `chunkId > numOfChunks`, i.e., the write must append the file or replace the existing chunk. - -``` - function writeChunk(bytes memory name, uint256 chunkId, bytes memory chunkData) external payable; -``` - -##### readChunk - -Returns the chunk data of the file `name` and the existence of the chunk. - -``` -function readChunk(bytes memory name, uint256 chunkId) external view returns (bytes memory chunkData, bool exist); -``` - -##### chunkSize - -Returns the size of a chunk of the file `name` and the existence of the chunk. - -``` -function chunkSize(bytes memory name, uint256 chunkId) external view returns (uint256 chunkSize, bool exist); -``` - -##### removeChunk - -Removes a chunk of the file `name` and returns `false` if such chunk does not exist. The method should be called by an account with write permission. - -``` -function removeChunk(bytes memory name, uint256 chunkId) external returns (bool exist); -``` - -##### truncate - -Removes the chunks of the file `name` in the directory from the given `chunkId` and returns the number of chunks removed by an account with write permission. When `chunkId = 0`, the method is essentially the same as `remove()`. - -``` -function truncate(bytes memory name, uint256 chunkId) external returns (uint256 numOfChunksRemoved); -``` - -##### getChunkHash - -Returns the hash value of the chunk data. - -``` -function getChunkHash(bytes memory name, uint256 chunkId) external view returns (bytes32); -``` - -## Rationale - -One issue of uploading the web contents to the blockchain is that the web contents may be too large to fit into a single transaction. As a result, the standard provides chunk-based operations so that uploading a content can be split into several transactions. Meanwhile, the read operation can be done in a single transaction, i.e., with a single Web3 URL defined in EIP-4804. - -### Interactions Between Unchunked/Chunked Functions - -`read` method should return the concatenated chunked data written by `writeChunk` method. The following gives some examples of the interactions: - -- `read("hello.txt")` => "" (file is empty) -- `writeChunk("hello.txt", 0, "abc")` will succeed -- `read("hello.txt")` => "abc" -- `writeChunk("hello.txt", 1, "efg")` will succeed -- `read("hello.txt")` => "abcefg" -- `writeChunk("hello.txt", 0, "aaa")` will succeed (replace chunk 0's data) -- `read("hello.txt")` => "aaaefg" -- `writeChunk("hello.txt", 3, "hij")` will fail because the operation is not replacement or append. - -With `writeChunk` method, we allow writing a file with external data that exceeds the current calldata limit (e.g., 1.8MB now), and it is able to read the whole file in a single `read` method (which is friendly for large web objects such as HTML/SVG/PNG/JPG, etc). - -For `write` method, calling a `write` method will replace all data chunks of the file with `write` method data, and one implementation can be: - -1. `writeChunk(filename, chunkId=0, data_from_write)` to chunk 0 with the same `write` method data; and -2. `truncate(filename, chunkId=1)`, which will remove the rest chunks. - -## Backwards Compatibility - -No backwards compatibility issues were identified. - -## Security Considerations - -No security considerations were found. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5018.md diff --git a/EIPS/eip-5023.md b/EIPS/eip-5023.md index c3e36b57e2b83c..5f6ade7fc343bd 100644 --- a/EIPS/eip-5023.md +++ b/EIPS/eip-5023.md @@ -1,169 +1,7 @@ --- eip: 5023 -title: Shareable Non-Fungible Token -description: An interface for creating value-holding tokens shareable by multiple owners -author: Jarno Marttila (@yaruno), Martin Moravek (@mmartinmo) -discussions-to: https://ethereum-magicians.org/t/new-nft-concept-shareable-nfts/8681 -status: Final -type: Standards Track category: ERC -created: 2022-01-28 -requires: 165 +status: Moved --- -## Abstract - -This EIP standardizes an interface for non-fungible value-holding shareable tokens. Shareability is accomplished by minting copies of existing tokens for new recipients. Sharing and associated events allow the construction of a graph describing who has shared what to which party. - - -## Motivation - -NFT standards such as [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) have been developed to standardize scarce digital resources. However, many non-fungible digital resources need not be scarce. - -We have attempted to capture positive externalities in ecosystems with new types of incentive mechanisms that exhibit anti-rival logic, serve as an unit of accounting and function as medium of sharing. We envision that shareable tokens can work both as incentives but also as representations of items that are typically digital in their nature and gain more value as they are shared. - -These requirements have set us to define shareable NFTs and more specifically a variation of shareable NFTs called non-transferable shareable NFTs. These shareable NFTs can be “shared” in the same way digital goods can be shared, at an almost zero technical transaction cost. We have utilized them to capture anti-rival value in terms of accounting positive externalities in an economic system. - -Typical NFT standards such as EIP-721 and EIP-1155 do not define a sharing modality. Instead ERC standards define interfaces for typical rival use cases such as token minting and token transactions that the NFT contract implementations should fulfil. The ‘standard contract implementations' may extend the functionalities of these standards beyond the definition of interfaces. The shareable tokens that we have designed and developed in our experiments are designed to be token standard compatible at the interface level. However the implementation of token contracts may contain extended functionalities to match the requirements of the experiments such as the requirement of 'shareability'. In reflection to standard token definitions, shareability of a token could be thought of as re-mintability of an existing token to another party while retaining the original version of it. - -Sharing is an interesting concept as it can be thought and perceived in different ways. For example, when we talk about sharing we can think about it is as digital copying, giving a copy of a digital resource while retaining a version by ourselves. Sharing can also be fractional or sharing could be about giving rights to use a certain resource. The concept of shareability and the context of shareability can take different forms and one might use different types of implementatins for instances of shareable tokens. Hence we haven't restricted that the interface should require any specific token type. - -Shareable tokens can be made non-transferable at the contract implementaiton level. Doing so, makes them shareable non-transferable tokens. In the reference implementation we have distilled a general case from our use cases that defines a shareable non-transferable NFTs using the shareable NFT interface. - -We believe that the wider audience should benefit from an abstraction level higher definition for shareability, such as this interface implementation, that defines minimum amount of functions that would be implemented to satisfy the concept of shareability. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// Note: the ERC-165 identifier for this interface is 0xded6338b -interface IERC5023 is IERC165 { - - /// @dev This emits when a token is shared, reminted and given to another wallet that isn't function caller - event Share(address indexed from, address indexed to, uint256 indexed tokenId, uint256 derivedFromtokenId); - - /// @dev Shares, remints an existing token, gives a newly minted token a fresh token id, keeps original token at function callers possession and transfers newly minted token to receiver which should be another address than function caller. - function share(address to, uint256 tokenIdToBeShared) external returns(uint256 newTokenId); - -} -``` - -The Share event is expected to be emitted when function method share is succesfully called and a new token on basis of a given token id is minted and transferred to a recipient. - -## Rationale - -Current NFT standards define transferable non-fungible tokens, but not shareable non-fungible tokens. To be able to create shareable NFTs we see that existing NFT contracts could be extended with an interface which defines the basic principles of sharing, namely the Event of sharing and the function method of sharing. Definition of how transferability of tokens should be handled is left to the contract implementor. In case transfering is left enable shareable tokens behave similarily to the existing tokens, except when they are shared, a version of token is retained. In case transfering is disabled, shareable tokens become shareable non-transferable tokens, where they can be minted and given or shared to other people, but they cannot be transferred away. - -Imagine that Bob works together with Alice on a project. Bob earns an unique NFT indicating that he has made effort to the project, but Bob feels that his accomplishments are not only out of his own accord. Bob wants to share his token with Alice to indicate that also Alice deserves recognition of having put effort on their project. Bob initiates token sharing by calling `Share` method on the contract which has his token and indicates which one of his tokens he wishes to share and to whom by passing address and token id parameters. A new token is minted for Alice and a `Share` event is initiated to communicate that it was Bob whom shared his token to Alice by logging addresses who shared a token id to whose address and which token id was this new token derived from. - -Over time, a tree-like structures can be formed from the Share event information. If Bob shared to Alice, and Alice shared further to Charlie and Alice also shared to David a rudimentary tree structure forms out from sharing activity. This share event data can be later on utilized to gain more information of share activities that the tokens represent. - -```text -B -> A -> C - \ - > D -``` - -These tree structures can be further aggregated and collapsed to network representations e.g. social graphs on basis of whom has shared to whom over a span of time. E.g. if Bob shared a token to Alice, and Alice has shared a different token to Charlie and Bob has shared a token to Charlie, connections form between all these parties through sharing activities. - -```text - B----A----C - \_______/ -``` - -## Backwards Compatibility - -This proposal is backwards compatible with EIP-721 and EIP-1155. - -## Reference Implementation - -Following reference implementation demonstrates a general use case of one of our pilots. In this case a shareable non-transferable token represents a contribution done to a community that the contract owner has decided to merit with a token. Contract owner can mint a merit token and give it to a person. This token can be further shared by the receiver to other parties for example to share the received merit to others that have participated or influenced his contribution. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "./IERC5023.sol"; -import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; -import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/utils/Context.sol"; -import "@openzeppelin/contracts/utils/Strings.sol"; -import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; -import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; -import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract ShareableERC721 is ERC721URIStorage, Ownable, IERC5023 /* EIP165 */ { - - string baseURI; - - uint256 internal _currentIndex; - - constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} - - function mint( - address account, - uint256 tokenId - ) external onlyOwner { - _mint(account, tokenId); - } - - function setTokenURI( - uint256 tokenId, - string memory tokenURI - ) external { - _setTokenURI(tokenId, tokenURI); - } - - function setBaseURI(string memory baseURI_) external { - baseURI = baseURI_; - } - - function _baseURI() internal view override returns (string memory) { - return baseURI; - } - - function share(address to, uint256 tokenIdToBeShared) external returns(uint256 newTokenId) { - require(to != address(0), "ERC721: mint to the zero address"); - require(_exists(tokenIdToBeShared), "ShareableERC721: token to be shared must exist"); - - require(msg.sender == ownerOf(tokenIdToBeShared), "Method caller must be the owner of token"); - - string memory _tokenURI = tokenURI(tokenIdToBeShared); - _mint(to, _currentIndex); - _setTokenURI(_currentIndex, _tokenURI); - - emit Share(msg.sender, to, _currentIndex, tokenIdToBeShared); - - return _currentIndex; - } - - function transferFrom( - address from, - address to, - uint256 tokenId - ) public virtual override { - revert('In this reference implementation tokens are not transferrable'); - } - - function safeTransferFrom( - address from, - address to, - uint256 tokenId - ) public virtual override { - revert('In this reference implementation tokens are not transferrable'); - } -} - -``` - -## Security Considerations - -Reference implementation should not be used as is in production. -There are no other security considerations related directly to implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5023.md diff --git a/EIPS/eip-5027.md b/EIPS/eip-5027.md index 8d0e9207387e2f..279c8f7f8bd2cb 100644 --- a/EIPS/eip-5027.md +++ b/EIPS/eip-5027.md @@ -4,7 +4,7 @@ title: Remove the limit on contract code size description: Change the limit on contract size from 24576 to infinity author: Qi Zhou (@qizhou) discussions-to: https://ethereum-magicians.org/t/eip-5027-unlimit-contract-code-size/9010 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-04-21 @@ -53,9 +53,9 @@ If `block.number >= FORK_BLKNUM`, the contract creation initialization can retur (CODE_SIZE - 1) // CODE_SIZE_UNIT * COLD_ACCOUNT_CODE_ACCESS_COST_PER_UNIT ``` -if the contract is not in `accessed_code_in_addresses` or `0` if the contract is in `accessed_code_in_addresses`, where `//` is the integer divide operator, and `accessed_code_in_addresses: Set[Address]` is a tranasction-context-wide set similar to `access_addressses` and `accessed_storage_keys`. +if the contract is not in `accessed_code_in_addresses` or `0` if the contract is in `accessed_code_in_addresses`, where `//` is the integer divide operator, and `accessed_code_in_addresses: Set[Address]` is a transaction-context-wide set similar to `access_addresses` and `accessed_storage_keys`. -When a transactoin execution begins, `accessed_code_in_addresses` will include `tx.sender`, `tx.to`, and all precompiles. +When a transaction execution begins, `accessed_code_in_addresses` will include `tx.sender`, `tx.to`, and all precompiles. When `CREATE/CREATE2/EXTCODECOPY/CALL/CALLCODE/DELEGATECALL/STATICCALL` is called, immediately add the address to `accessed_code_in_addresses`. diff --git a/EIPS/eip-5050.md b/EIPS/eip-5050.md index 10305c414ead0d..677c5c3223f3c7 100644 --- a/EIPS/eip-5050.md +++ b/EIPS/eip-5050.md @@ -1,351 +1,7 @@ --- eip: 5050 -title: Interactive NFTs with Modular Environments -description: Action messaging and discovery protocol for interactions on and between NFTs -author: Alexi (@alexi) -discussions-to: https://ethereum-magicians.org/t/eip-5050-nft-interaction-standard/9922 -status: Draft -type: Standards Track category: ERC -created: 2021-4-18 -requires: 165, 173, 721, 1155, 1820, 4906 +status: Moved --- -## Abstract - -This standard defines a broadly applicable action messaging protocol for the transmission of user-initiated actions between tokens. Modular statefulness is achieved with optional state controller contracts (i.e. environments) that manage shared state, and provide arbitration and settlement of the action process. - -## Motivation - -Tokenized item standards such as [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) serve as the objects of the Ethereum computing environment. A growing number of projects are seeking to build interactivity and *"digital physics"* into NFTs, especially in the contexts of gaming and decentralized identity. A standard action messaging protocol will allow this physics layer to be developed in the same open, Ethereum-native way as the objects they operate on. - -The messaging protocol outlined defines how an action is initiated and transmitted between tokens and (optional) shared state environments. It is paired with a common interface for defining functionality that allows off-chain services to aggregate and query supported contracts for functionality and interoperability; creating a discoverable, human-readable network of interactive token contracts. Not only can contracts that implement this standard be automatically discovered by such services, their *policies for interaction* can be as well. This allows clients to easily discover compatible senders and receivers, and allowed actions. - -Aggregators can also parse action event logs to derive analytics on new action types, trending/popular/new interactive contracts, which token and state contract pairs users are likely to interact with, and other discovery tools to facilitate interaction. - -### Benefits - -1. Make interactive token contracts **discoverable and usable** by applications -2. Create a decentralized "digital physics" layer for gaming and other applications -3. Provide developers a simple solution with viable validity guarantees to make dynamic NFTs and other tokens -4. Allow for generalized action bridges to transmit actions between chains (enabling actions on L1 assets to be saved to L2s, L1 assets to interact with L2 assets, and L2 actions to be "rolled-up"/finalized on L1). - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -Smart contracts implementing this EIP standard MUST implement the [EIP-165](./eip-165.md) supportsInterface function and MUST return the constant value `true` if the `IERC5050Sender` interface ID `0xc8c6c9f3` and/or the `IERC5050Receiver` interface ID `0x1a3f02f4` is passed through the `interfaceID` argument (depending on which interface(s) the contract implements). - -```solidity -pragma solidity ^0.8.0; - -/// @param _address The address of the interactive object -/// @param tokenId The token that is interacting (optional) -struct Object { - address _address; - uint256 _tokenId; -} - -/// @param selector The bytes4(keccack256()) encoding of the action string -/// @param user The address of the sender -/// @param from The initiating object -/// @param to The receiving object -/// @param state The state controller contract -/// @param data Additional data with no specified format -struct Action { - bytes4 selector; - address user; - Object from; - Object to; - address state; - bytes data; -} - -/// @title EIP-5050 Interactive NFTs with Modular Environments -interface IERC5050Sender { - /// @notice Send an action to the target address - /// @dev The action's `fromContract` is automatically set to `address(this)`, - /// and the `from` parameter is set to `msg.sender`. - /// @param action The action to send - function sendAction(Action memory action) external payable; - - /// @notice Check if an action is valid based on its hash and nonce - /// @dev When an action passes through all three possible contracts - /// (`fromContract`, `to`, and `state`) the `state` contract validates the - /// action with the initiating `fromContract` using a nonced action hash. - /// This hash is calculated and saved to storage on the `fromContract` before - /// action handling is initiated. The `state` contract calculates the hash - /// and verifies it and nonce with the `fromContract`. - /// @param _hash The hash to validate - /// @param _nonce The nonce to validate - function isValid(bytes32 _hash, uint256 _nonce) external returns (bool); - - /// @notice Retrieve list of actions that can be sent. - /// @dev Intended for use by off-chain applications to query compatible contracts, - /// and to advertise functionality in human-readable form. - function sendableActions() external view returns (string[] memory); - - /// @notice Change or reaffirm the approved address for an action - /// @dev The zero address indicates there is no approved address. - /// Throws unless `msg.sender` is the `_account`, or an authorized - /// operator of the `_account`. - /// @param _account The account of the account-action pair to approve - /// @param _action The action of the account-action pair to approve - /// @param _approved The new approved account-action controller - function approveForAction( - address _account, - bytes4 _action, - address _approved - ) external returns (bool); - - /// @notice Enable or disable approval for a third party ("operator") to conduct - /// all actions on behalf of `msg.sender` - /// @dev Emits the ApprovalForAll event. The contract MUST allow - /// an unbounded number of operators per owner. - /// @param _operator Address to add to the set of authorized operators - /// @param _approved True if the operator is approved, false to revoke approval - function setApprovalForAllActions(address _operator, bool _approved) - external; - - /// @notice Get the approved address for an account-action pair - /// @dev Throws if `_tokenId` is not a valid NFT. - /// @param _account The account of the account-action to find the approved address for - /// @param _action The action of the account-action to find the approved address for - /// @return The approved address for this account-action, or the zero address if - /// there is none - function getApprovedForAction(address _account, bytes4 _action) - external - view - returns (address); - - /// @notice Query if an address is an authorized operator for another address - /// @param _account The address on whose behalf actions are performed - /// @param _operator The address that acts on behalf of the account - /// @return True if `_operator` is an approved operator for `_account`, false otherwise - function isApprovedForAllActions(address _account, address _operator) - external - view - returns (bool); - - /// @dev This emits when an action is sent (`sendAction()`) - event SendAction( - bytes4 indexed name, - address _from, - address indexed _fromContract, - uint256 _tokenId, - address indexed _to, - uint256 _toTokenId, - address _state, - bytes _data - ); - - /// @dev This emits when the approved address for an account-action pair - /// is changed or reaffirmed. The zero address indicates there is no - /// approved address. - event ApprovalForAction( - address indexed _account, - bytes4 indexed _action, - address indexed _approved - ); - - /// @dev This emits when an operator is enabled or disabled for an account. - /// The operator can conduct all actions on behalf of the account. - event ApprovalForAllActions( - address indexed _account, - address indexed _operator, - bool _approved - ); -} - -interface IERC5050Receiver { - /// @notice Handle an action - /// @dev Both the `to` contract and `state` contract are called via - /// `onActionReceived()`. - /// @param action The action to handle - function onActionReceived(Action calldata action, uint256 _nonce) - external - payable; - - /// @notice Retrieve list of actions that can be received. - /// @dev Intended for use by off-chain applications to query compatible contracts, - /// and to advertise functionality in human-readable form. - function receivableActions() external view returns (string[] memory); - - /// @dev This emits when a valid action is received. - event ActionReceived( - bytes4 indexed name, - address _from, - address indexed _fromContract, - uint256 _tokenId, - address indexed _to, - uint256 _toTokenId, - address _state, - bytes _data - ); -} -``` - -### Action Naming - -Actions SHOULD use dot-separation for namespacing (e.g. `"spells.cast"` specifies the `"cast"` action with namespace `"spells"`), and arrow-separation for sequence specification (e.g. `"settle>build"` indicating `"settle"` must be received before `"build"`). - -### How State Contracts Work - -Actions do not require that a state contract be used. Actions can be transmitted from one token contract (`Object`) to another, or from a user to a single token contract. In these cases, the sending and receiving contracts each control their own state. - -State contracts allow arbitrary senders and receivers to share a user-specified state environment. Each `Object` MAY define its own action handling, which MAY include reading from the state contract during, but the action MUST be finalized by the state contract. This means the state contract serves as ground truth. - -The intended workflow is for state contracts to define stateful game environments, typically with a custom `IState` interface for use by other contracts. `Objects` register with state contracts to initialize their state. Then, users commit actions using a specific state contract to make things happen in the game. - -The modularity of state contracts allows multiple copies of the same or similar "game environment" to be created and swapped in or out by the client. There are many ways this modularity can be used: - -- Aggregator services can analyze action events to determine likely state contracts for a given sender/receiver -- Sender/receiver contracts can require a specific state contract -- Sender/receiver contracts can allow any state contract, but set a default. This is important for NFTs that change their render based on state. This default can also be configurable by the token holder. -- State contracts can be bridges to state contracts on another chain, allowing for L1-verification, L2-storage usage pattern (validate action with layer-1 assets, save on l2 where storage is cheaper). - -#### Example - -State Contract `FightGame` defines a fighting game environment. Token holders call `FightGame.register(contract, tokenId)` to randomly initialize their stats (strength/hp/etc.). An account which holds a registered token A of contract `Fighters`, calls `Fighters.sendAction(AttackAction)`, specifying token A from `Fighters` as the sender, token B from `Pacifists` contract as the receiver, and `FightGame` as the state contract. - -The action is passed to token B, which may handle the action in whatever way it wants before passing the action to the `FightGame` state contract. The state contract can verify the stored action hash with the `Fighters` contract to validate the action is authentic before updating the stats if the tokens, dealing damage to token B. - -Tokens A and B may update their metadata based on stats in the `FightGame` state contract, or based on their own stored data updated in response to sending/receiving actions. - -### Extensions - -#### Interactive - -Some contracts may have custom user interfaces that facilitate interaction. - -```solidity -pragma solidity ^0.8.0; - -/// @title EIP-5050 Interactive NFTs with Modular Environments -interface IERC5050Interactive { - function interfaceURI(bytes4 _action) external view returns (string); -} -``` - -#### Action Proxies - -Action proxies can be used to support backwards compatibility with non-upgradeable contracts, and potentially for cross-chain action bridging. - -They can be implemented using a modified version of [EIP-1820](./eip-1820.md#erc-1820-registry-smart-contract) that allows [EIP-173](./eip-173.md) contract owners to call `setManager()`. - -#### Controllable - -Users of this standard may want to allow trusted contracts to control the action process to provide security guarantees, and support action bridging. Controllers step through the action chain, calling each contract individually in sequence. - -Contracts that support Controllers SHOULD ignore require/revert statements related to action verification, and MUST NOT pass the action to the next contract in the chain. - -```solidity -pragma solidity ^0.8.0; - -/// @title EIP-5050 Action Controller -interface IControllable { - - /// @notice Enable or disable approval for a third party ("controller") to force - /// handling of a given action without performing EIP-5050 validity checks. - /// @dev Emits the ControllerApproval event. The contract MUST allow - /// an unbounded number of controllers per action. - /// @param _controller Address to add to the set of authorized controllers - /// @param _action Selector of the action for which the controller is approved / disapproved - /// @param _approved True if the controller is approved, false to revoke approval - function setControllerApproval(address _controller, bytes4 _action, bool _approved) - external; - - /// @notice Enable or disable approval for a third party ("controller") to force - /// action handling without performing EIP-5050 validity checks. - /// @dev Emits the ControllerApproval event. The contract MUST allow - /// an unbounded number of controllers per action. - /// @param _controller Address to add to the set of authorized controllers - /// @param _approved True if the controller is approved, false to revoke approval - function setControllerApprovalForAll(address _controller, bool _approved) - external; - - /// @notice Query if an address is an authorized controller for a given action. - /// @param _controller The trusted third party address that can force action handling - /// @param _action The action selector to query against - /// @return True if `_controller` is an approved operator for `_account`, false otherwise - function isApprovedController(address _controller, bytes4 _action) - external - view - returns (bool); - - /// @dev This emits when a controller is enabled or disabled for the given - /// action. The controller can force `action` handling on the emitting contract, - /// bypassing the standard EIP-5050 validity checks. - event ControllerApproval( - address indexed _controller, - bytes4 indexed _action, - bool _approved - ); - - /// @dev This emits when a controller is enabled or disabled for all actions. - /// Disabling all action approval for a controller does not override explicit action - /// action approvals. Controller's approved for all actions can force action handling - /// on the emitting contract for any action. - event ControllerApprovalForAll( - address indexed _controller, - bool _approved - ); -} -``` - -#### Metadata Update - -Interactive NFTs are likely to update their metadata in response to certain actions and developers MAY want to implement [EIP-4906](./eip-4906.md) event emitters. - -## Rationale - -The critical features of this interactive token standard are that it 1) creates a common way to define, advertise, and conduct object interaction, 2) enables optional, brokered statefulness with *useful* validity assurances at minimum gas overhead, 3) is easy for developers to implement, and 4) is easy for end-users to use. - -### Action Names & Selectors - -Actions are advertised using human-readable strings, and processed using function selectors (`bytes4(keccack256(action_key))`). Human-readable strings allow end-users to easily interpret functionality, while function selectors allow efficient comparison operations on arbitrarily long action keys. This scheme also allows for simple namespacing and sequence specification. - -Off-chain services can easily convert the strings to `bytes4` selector encoding when interacting with contracts implementing this EIP or parsing `SendAction` and `ActionReceived` event logs. - -### Validation - -Validation of the initiating contract via a hash of the action data was satisfactory to nearly everyone surveyed and was the most gas efficient verification solution explored. We recognize that this solution does not allow the receiving and state contracts to validate the initiating `user` account beyond using `tx.origin`, which is vulnerable to phishing attacks. - -We considered using a signed message to validate user-intiation, but this approach had two major drawbacks: - -1. **UX** users would be required to perform two steps to commit each action (sign the message, and send the transaction) -2. **Gas** performing signature verification is computationally expensive - -Most importantly, the consensus among the developers surveyed is that strict user validation is not necessary because the concern is only that malicious initiating contracts will phish users to commit actions *with* the malicious contract's assets. **This protocol treats the initiating contract's token as the prime mover, not the user.** Anyone can tweet at Bill Gates. Any token can send an action to another token. Which actions are accepted, and how they are handled is left up to the contracts. High-value actions can be reputation-gated via state contracts, or access-gated with allow/disallow-lists. [`Controllable`](#controllable) contracts can also be used via trusted controllers as an alternative to action chaining. - -*Alternatives considered: action transmitted as a signed message, action saved to reusable storage slot on initiating contract* - -### State Contracts - -Moving state logic into dedicated, parameterized contracts makes state an action primitive and prevents state management from being obscured within the contracts. Specifically, it allows users to decide which "environment" to commit the action in, and allows the initiating and receiving contracts to share state data without requiring them to communicate. - -The specifics of state contract interfaces are outside the scope of this standard, and are intended to be purpose-built for unique interactive environments. - -### Gas and Complexity (regarding action chaining) - -Action handling within each contract can be arbitrarily complex, and there is no way to eliminate the possibility that certain contract interactions will run out of gas. However, developers SHOULD make every effort to minimize gas usage in their action handler methods, and avoid the use of for-loops. - -*Alternatives considered: multi-request action chains that push-pull from one contract to the next.* - -## Backwards Compatibility - -Non-upgradeable, already deployed token contracts will not be compatible with this standard unless a proxy registry extension is used. - -## Reference Implementation - -A reference implementation is included in `../assets/eip-5050` with a simple stateless example [`ExampleToken2Token.sol`](../assets/eip-5050/ExampleToken2Token.sol), and a stateful example [`ExampleStateContract.sol`](../assets/eip-5050/ExampleStateContract.sol) - -## Security Considerations - -The core security consideration of this protocol is action validation. Actions are passed from one contract to another, meaning it is not possible for the receiving contract to natively verify that the caller of the initiating contract matches the `action.from` address. One of the most important contributions of this protocol is that it provides an alternative to using signed messages, which require users to perform two operations for every action committed. - -As discussed in [Validation](#validation), this is viable because the initiating contract / token is treated as the prime mover, not the user. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5050.md diff --git a/EIPS/eip-5058.md b/EIPS/eip-5058.md index e6fe7b6987f46a..568d58249c290d 100644 --- a/EIPS/eip-5058.md +++ b/EIPS/eip-5058.md @@ -1,206 +1,7 @@ --- eip: 5058 -title: Lockable Non-Fungible Tokens -description: Lockable EIP-721 tokens -author: Tyler (@radiocaca), Alex (@gojazdev), John (@sfumato00) -discussions-to: https://ethereum-magicians.org/t/eip-5058-erc-721-lockable-standard/9201 -status: Draft -type: Standards Track category: ERC -created: 2022-04-30 -requires: 20, 165, 721 +status: Moved --- -## Abstract - -We propose to extend the [EIP-721](./eip-721.md) standard with a secure locking mechanism. The NFT owners approve the operator to lock the NFT through `setLockApprovalForAll()` or `lockApprove()`. The approved operator locks the NFT through `lock()`. The locked NFTs cannot be transferred until the end of the locking period. An immediate use case is to allow NFTs to participate in smart contracts without leaving the wallets of their owners. - -## Motivation - -NFTs, enabled by [EIP-721](./eip-721.md), have exploded in demand. The total market value and the ecosystem continue to grow with more and more blue chip NFTs, which are approximately equivalent to popular intellectual properties in a conventional sense. Despite the vast success, something is left to be desired. Liquidity has always been one of the biggest challenges for NFTs. Several attempts have been made to tackle the liquidity challenge: NFTFi and BendDAO, to name a few. Utilizing the currently prevalent EIP-721 standard, these projects require participating NFTs to be transferred to the projects' contracts, which poses inconveniences and risks to the owners: - -1. Smart contract risks: NFTs can be lost or stolen due to bugs or vulnerabilities in the contracts. -2. Loss of utility: NFTs have utility values, such as profile pictures and bragging rights, which are lost when the NFTs are no longer seen under the owners' custody. -3. Missing Airdrops: The owners can no longer directly receive airdrops entitled to the NFTs. Considering the values and price fluctuation of some of the airdrops, either missing or not getting the airdrop on time can financially impact the owners. - -All of the above are bad UX, and we believe the EIP-721 standard can be improved by adopting a native locking mechanism: - -1. Instead of being transferred to a smart contract, an NFT remains in self-custody but locked. -2. While an NFT is locked, its transfer is prohibited. Other properties remain unaffected. -3. The owners can receive or claim airdrops themselves. - -The value of an NFT can be reflected in two aspects: collection value and utility value. Collection value needs to ensure that the holder's wallet retains ownership of the NFT forever. Utility value requires ensuring that the holder can verify their NFT ownership in other projects. Both of these aspects require that the NFT remain in its owner's wallet. - -The proposed standard allows the underlying NFT assets to be managed securely and conveniently by extending the EIP-721 standard to natively support common NFTFi use cases including locking, staking, lending, and crowdfunding. We believe the proposed standard will encourage NFT owners to participate more actively in NFTFi projects and, hence, improve the livelihood of the whole NFT ecosystem. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Lockable EIP-721 **MUST** implement the `IERC5058` interfaces: - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.8; - -/** - * @dev EIP-721 Non-Fungible Token Standard, optional lockable extension - * ERC721 Token that can be locked for a certain period and cannot be transferred. - * This is designed for a non-escrow staking contract that comes later to lock a user's NFT - * while still letting them keep it in their wallet. - * This extension can ensure the security of user tokens during the staking period. - * If the nft lending protocol is compatible with this extension, the trouble caused by the NFT - * airdrop can be avoided, because the airdrop is still in the user's wallet - */ -interface IERC5058 { - /** - * @dev Emitted when `tokenId` token is locked by `operator` from `from`. - */ - event Locked(address indexed operator, address indexed from, uint256 indexed tokenId, uint256 expired); - - /** - * @dev Emitted when `tokenId` token is unlocked by `operator` from `from`. - */ - event Unlocked(address indexed operator, address indexed from, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables `approved` to lock the `tokenId` token. - */ - event LockApproval(address indexed owner, address indexed approved, uint256 indexed tokenId); - - /** - * @dev Emitted when `owner` enables or disables (`approved`) `operator` to lock all of its tokens. - */ - event LockApprovalForAll(address indexed owner, address indexed operator, bool approved); - - /** - * @dev Returns the locker who is locking the `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function lockerOf(uint256 tokenId) external view returns (address locker); - - /** - * @dev Lock `tokenId` token until the block number is greater than `expired` to be unlocked. - * - * Requirements: - * - * - `tokenId` token must be owned by `owner`. - * - `expired` must be greater than block.number - * - If the caller is not `owner`, it must be approved to lock this token - * by either {lockApprove} or {setLockApprovalForAll}. - * - * Emits a {Locked} event. - */ - function lock(uint256 tokenId, uint256 expired) external; - - /** - * @dev Unlock `tokenId` token. - * - * Requirements: - * - * - `tokenId` token must be owned by `owner`. - * - the caller must be the operator who locks the token by {lock} - * - * Emits a {Unlocked} event. - */ - function unlock(uint256 tokenId) external; - - /** - * @dev Gives permission to `to` to lock `tokenId` token. - * - * Requirements: - * - * - The caller must own the token or be an approved lock operator. - * - `tokenId` must exist. - * - * Emits an {LockApproval} event. - */ - function lockApprove(address to, uint256 tokenId) external; - - /** - * @dev Approve or remove `operator` as an lock operator for the caller. - * Operators can call {lock} for any token owned by the caller. - * - * Requirements: - * - * - The `operator` cannot be the caller. - * - * Emits an {LockApprovalForAll} event. - */ - function setLockApprovalForAll(address operator, bool approved) external; - - /** - * @dev Returns the account lock approved for `tokenId` token. - * - * Requirements: - * - * - `tokenId` must exist. - */ - function getLockApproved(uint256 tokenId) external view returns (address operator); - - /** - * @dev Returns if the `operator` is allowed to lock all of the assets of `owner`. - * - * See {setLockApprovalForAll} - */ - function isLockApprovedForAll(address owner, address operator) external view returns (bool); - - /** - * @dev Returns if the `tokenId` token is locked. - */ - function isLocked(uint256 tokenId) external view returns (bool); - - /** - * @dev Returns the `tokenId` token lock expired time. - */ - function lockExpiredTime(uint256 tokenId) external view returns (uint256); -} -``` - -## Rationale - -### NFT lock approvals - -An NFT owner can give another trusted operator the right to lock his NFT through the approve functions. The `lockApprove()` function only approves for the specified NFT, whereas `setLockApprovalForAll()` approves for all NFTs of the collection under the wallet. When a user participates in an NFTFi project, the project contract calls `lock()` to lock the user's NFT. Locked NFTs cannot be transferred, but the NFTFi project contract can use the unlock function `unlock()` to unlock the NFT. - -### NFT lock/unlock - -Authorized project contracts have permission to lock NFT with the `lock` method. Locked NFTs cannot be transferred until the lock time expires. The project contract also has permission to unlock NFT in advance through the `unlock` function. Note that only the address of the locked NFT has permission to unlock that NFT. - -### NFT lock period - -When locking an NFT, one must specify the lock expiration block number, which must be greater than the current block number. When the current block number exceeds the expiration block number, the NFT is automatically released and can be transferred. - -### Bound NFT - -Bound NFT is an extension of this EIP, which implements the ability to mint a boundNFT during the NFT locking period. The boundNFT is identical to the locked NFT metadata and can be transferred. However, a boundNFT only exists during the NFT locking period and will be destroyed after the NFT is unlocked. -BoundNFT can be used to lend, as a staking credential for the contract. The credential can be locked in the contract, but also to the user. In NFT leasing, boundNFT can be rented to users because boundNFT is essentially equivalent to NFT. This consensus, if accepted by all projects, boundNFT will bring more creativity to NFT. - -### Bound NFT Factory - -Bound NFT Factory is a common boundNFT factory, similar to Uniswap's [EIP-20](./eip-20.md) pairs factory. It uses the create2 method to create a boundNFT contract address for any NFT deterministic. BoundNFT contract that has been created can only be controlled by the original NFT contract. - - -## Backwards Compatibility - -This standard is compatible with EIP-721. - -## Test Cases - -Test cases written using hardhat can be found [here](../assets/eip-5058/test/test.ts) - -## Reference Implementation - -You can find an implementation of this standard in the [assets](../assets/eip-5058/ERC5058.sol) folder. - -## Security Considerations - -After being locked, the NFT can not be transferred, so before authorizing locking rights to other project contracts, you must confirm that the project contract can unlock NFT. Otherwise there is a risk of NFT being permanently locked. It is recommended to give a reasonable locking period in use for projects. NFT can be automatically unlocked, which can reduce the risk to a certain extent. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5058.md diff --git a/EIPS/eip-5069.md b/EIPS/eip-5069.md index 43b0b4138d6f34..0e37f8f230d25c 100644 --- a/EIPS/eip-5069.md +++ b/EIPS/eip-5069.md @@ -1,44 +1,119 @@ --- eip: 5069 title: EIP Editor Handbook -description: Handy reference for EIP editors and those who want to become one -author: Pooja Ranjan (@poojaranjan), Pandapip1 (@Pandapip1) +description: Organizational structure, decision making process, and other EIP Editor odds and ends. +author: Pooja Ranjan (@poojaranjan), Gavin John (@Pandapip1), Sam Wilson (@SamWilsn), et al. discussions-to: https://ethereum-magicians.org/t/pr-5069-eip-editor-handbook/9137 status: Living -type: Informational +type: Meta created: 2022-05-02 requires: 1 --- -## Abstract +## Introduction -An Ethereum Improvement Proposal (EIP) is a design document providing information to the Ethereum community, or describing a new feature for Ethereum or its processes or environment. The EIP standardization process is a mechanism for proposing new features, for collecting community technical input on an issue, and for documenting the design decisions that have gone into Ethereum. Because improvement proposals are key components of Ethereum blockchain, it is important that they are well reviewed before reaching `Final` status. EIPs are stored in text files in a versioned repository which is monitored by the EIP editors. +We, the Ethereum Improvement Proposal (EIP) Editors, maintain a repository of documents related to the Ethereum protocol and its ecosystem. Consider us both _archivists_ making sure the community as a whole does not lose its history, and a _publisher_ making sure interested parties can stay up-to-date with the latest proposals. -This EIP describes the recommended process for becoming an EIP editor. +## Mission -## Specification +### What we Do -### Application and Onboarding Process +Our mission is to serve the broad Ethereum community, both present and future, by: -Anyone having a good understanding of the EIP standardization and network upgrade process, intermediate level experience on the core and/or application side of the Ethereum blockchain, and willingness to contribute to the process management may apply to become an EIP editor. Potential EIP editors should have the following skills: + - **Publishing Proposals**: Making proposals, including their history and associated discussions available over the long term at no cost. + + By doing so, we foster transparency and ensure that valuable insights from past proposals are accessible for future decision-making and learning. + - **Facilitating Discussion**: Providing a forum for discussing proposals open to anyone who wants to participate civilly. + + By encouraging open dialogue and collaboration, we aim to harness the collective knowledge and expertise of the Ethereum community in shaping proposals. + - **Upholding Quality**: Upholding a measure of minimally-subjective quality for each proposal as defined by its target audience. -- Good communication skills -- Ability to handle contentious discourse -- 1-5 spare hours per week + By adhering to defined criteria, we promote the development of high-quality and relevant proposals that drive the evolution of Ethereum. -The best available resource to understand the EIP process is [EIP-1](./eip-1.md). Anyone desirous of becoming an EIP editor MUST understand this document. Afterwards, participating in the EIP process by commenting on and suggesting improvements to PRs and issues will familliarize the procedure, and is recommended. The contributions of newer editors should be monitored by other EIP editors. +### What we Don't -Anyone meeting the above requirements may make a pull request adding themselves as an EIP editor and adding themselves to the editor list at `config/eip-editors.yml` and in [EIP-1](./eip-1.md). If every existing EIP editor approves, the author becomes a full EIP editor. This should notify the editor of relevant new proposals submitted in the EIPs repository, and they should review and merge those pull requests. +On the other hand, we do _not_: -### Special Merging Rules for this EIP + - **Decide Winners**: If there are multiple competing proposals, we will publish all of them. We are not in the business of deciding what is the right path for Ethereum, nor do we believe that there is One True Way to satisfy a need. -This EIP MUST have the same rules regarding changes as [EIP-1](./eip-1.md). + - **Assert Correctness**: While we might offer technical feedback from time to time, we are not experts nor do we vet every proposal in depth. Publishing a proposal is not an endorsement or a statement of technical soundness. -## Rationale + - **Manage**: We do not track implementation status, schedule work, or set fork dates or contents. -- "6 months" was chosen as the cutoff for denoting `Stagnant` EIPs terminally-`Stagnant` arbitrarily. -- This EIP requires special merging rules for the same reason [EIP-1](./eip-1.md) does. + - **Track Registries**: We want all proposals to eventually become immutable, but a registry will never get there if anyone can keep adding items. To be clear, exhaustive and/or static lists are fine. + - **Provide Legal Advice**: Trademarks, copyrights, patents, prior art, and other legal matters are the responsibility of authors and implementers, not EIP Editors. We are not lawyers, and while we may occasionally make comments touching on these areas, we cannot guarantee any measure of correctness. + +Documenting all of the things we would not do is impossible, and the above are just a few examples. We reserve the right to do less work whenever possible! + +## Structure + +### EIP Editors + +We, the Editors, consist of some number of EIP Editors and one Keeper of Consensus (or just Keeper for short) elected by and from the EIP Editors. + +EIP Editors are responsible for governing the EIP process itself, electing a Keeper, and stewarding proposals. + +The Keeper's two responsibilities (on top of their EIP Editor duties) are: to determine when rough consensus has been reached on a matter, and determine when/if it is appropriate to re-open an already settled matter. + +## Membership + +Anyone may apply to join as an EIP Editor. Specific eligibility requirements are left to individual current EIP Editors, but the general requirements are: + + - A strong belief in the above mission; + - Proficiency with English (both written and spoken); + - Reading and critiquing EIPs; + - Participation in governance. + +EIP Editors are expected to meet these requirements throughout their tenure, and not doing so is grounds for removal. Any member may delegate some or all of their responsibilities/powers to tools and/or to other people. + +## Making Decisions + +### Informally + +For decisions that are unlikely to be controversial—especially for decisions affecting a single proposal—an EIP Editor may choose whatever option they deem appropriate in accordance with our mission. + +### Formally + +Electing a Keeper, adding/removing EIP Editors, and any possibly-controversial decisions must all be made using variations of this formal process. + +#### Preparation + +##### Call for Input + +For any matter requiring a decision, a call for input must be published in writing to the usual channels frequented by EIP Editors. + +##### Quorum + +Within thirty days of the call for input, to establish a valid quorum, all EIP Editors must express their opinion, vote (where appropriate), or lack thereof on the matter under consideration. + +After thirty days from the call for input, if not all EIP Editors have responded, the quorum is reduced to the Editors that have responded. This deadline may be extended in exceptional situations. + +#### Deciding + +##### Electing a Keeper of Consensus + +Any EIP Editor can call for an election for Keeper. Business continues as usual while the election is running. The EIP Editor with the most votes once quorum is met is named Keeper until the next election completes. If there is a tie, we'll randomly choose between the EIP Editors with the most votes, using a fair and agreed upon method (for example, a coin toss over a video call or a commit/reveal game of rock paper scissors.) + +##### Adding an EIP Editor + +An EIP Editor is added once quorum is met, provided the candidate consents and no current EIP Editor objects. + +##### Removing an EIP Editor + +An EIP Editor is involuntarily retired once quorum is met, provided no current EIP Editor (aside from the one being removed) objects. An EIP Editor may voluntarily leave their position at any time. + +If the departing Editor was also the Keeper, an election for a new Keeper begins immediately. + +##### Other Decisions + +All other decisions are made through a "rough consensus" process. This does not require all EIP Editors to agree, although this is preferred. In general, the dominant view of the Editors shall prevail. Dominance, in this process, is not determined by persistence or volume but rather a more general sense of agreement. Note that 51% does not mean "rough consensus" has been reached, and 99% is better than rough. It is up to the Keeper to determine if rough consensus has been reached. Every EIP Editor is entitled to have their opinion heard and understood before the Keeper makes that determination. + +No one, not the EIP Editors and certainly not the Keeper, holds veto powers (except when adding/removing an Editor as defined above.) It is imperative that the EIP process evolve, albeit cautiously. + +_This section has been adapted from [RFC 2418]._ ## Copyright Copyright and related rights waived via [CC0](../LICENSE.md). + +[RFC 2418]: https://www.rfc-editor.org/rfc/rfc2418 diff --git a/EIPS/eip-5081.md b/EIPS/eip-5081.md index 8907fba05d5039..6b6ad04657c9dc 100644 --- a/EIPS/eip-5081.md +++ b/EIPS/eip-5081.md @@ -4,7 +4,7 @@ title: Expirable Trainsaction description: This EIP adds a new transaction type of that includes expiration with a blocknum author: Zainan Victor Zhou (@xinbenlv), Nick Johnson (@Arachnid), Konrad Feldmeier discussions-to: https://ethereum-magicians.org/t/eip-5081-expirable-transaction/9208 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-05-06 diff --git a/EIPS/eip-5094.md b/EIPS/eip-5094.md index ed4fa85d83ad45..3bbbc02603efb5 100644 --- a/EIPS/eip-5094.md +++ b/EIPS/eip-5094.md @@ -1,95 +1,7 @@ --- eip: 5094 -title: URL Format for Ethereum Network Switching -description: A way of representing various network configurations as URLs. -author: Luc van Kampen (@lucemans), Jakob Helgesson (@svemat01), Joshua Hendrix (@thejoshuahendrix) -discussions-to: https://ethereum-magicians.org/t/5094-uri-format-for-ethereum-network-switching/9277 -status: Stagnant -type: Standards Track category: ERC -created: 2022-05-13 -requires: 681, 831 +status: Moved --- -## Abstract - -This standard includes all needed information for adding a network to a wallet via URL, by including parameters such as `chainId`, `rpc_url`, `chain_name` and others, such that the network configuration is provided through the URL itself. - -## Motivation - -As observed with the use of [EIP-681](./eip-681.md) and its implementation in current mobile wallets, transactions can be made, approved, viewed, and used. However, if the wallet is instructed to perform a transaction on a chain they have not yet been configured before, the operation tends to fail. - -This is understandable, as the `chain_id` provided makes up only one part of what is required to connect to a network. This EIP aims to introduce a new type of URL for usage with deep-linking, QR, and more, to allow users to seamlessly add new networks to their (for ex. mobile) wallet to then be able to more easily partake in `pay-`, `tx-`, or other Ethereum URL interactions. - -As an extension to [EIP-831](./eip-831.md) and neighboring [EIP-681](./eip-681.md) and [EIP-2400](./eip-2400.md), this document aims to standardize the addition of new networks and switching thereof through the means of URLs. User convenience in this case is primary. - -Introduction of this EIP is meant to bridge to a safer RPC listing system to be introduced in the near future. - -## Specification - -### Syntax - -Network Switching URLs contain "ethereum" in their schema (protocol) part and are constructed as follows: - - network_add = erc831_part "add" "@" chain_id [ "/" ] "?" parameters - erc831_part = "ethereum:network-" - chain_id = 1*DIGIT - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = required_keys / optional_keys - required_keys = "rpc_url" / "chain_name" - optional_keys = "name" / "symbol" / "decimals" / "explorer_url" / "icon_url" - value = STRING / number - number = 1*DIGIT - -`STRING` is a URL-encoded Unicode string of arbitrary length, where delimiters and the -percentage symbol (`%`) are mandatorily hex-encoded with a `%` prefix. - -If the *key* in the parameter is `decimals` the *value* MUST be a `number`. - -### Semantics - -`chain_id` is mandatory and denotes the decimal chain ID, such that we have the identifier of the network we would like to add. - -`rpc_url` is represented as an array of RPC URLs. A minimum of 1 `rpc_url` MUST be present, in the format of `rpc_url=https%3A%2F%2Fpolygon-rpc.com`, or when multiple present `rpc_url=https%3A%2F%2Fpolygon-rpc.com&rpc_url=https%3A%2F%2Frpc-mainnet.matic.network`. - -`chain_name` is required to specify the name of the network to be added. - -`name` and `symbol` if provided, SHOULD be a human-readable string representing the native token. - -`decimals` if provided, MUST be a non-negative integer representing the decimal precision of the native token. - -`explorer_url` if provided, MUST specify one or more URLs pointing to block explorer web sites for the chain. - -`icon_url` if provided, MUST specify one or more URLs pointing to reasonably sized images that can be used to visually identify the chain. - -An example of adding a network with RPC endpoints `https://rpc-polygon.com` and `https://rpc-mainnet.matic.network`, the name `Polygon Mainnet`, token `Matic`, symbol `MATIC`, decimals `18`, explorer at `https://polygonscan.com/`, and Chain ID `137` would look as follows: - -```URL -ethereum:network-add@137/?chain_name=Polygon%20Mainnet&rpc_url=https%3A%2F%2Frpc-polygon.com&rpc_url=https%3A%2F%2Frpc-mainnet.matic.network&name=Matic&symbol=MATIC&decimals=18&explorer_url=https%3A%2F%2Fpolygonscan.com -``` - -## Rationale - -In furtherance of the Ethereum URL saga, network configuration is a needed addition to the possibility of Ethereum URLs. This would improve functionality for URLs, and offer non-mainnet users a way to connect without needing to configure their wallet by hand. - -The URL follows [EIP-831](./eip-831.md) with the `PREFIX` being `network` and the `PAYLOAD` being a composite of `add` and [EIP-681](./eip-681.md)-like `chain_id` and parameters. - -The choice for `PREFIX` being `network` is to allow further expansion and allow variants following the pattern `network-x`. - -An example URL for adding the Optimism Network - -```URL -ethereum:network-add@10/?chain_name=Optimistic%20Ethereum -&rpc_url=https%3A%2F%2Fmainnet.optimism.io&name=Ethereum&symbol=ETH&decimals=18&explorer_url=https%3A%2F%2Foptimistic.etherscan.io -``` - -The specification allows for a multitude of `rpc_url` and `explorer_url` to be specified. This is done such to overlap with parsing of the `TYPE` mentioned in [EIP-681](./eip-681.md). - -## Security Considerations - -URLs can be malformed to deceive users. Users SHOULD confirm source of URL before using any links. As well as checking source and transaction details before confirming any transactions. Applications SHOULD display network config, prior to network addition, such that users can confirm the validity of the network configuration being added. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5094.md diff --git a/EIPS/eip-5095.md b/EIPS/eip-5095.md index a2f9899399d970..6fc5b3ca5361b7 100644 --- a/EIPS/eip-5095.md +++ b/EIPS/eip-5095.md @@ -1,551 +1,7 @@ --- eip: 5095 -title: Principal Token -description: Principal tokens (zero-coupon tokens) are redeemable for a single underlying EIP-20 token at a future timestamp. -author: Julian Traversa (@JTraversa), Robert Robbins (@robrobbins), Alberto Cuesta Cañada (@alcueca) -discussions-to: https://ethereum-magicians.org/t/eip-5095-principal-token-standard/9259 -status: Stagnant -type: Standards Track category: ERC -created: 2022-05-01 -requires: 20, 2612 +status: Moved --- -## Abstract - -Principal tokens represent ownership of an underlying [EIP-20](./eip-20.md) token at a future timestamp. - -This specification is an extension on the [EIP-20](./eip-20.md) token that provides basic functionality for depositing -and withdrawing tokens and reading balances and the [EIP-2612](./eip-2612.md) specification that provides -[EIP-712](./eip-712.md) signature based approvals. - -## Motivation - -Principal tokens lack standardization which has led to a difficult to navigate development space and diverse implementation -schemes. - -The primary examples include yield tokenization platforms which strip future yield leaving a principal -token behind, as well as fixed-rate money-markets which utilize principal tokens as a medium -to lend/borrow. - -This inconsistency in implementation makes integration difficult at the application layer as well as -wallet layer which are key catalysts for the space's growth. -Developers are currently expected to implement individual adapters for each principal token, as well as adapters for -their pool contracts, and many times adapters for their custodial contracts as well, wasting significant developer resources. - -## Specification - -All Principal Tokens (PTs) MUST implement [EIP-20](./eip-20.md) to represent ownership of future underlying redemption. -If a PT is to be non-transferrable, it MAY revert on calls to `transfer` or `transferFrom`. -The [EIP-20](./eip-20.md) operations `balanceOf`, `transfer`, `totalSupply`, etc. operate on the Principal Token balance. - -All Principal Tokens MUST implement [EIP-20](./eip-20.md)'s optional metadata extensions. -The `name` and `symbol` functions SHOULD reflect the underlying token's `name` and `symbol` in some way, as well as the origination protocol, and in the case of yield tokenization protocols, the origination money-market. - -All Principal Tokens MAY implement [EIP-2612](./eip-2612.md) to improve the UX of approving PTs on various integrations. - -### Definitions: - -- underlying: The token that Principal Tokens are redeemable for at maturity. - Has units defined by the corresponding [EIP-20](./eip-20.md) contract. -- maturity: The timestamp (unix) at which a Principal Token matures. Principal Tokens become redeemable for underlying at or after this timestamp. -- fee: An amount of underlying or Principal Token charged to the user by the Principal Token. Fees can exist on redemption or post-maturity yield. -- slippage: Any difference between advertised redemption value and economic realities of PT redemption, which is not accounted by fees. - -### Methods - -#### `underlying` - -The address of the underlying token used by the Principal Token for accounting, and redeeming. - -MUST be an EIP-20 token contract. - -MUST _NOT_ revert. - -```yaml -- name: underlying - type: function - stateMutability: view - - inputs: [] - - outputs: - - name: underlyingAddress - type: address -``` - -#### `maturity` - -The unix timestamp (uint256) at or after which Principal Tokens can be redeemed for their underlying deposit. - -MUST _NOT_ revert. - -```yaml -- name: maturity - type: function - stateMutability: view - - inputs: [] - - outputs: - - name: timestamp - type: uint256 -``` - -#### `convertToUnderlying` - -The amount of underlying that would be exchanged for the amount of PTs provided, in an ideal scenario where all the conditions are met. - -Before maturity, the amount of underlying returned is as if the PTs would be at maturity. - -MUST NOT be inclusive of any fees that are charged against redemptions. - -MUST NOT show any variations depending on the caller. - -MUST NOT reflect slippage or other on-chain conditions, when performing the actual redemption. - -MUST NOT revert unless due to integer overflow caused by an unreasonably large input. - -MUST round down towards 0. - -This calculation MAY NOT reflect the "per-user" price-per-principal-token, and instead should reflect the "average-user's" price-per-principal-token, meaning what the average user should expect to see when exchanging to and from. - -```yaml -- name: convertToUnderlying - type: function - stateMutability: view - - inputs: - - name: principalAmount - type: uint256 - - outputs: - - name: underlyingAmount - type: uint256 -``` - -#### `convertToPrincipal` - -The amount of principal tokens that the principal token contract would request for redemption in order to provide the amount of underlying specified, in an ideal scenario where all the conditions are met. - -MUST NOT be inclusive of any fees. - -MUST NOT show any variations depending on the caller. - -MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. - -MUST NOT revert unless due to integer overflow caused by an unreasonably large input. - -MUST round down towards 0. - -This calculation MAY NOT reflect the "per-user" price-per-principal-token, and instead should reflect the "average-user's" price-per-principal-token, meaning what the average user should expect to see when redeeming. - -```yaml -- name: convertToPrincipal - type: function - stateMutability: view - - inputs: - - name: underlyingAmount - type: uint256 - - outputs: - - name: principalAmount - type: uint256 -``` - -#### `maxRedeem` - -Maximum amount of principal tokens that can be redeemed from the `holder` balance, through a `redeem` call. - -MUST return the maximum amount of principal tokens that could be transferred from `holder` through `redeem` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). - -MUST factor in both global and user-specific limits, like if redemption is entirely disabled (even temporarily) it MUST return 0. - -MUST NOT revert. - -```yaml -- name: maxRedeem - type: function - stateMutability: view - - inputs: - - name: holder - type: address - - outputs: - - name: maxPrincipalAmount - type: uint256 -``` - -#### `previewRedeem` - -Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. - -MUST return as close to and no more than the exact amount of underliyng that would be obtained in a `redeem` call in the same transaction. I.e. `redeem` should return the same or more `underlyingAmount` as `previewRedeem` if called in the same transaction. - -MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the redemption would be accepted, regardless if the user has enough principal tokens, etc. - -MUST be inclusive of redemption fees. Integrators should be aware of the existence of redemption fees. - -MUST NOT revert due to principal token contract specific user/global limits. MAY revert due to other conditions that would also cause `redeem` to revert. - -Note that any unfavorable discrepancy between `convertToUnderlying` and `previewRedeem` SHOULD be considered slippage in price-per-principal-token or some other type of condition. - -```yaml -- name: previewRedeem - type: function - stateMutability: view - - inputs: - - name: principalAmount - type: uint256 - - outputs: - - name: underlyingAmount - type: uint256 -``` - -#### `redeem` - -At or after maturity, burns exactly `principalAmount` of Principal Tokens from `from` and sends `underlyingAmount` of underlying tokens to `to`. - -Interfaces and other contracts MUST NOT expect fund custody to be present. While custodial redemption of Principal Tokens through the Principal Token contract is extremely useful for integrators, some protocols may find giving the Principal Token itself custody breaks their backwards compatibility. - -MUST emit the `Redeem` event. - -MUST support a redeem flow where the Principal Tokens are burned from `holder` directly where `holder` is `msg.sender` or `msg.sender` has EIP-20 approval over the principal tokens of `holder`. -MAY support an additional flow in which the principal tokens are transferred to the Principal Token contract before the `redeem` execution, and are accounted for during `redeem`. - -MUST revert if all of `principalAmount` cannot be redeemed (due to withdrawal limit being reached, slippage, the holder not having enough Principal Tokens, etc). - -Note that some implementations will require pre-requesting to the Principal Token before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: redeem - type: function - stateMutability: nonpayable - - inputs: - - name: principalAmount - type: uint256 - - name: to - type: address - - name: from - type: address - - outputs: - - name: underlyingAmount - type: uint256 -``` - -#### `maxWithdraw` - -Maximum amount of the underlying asset that can be redeemed from the `holder` principal token balance, through a `withdraw` call. - -MUST return the maximum amount of underlying tokens that could be redeemed from `holder` through `withdraw` and not cause a revert, which MUST NOT be higher than the actual maximum that would be accepted (it should underestimate if necessary). - -MUST factor in both global and user-specific limits, like if withdrawals are entirely disabled (even temporarily) it MUST return 0. - -MUST NOT revert. - -```yaml -- name: maxWithdraw - type: function - stateMutability: view - - inputs: - - name: holder - type: address - - outputs: - - name: maxUnderlyingAmount - type: uint256 -``` - -#### `previewWithdraw` - -Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. - -MUST return as close to and no fewer than the exact amount of principal tokens that would be burned in a `withdraw` call in the same transaction. I.e. `withdraw` should return the same or fewer `principalAmount` as `previewWithdraw` if called in the same transaction. - -MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though the withdrawal would be accepted, regardless if the user has enough principal tokens, etc. - -MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. - -MUST NOT revert due to principal token contract specific user/global limits. MAY revert due to other conditions that would also cause `withdraw` to revert. - -Note that any unfavorable discrepancy between `convertToPrincipal` and `previewWithdraw` SHOULD be considered slippage in price-per-principal-token or some other type of condition. - -```yaml -- name: previewWithdraw - type: function - stateMutability: view - - inputs: - - name: underlyingAmount - type: uint256 - - outputs: - - name: principalAmount - type: uint256 -``` - -#### `withdraw` - -Burns `principalAmount` from `holder` and sends exactly `underlyingAmount` of underlying tokens to `receiver`. - -MUST emit the `Redeem` event. - -MUST support a withdraw flow where the principal tokens are burned from `holder` directly where `holder` is `msg.sender` or `msg.sender` has [EIP-20](./eip-20.md) approval over the principal tokens of `holder`. - MAY support an additional flow in which the principal tokens are transferred to the principal token contract before the `withdraw` execution, and are accounted for during `withdraw`. - -MUST revert if all of `underlyingAmount` cannot be withdrawn (due to withdrawal limit being reached, slippage, the holder not having enough principal tokens, etc). - -Note that some implementations will require pre-requesting to the principal token contract before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: withdraw - type: function - stateMutability: nonpayable - - inputs: - - name: underlyingAmount - type: uint256 - - name: receiver - type: address - - name: holder - type: address - - outputs: - - name: principalAmount - type: uint256 -``` - -### Events - -#### Redeem - -`from` has exchanged `principalAmount` of Principal Tokens for `underlyingAmount` of underlying, and transferred that underlying to `to`. - -MUST be emitted when Principal Tokens are burnt and underlying is withdrawn from the contract in the `EIP5095.redeem` method. - -```yaml -- name: Redeem - type: event - - inputs: - - name: from - indexed: true - type: address - - name: to - indexed: true - type: address - - name: amount - indexed: false - type: uint256 -``` - -## Rationale - -The Principal Token interface is designed to be optimized for integrators with a core minimal interface alongside optional interfaces to enable backwards compatibility. Details such as accounting and management of underlying are intentionally not specified, as Principal Tokens are expected to be treated as black boxes on-chain and inspected off-chain before use. - -[EIP-20](./eip-20.md) is enforced as implementation details such as token approval and balance calculation directly carry over. This standardization makes Principal Tokens immediately compatible with all [EIP-20](./eip-20.md) use cases in addition to EIP-5095. - -All principal tokens are redeemable upon maturity, with the only variance being whether further yield is generated post-maturity. Given the ubiquity of redemption, the presence of `redeem` allows integrators to purchase Principal Tokens on an open market, and them later redeem them for a fixed-yield solely knowing the address of the Principal Token itself. - -This EIP draws heavily on the design of [EIP-4626](./eip-4626.md) because technically Principal Tokens could be described as a subset of Yield Bearing Vaults, extended with a `maturity` variable and restrictions on the implementation. However, extending [EIP-4626](./eip-4626.md) would force PT implementations to include methods (namely, `mint` and `deposit`) that are not necessary to the business case that PTs solve. It can also be argued that partial redemptions (implemented via `withdraw`) are rare for PTs. - -PTs mature at a precise second, but given the reactive nature of smart contracts, there can't be an event marking maturity, because there is no guarantee of any activity at or after maturity. Emitting an event to notify of maturity in the first transaction after maturity would be imprecise and expensive. Instead, integrators are recommended to either use the first `Redeem` event, or to track themselves when each PT is expected to have matured. - -## Backwards Compatibility - -This EIP is fully backward compatible with the [EIP-20](./eip-20.md) specification and has no known compatibility issues with other standards. -For production implementations of Principal Tokens which do not use EIP-5095, wrapper adapters can be developed and used, or wrapped tokens can be implemented. - -## Reference Implementation - -``` -// SPDX-License-Identifier: MIT -pragma solidity 0.8.14; - -import {ERC20} from "yield-utils-v2/contracts/token/ERC20.sol"; -import {MinimalTransferHelper} from "yield-utils-v2/contracts/token/MinimalTransferHelper.sol"; - -contract ERC5095 is ERC20 { - using MinimalTransferHelper for ERC20; - - /* EVENTS - *****************************************************************************************************************/ - - event Redeem(address indexed from, address indexed to, uint256 underlyingAmount); - - /* MODIFIERS - *****************************************************************************************************************/ - - /// @notice A modifier that ensures the current block timestamp is at or after maturity. - modifier afterMaturity() virtual { - require(block.timestamp >= maturity, "BEFORE_MATURITY"); - _; - } - - /* IMMUTABLES - *****************************************************************************************************************/ - - ERC20 public immutable underlying; - uint256 public immutable maturity; - - /* CONSTRUCTOR - *****************************************************************************************************************/ - - constructor( - string memory name_, - string memory symbol_, - uint8 decimals_, - ERC20 underlying_, - uint256 maturity_ - ) ERC20(name_, symbol_, decimals_) { - underlying = underlying_; - maturity = maturity_; - } - - /* CORE FUNCTIONS - *****************************************************************************************************************/ - - /// @notice Burns an exact amount of principal tokens in exchange for an amount of underlying. - /// @dev This reverts if before maturity. - /// @param principalAmount The exact amount of principal tokens to be burned. - /// @param from The owner of the principal tokens to be redeemed. If not msg.sender then must have prior approval. - /// @param to The address to send the underlying tokens. - /// @return underlyingAmount The total amount of underlying tokens sent. - function redeem( - uint256 principalAmount, - address from, - address to - ) public virtual afterMaturity returns (uint256 underlyingAmount) { - _decreaseAllowance(from, principalAmount); - - // Check for rounding error since we round down in previewRedeem. - require((underlyingAmount = _previewRedeem(principalAmount)) != 0, "ZERO_ASSETS"); - - _burn(from, principalAmount); - - emit Redeem(from, to, principalAmount); - - _transferOut(to, underlyingAmount); - } - - /// @notice Burns a calculated amount of principal tokens in exchange for an exact amount of underlying. - /// @dev This reverts if before maturity. - /// @param underlyingAmount The exact amount of underlying tokens to be received. - /// @param from The owner of the principal tokens to be redeemed. If not msg.sender then must have prior approval. - /// @param to The address to send the underlying tokens. - /// @return principalAmount The total amount of underlying tokens redeemed. - function withdraw( - uint256 underlyingAmount, - address from, - address to - ) public virtual afterMaturity returns (uint256 principalAmount) { - principalAmount = _previewWithdraw(underlyingAmount); // No need to check for rounding error, previewWithdraw rounds up. - - _decreaseAllowance(from, principalAmount); - - _burn(from, principalAmount); - - emit Redeem(from, to, principalAmount); - - _transferOut(to, underlyingAmount); - } - - /// @notice An internal, overridable transfer function. - /// @dev Reverts on failed transfer. - /// @param to The recipient of the transfer. - /// @param amount The amount of the transfer. - function _transferOut(address to, uint256 amount) internal virtual { - underlying.safeTransfer(to, amount); - } - - /* ACCOUNTING FUNCTIONS - *****************************************************************************************************************/ - - /// @notice Calculates the amount of underlying tokens that would be exchanged for a given amount of principal tokens. - /// @dev Before maturity, it converts to underlying as if at maturity. - /// @param principalAmount The amount principal on which to calculate conversion. - /// @return underlyingAmount The total amount of underlying that would be received for the given principal amount.. - function convertToUnderlying(uint256 principalAmount) external view returns (uint256 underlyingAmount) { - return _convertToUnderlying(principalAmount); - } - - function _convertToUnderlying(uint256 principalAmount) internal view virtual returns (uint256 underlyingAmount) { - return principalAmount; - } - - /// @notice Converts a given amount of underlying tokens to principal exclusive of fees. - /// @dev Before maturity, it converts to principal as if at maturity. - /// @param underlyingAmount The total amount of underlying on which to calculate the conversion. - /// @return principalAmount The amount principal tokens required to provide the given amount of underlying. - function convertToPrincipal(uint256 underlyingAmount) external view returns (uint256 principalAmount) { - return _convertToPrincipal(underlyingAmount); - } - - function _convertToPrincipal(uint256 underlyingAmount) internal view virtual returns (uint256 principalAmount) { - return underlyingAmount; - } - - /// @notice Allows user to simulate redemption of a given amount of principal tokens, inclusive of fees and other - /// current block conditions. - /// @dev This reverts if before maturity. - /// @param principalAmount The amount of principal that would be redeemed. - /// @return underlyingAmount The amount of underlying that would be received. - function previewRedeem(uint256 principalAmount) external view afterMaturity returns (uint256 underlyingAmount) { - return _previewRedeem(principalAmount); - } - - function _previewRedeem(uint256 principalAmount) internal view virtual returns (uint256 underlyingAmount) { - return _convertToUnderlying(principalAmount); // should include fees/slippage - } - - /// @notice Calculates the maximum amount of principal tokens that an owner could redeem. - /// @dev This returns 0 if before maturity. - /// @param owner The address for which the redemption is being calculated. - /// @return maxPrincipalAmount The maximum amount of principal tokens that can be redeemed by the given owner. - function maxRedeem(address owner) public view returns (uint256 maxPrincipalAmount) { - return block.timestamp >= maturity ? _balanceOf[owner] : 0; - } - - /// @notice Allows user to simulate withdraw of a given amount of underlying tokens. - /// @dev This reverts if before maturity. - /// @param underlyingAmount The amount of underlying tokens that would be withdrawn. - /// @return principalAmount The amount of principal tokens that would be redeemed. - function previewWithdraw(uint256 underlyingAmount) external view afterMaturity returns (uint256 principalAmount) { - return _previewWithdraw(underlyingAmount); - } - - function _previewWithdraw(uint256 underlyingAmount) internal view virtual returns (uint256 principalAmount) { - return _convertToPrincipal(underlyingAmount); // should include fees/slippage - } - - /// @notice Calculates the maximum amount of underlying tokens that can be withdrawn by a given owner. - /// @dev This returns 0 if before maturity. - /// @param owner The address for which the withdraw is being calculated. - /// @return maxUnderlyingAmount The maximum amount of underlying tokens that can be withdrawn by a given owner. - function maxWithdraw(address owner) public view returns (uint256 maxUnderlyingAmount) { - return _previewWithdraw(maxRedeem(owner)); - } -} - -``` - -## Security Considerations - -Fully permissionless use cases could fall prey to malicious implementations which only conform to the interface in this EIP but not the specification, failing to implement proper custodial functionality but offering the ability to purchase Principal Tokens through secondary markets. - -It is recommended that all integrators review each implementation for potential ways of losing user deposits before integrating. - -The `convertToUnderlying` method is an estimate useful for display purposes, -and do _not_ have to confer the _exact_ amount of underlying assets their context suggests. - -As is common across many standards, it is strongly recommended to mirror the underlying token's `decimals` if at all possible, to eliminate possible sources of confusion and simplify integration across front-ends and for other off-chain users. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5095.md diff --git a/EIPS/eip-5114.md b/EIPS/eip-5114.md index 379abead0dc90d..79c5a50e50faa7 100644 --- a/EIPS/eip-5114.md +++ b/EIPS/eip-5114.md @@ -1,97 +1,7 @@ --- eip: 5114 -title: Soulbound Badge -description: A badge that is attached to a "soul" at mint time and cannot be transferred after that. -author: Micah Zoltu (@MicahZoltu) -discussions-to: https://ethereum-magicians.org/t/eip-5114-soulbound-token/9417 -status: Review -type: Standards Track category: ERC -created: 2022-05-30 +status: Moved --- - -## Abstract - -A soulbound token is a token that is bound to another Non-Fungible Token (NFT) when it is minted, and cannot be transferred/moved after that. - - -## Specification - -```solidity -interface IERC5114 { - // fired anytime a new instance of this token is minted - // this event **MUST NOT** be fired twice for the same `tokenId` - event Mint(uint256 indexed tokenId, address indexed nftAddress, uint256 indexed nftTokenId); - - // returns the NFT that this token is bound to. - // this function **MUST** throw if the token hasn't been minted yet - // this function **MUST** always return the same result every time it is called after it has been minted - // this function **MUST** return the same value as found in the original `Mint` event for the token - function ownerOf(uint256 index) external view returns (address nftAddress, uint256 nftTokenId); - - // returns a URI with details about this token collection - // the metadata returned by this is merged with the metadata return by `tokenUri(uint256)` - // the collectionUri **MUST** be immutable (e.g., ipfs:// and not http://) - // the collectionUri **MUST** be content addressable (e.g., ipfs:// and not http://) - // data from `tokenUri` takes precedence over data returned by this method - // any external links referenced by the content at `collectionUri` also **MUST** follow all of the above rules - function collectionUri() external pure returns (string collectionUri); - - // returns a censorship resistant URI with details about this token instance - // the collectionUri **MUST** be immutable (e.g., ipfs:// and not http://) - // the collectionUri **MUST** be content addressable (e.g., ipfs:// and not http://) - // data from this takes precedence over data returned by `collectionUri` - // any external links referenced by the content at `tokenUri` also **MUST** follow all of the above rules - function tokenUri(uint256 tokenId) external view returns (string tokenUri); - - // returns a string that indicates the format of the tokenUri and collectionUri results (e.g., 'EIP-ABCD' or 'soulbound-schema-version-4') - function metadataFormat() external pure returns (string format); -} -``` - -Implementers of this standard **SHOULD** also depend on a standard for interface detection so callers can easily find out if a given contract implements this interface. - - -## Rationale - -### Immutability - -By requiring that tokens can never move, we both guarantee non-separability and non-mergeability among collections of soulbound tokens that are bound to a single NFT while simultaneously allowing users to aggressively cache results. - -### Content Addressable URIs Required - -Soulbound tokens are meant to be permanent badges/indicators attached to a persona. -This means that not only can the user not transfer ownership, but the minter also cannot withdraw/transfer/change ownership as well. -This includes mutating or removing any remote content as a means of censoring or manipulating specific users. - -### No Specification for tokenUri Data Format - -The format of the data pointed to by `collectionUri()` and `tokenUri(uint256)` is intentionally left out of this standard in favor of separate standards that can be iterated on in the future. -The immutability constraints are the only thing defined by this to ensure that the spirit of this token is maintained, regardless of the specifics of the data format. -The `metadataFormat` function can be used to inform a caller what type/format/version of data they should expect at the URIs, so the caller can parse the data directly without first having to deduce its format via inspection. - - -## Backwards Compatibility - -This is a new token type and is not meant to be backward compatible with any existing tokens other than existing viable souls (any asset that can be identified by `[address,id]`). - - -## Security Considerations - -Users of tokens that claim to implement this EIP must be diligent in verifying they actually do. -A token author can create a token that, upon initial probing of the API surface, may appear to follow the rules when in reality it doesn't. -For example, the contract could allow transfers via some mechanism and simply not utilize them initially. - -It should also be made clear that soulbound tokens are not bound to a human, they are bound to a persona. -A persona is any actor (which could be a group of humans) that collects multiple soulbound tokens over time to build up a collection of badges. -This persona may transfer to another human, or to another group of humans, and anyone interacting with a persona should not assume that there is a single permanent human behind that persona. - -It is possible for a soulbound token to be bound to another soulbound token. -In theory, if all tokens in the chain are created at the same time they could form a loop. -Software that tries to walk such a chain should take care to have an exit strategy if a loop is detected. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5114.md diff --git a/EIPS/eip-5115.md b/EIPS/eip-5115.md index d93052455f2a34..bf95b31278dc77 100644 --- a/EIPS/eip-5115.md +++ b/EIPS/eip-5115.md @@ -1,349 +1,7 @@ --- eip: 5115 -title: SY Token -description: Interface for wrapped yield-bearing tokens. -author: Vu Nguyen (@mrenoon), Long Vuong (@UncleGrandpa925), Anton Buenavista (@ayobuenavista) -discussions-to: https://ethereum-magicians.org/t/eip-5115-super-composable-yield-token-standard/9423 -status: Draft -type: Standards Track category: ERC -created: 2022-05-30 -requires: 20 +status: Moved --- -## Abstract - -This standard proposes an API for wrapped yield-bearing tokens within smart contracts. It is an extension on the [EIP-20](./eip-20.md) token that provides basic functionality for transferring, depositing, withdrawing tokens, as well as reading balances. - -## Motivation - -Yield generating mechanisms are built in all shapes and sizes, necessitating a manual integration every time a protocol builds on top of another protocol’s yield generating mechanism. - -[EIP-4626](./eip-4626.md) tackled a significant part of this fragmentation by standardizing the interfaces for vaults, a major category among various yield generating mechanisms. - -In this EIP, we’re extending the coverage to include assets beyond EIP-4626’s reach, namely: - -- yield-bearing assets that have different input tokens used for minting vs accounting for the pool value. - - This category includes AMM liquidity tokens (which are yield-bearing assets that yield swap fees) since the value of the pool is measured in “liquidity units” (for example, $\sqrt k$ in UniswapV2, as defined in UniswapV2 whitepaper) which can’t be deposited in (as they are not tokens). - - This extends the flexibility in minting the yield-bearing assets. For example, there could be an ETH vault that wants to allow users to deposit cETH directly instead of ETH, for gas efficiency or UX reasons. -- Assets with reward tokens by default (e.g. COMP rewards for supplying in Compound). The reward tokens are expected to be sold to compound into the same asset. -- This EIP can be extended further to include the handling of rewards, such as the claiming of accrued multiple rewards tokens. - -While EIP-4626 is a well-designed and suitable standard for most vaults, there will inevitably be some yield generating mechanisms that do not fit into their category (LP tokens for instance). A more flexible standard is required to standardize the interaction with all types of yield generating mechanisms. - -Therefore, we are proposing Standardized Yield (SY), a flexible standard for wrapped yield-bearing tokens that could cover most mechanisms in DeFi. We foresee that: - -- EIP-4626 will still be a popular vault standard, that most vaults should adopt. -- SY tokens can wrap over most yield generating mechanisms in DeFi, including EIP-4626 vaults for projects built on top of yield-bearing tokens. -- Whoever needs the functionalities of SY could integrate with the existing SY tokens or write a new SY (to wrap over the target yield-bearing token). -- Reward handling can be extended from the SY token. - -### Use Cases - -This EIP is designed for flexibility, aiming to accommodate as many yield generating mechanisms as possible. Particularly, this standard aims to be generalized enough that it supports the following use cases and more: - -- Money market supply positions - - Lending DAI in Compound, getting DAI interests and COMP rewards - - Lending ETH in BenQi, getting ETH interests and QI + AVAX rewards - - Lending USDC in Aave, getting USDC interests and stkAAVE rewards -- AMM liquidity provision - - Provide ETH + USDC to ETHUSDC pool in SushiSwap, getting swap fees in more ETH+USDC - - Provide ETH + USDC to ETHUSDC pool in SushiSwap and stake it in Sushi Onsen, getting swap fees and SUSHI rewards - - Provide USDC+DAI+USDT to 3crv pool and stake it in Convex, getting 3crv swap fees and CRV + CVX rewards -- Vault positions - - Provide ETH into Yearn EIP-4626 vault, where the vault accrues yield from Yearn’s ETH strategy - - Provide DAI into Harvest and staking it, getting DAI interests and FARM rewards -- Liquid staking positions - - Holding stETH (in Lido), getting yields in more stETH -- Liquidity mining programs - - Provide USDC in Stargate, getting STG rewards - - Provide LOOKS in LooksRare, getting LOOKS yield and WETH rewards -- Rebasing tokens - - Stake OHM into sOHM/gOHM, getting OHM rebase yield - -The EIP hopes to minimize, if not possibly eliminate, the use of customized adapters in order to interact with many different forms of yield-bearing token mechanisms. - -## Specification - -### Generic Yield Generating Pool - -We will first introduce Generic Yield Generating Pool (GYGP), a model to describe most yield generating mechanisms in DeFi. In every yield generating mechanism, there is a pool of funds, whose value is measured in **assets**. There are a number of users who contribute liquidity to the pool, in exchange for **shares** of the pool, which represents units of ownership of the pool. Over time, the value (measured in **assets**) of the pool grows, such that each **share** is worth more **assets** over time. The pool could earn a number of **reward tokens** over time, which are distributed to the users according to some logic (for example, proportionally the number of **shares**). - -Here are the more concrete definitions of the terms: - -#### GYGP Definitions: - -- **asset**: Is a unit to measure the value of the pool. At time *t*, the pool has a total value of *TotalAsset(t)* **assets**. -- **shares**: Is a unit that represents ownership of the pool. At time *t*, there are *TotalShares(t)* **shares** in total. -- **reward tokens**: Over time, the pool earns $n_{rewards}$ types of reward tokens $(n_{rewards} \ge 0)$. At time *t*, $TotalRewards_i(t)$ is the amount of **reward token *i*** that has accumulated for the pool up until time *t*. -- **exchange rate**: At time *t*, the **exchange rate** *ExchangeRate(t)* is simply how many **assets** each **shares** is worth $ExchangeRate(t) = \frac{TotalAsset(t)}{TotalShares(t)}$ -- **users**: At time *t*, each user *u* has $shares_u(t)$ **shares** in the pool, which is worth $asset_u(t) = shares_u(t) \cdot ExchangeRate(t)$ **assets**. Until time *t*, user *u* is entitled to receive a total of $rewards_{u_i}(t)$ **reward token *i***. The sum of all users’ shares, assets and rewards should be the same as the total shares, assets and rewards of the whole pool. - -#### State changes: - -1. A user deposits $d_a$ **assets** into the pool at time $t$ ($d_a$ could be negative, which means a withdraw from the pool). $d_s = d_a / ExchangeRate(t)$ new **shares** will be created and given -to user (or removed and burned from the user when $d_a$ is negative). -2. The pool earns $d_a$ (or loses $−d_a$ if $d_a$ is negative) **assets** at time $t$. The **exchange rate** simply increases (or decreases if $d_a$ is negative) due to the additional assets. -3. The pool earns $d_r$ **reward token** $i$. Every user will receive a certain amount of **reward token** $i$. - -#### Examples of GYGPs in DeFi: - -| Yield generating mechanism | Asset | Shares | Reward tokens | Exchange rate | -| --- | --- | --- | --- | --- | -| Supply USDC in Compound | USDC | cUSDC | COMP | USDC value per cUSDC, increases with USDC supply interests | -| ETH liquid staking in Lido | stETH | wstETH | None | stETH value per wstETH, increases with ETH staking rewards | -| Stake LOOKS in LooksRare Compounder | LOOKS | shares (in contract) | WETH | LOOKS value per shares, increases with LOOKS rewards | -| Stake APE in $APE Compounder | sAPE | shares (in contract) | APE | sAPE value per shares, increases with APE rewards | -| Provide ETH+USDC liquidity on Sushiswap | ETHUSDC liquidity (a pool of x ETH + y USDC has sqrt(xy) ETHUSDC liquidity) | ETHUSDC Sushiswap LP (SLP) token | None | ETHUSDC liquidity value per ETHUSDC SLP, increases due to swap fees | -| Provide ETH+USDC liquidity on Sushiswap and stake into Onsen | ETHUSDC liquidity (a pool of x ETH + y USDC has sqrt(xy) ETHUSDC liquidity) | ETHUSDC Sushiswap LP (SLP) token | SUSHI | ETHUSDC liquidity value per ETHUSDC SLP, increases due to swap fees | -| Provide BAL+WETH liquidity in Balancer (80% BAL, 20% WETH) | BALWETH liquidity (a pool of x BAL + y WETH has x^0.8*y^0.2 BALWETH liquidity) | BALWETH Balancer LP token | None | BALWETH liquidity per BALWETH Balancer LP token, increases due to swap fees | -| Provide USDC+USDT+DAI liquidity in Curve | 3crv pool’s liquidity (amount of D per 3crv token) | 3crv token | CRV | 3crv pool’s liquidity per 3crv token, increases due to swap fees | -| Provide FRAX+USDC liquidity in Curve then stake LP in Convex | BALWETH liquidity (a pool of x BAL + y WETH has x^0.8*y^0.2 BALWETH liquidity) | BALWETH Balancer LP token | None | BALWETH liquidity per BALWETH Balancer LP token, increases due to swap fees | - - -### Standardized Yield Token Standard - -#### Overview: - -Standardized Yield (SY) is a token standard for any yield generating mechanism that conforms to the GYGP model. Each SY token represents **shares** in a GYGP and allows for interacting with the GYGP via a standard interface. - -All SY tokens: - -- **MUST** implement **`EIP-20`** to represent shares in the underlying GYGP. -- **MUST** implement EIP-20’s optional metadata extensions `name`, `symbol`, and `decimals`, which **SHOULD** reflect the underlying GYGP’s accounting asset’s `name`, `symbol`, and `decimals`. -- **MAY** implement [EIP-2612](./eip-2612.md) to improve the UX of approving SY tokens on various integrations. -- **MAY** revert on calls to `transfer` and `transferFrom` if a SY token is to be non-transferable. -- The EIP-20 operations `balanceOf`, `transfer`, `totalSupply`, etc. **SHOULD** operate on the GYGP “shares”, which represent a claim to ownership on a fraction of the GYGP’s underlying holdings. - -#### SY Definitions: - -On top of the definitions above for GYGPs, we need to define 2 more concepts: - -- **input tokens**: Are tokens that can be converted into assets to enter the pool. Each SY can accept several possible input tokens $tokens_{in_{i}}$ - -- **output tokens**: Are tokens that can be redeemed from assets when exiting the pool. Each SY can have several possible output tokens $tokens_{out_{i}}$ - -#### Interface - -```solidity -interface IStandardizedYield { - event Deposit( - address indexed caller, - address indexed receiver, - address indexed tokenIn, - uint256 amountDeposited, - uint256 amountSyOut - ); - - event Redeem( - address indexed caller, - address indexed receiver, - address indexed tokenOut, - uint256 amountSyToRedeem, - uint256 amountTokenOut - ); - - function deposit( - address receiver, - address tokenIn, - uint256 amountTokenToDeposit, - uint256 minSharesOut, - bool depositFromInternalBalance - ) external returns (uint256 amountSharesOut); - - function redeem( - address receiver, - uint256 amountSharesToRedeem, - address tokenOut, - uint256 minTokenOut, - bool burnFromInternalBalance - ) external returns (uint256 amountTokenOut); - - function exchangeRate() external view returns (uint256 res); - - function getTokensIn() external view returns (address[] memory res); - - function getTokensOut() external view returns (address[] memory res); - - function yieldToken() external view returns (address); - - function previewDeposit(address tokenIn, uint256 amountTokenToDeposit) - external - view - returns (uint256 amountSharesOut); - - function previewRedeem(address tokenOut, uint256 amountSharesToRedeem) - external - view - returns (uint256 amountTokenOut); - - function name() external view returns (string memory); - - function symbol() external view returns (string memory); - - function decimals() external view returns (uint8); -} -``` - -#### Methods - -```solidity -function deposit( - address receiver, - address tokenIn, - uint256 amountTokenToDeposit, - uint256 minSharesOut, - bool depositFromInternalBalance -) external returns (uint256 amountSharesOut); -``` - -This function will deposit *amountTokenToDeposit* of input token $i$ (*tokenIn*) to mint new SY shares. - -If *depositFromInternalBalance* is set to *false*, msg.sender will need to initially deposit *amountTokenToDeposit* of input token $i$ (*tokenIn*) into the SY contract, then this function will convert the *amountTokenToDeposit* of input token $i$ into $d_a$ worth of **asset** and deposit this amount into the pool for the *receiver*, who will receive *amountSharesOut* of SY tokens (**shares**). If *depositFromInternalBalance* is set to *true*, then *amountTokenToDeposit* of input token $i$ (*tokenIn*) will be taken from receiver directly (as msg.sender), and will be converted and shares returned to the receiver similarly to the first case. - -This function should revert if $amountSharesOut \lt minSharesOut$. - -- **MUST** emit the `Deposit` event. -- **MUST** support EIP-20’s `approve` / `transferFrom` flow where `tokenIn` are taken from receiver directly (as msg.sender) or if the msg.sender has EIP-20 approved allowance over the input token of the receiver. -- **MUST** revert if $amountSharesOut \lt minSharesOut$ (due to deposit limit being reached, slippage, or the user not approving enough `tokenIn` **to the SY contract, etc). -- **MAY** be payable if the `tokenIn` depositing asset is the chain's native currency (e.g. ETH). - -```solidity -function redeem( - address receiver, - uint256 amountSharesToRedeem, - address tokenOut, - uint256 minTokenOut, - bool burnFromInternalBalance -) external returns (uint256 amountTokenOut); -``` - -This function will redeem the $d_s$ shares, which is equivalent to $d_a = d_s \times ExchangeRate(t)$ assets, from the pool. The $d_a$ assets is converted into exactly *amountTokenOut* of output token $i$ (*tokenOut*). - -If *burnFromInternalBalance* is set to *false*, the user will need to initially deposit *amountSharesToRedeem* into the SY contract, then this function will burn the floating amount $d_s$ of SY tokens (**shares**) in the SY contract to redeem to output token $i$ (*tokenOut*). This pattern is similar to UniswapV2 which allows for more gas efficient ways to interact with the contract. If *burnFromInternalBalance* is set to *true*, then this function will burn *amountSharesToRedeem* $d_s$ of SY tokens directly from the user to redeem to output token $i$ (*tokenOut*). - -This function should revert if $amountTokenOut \lt minTokenOut$. - -- **MUST** emit the `Redeem` event. -- **MUST** support EIP-20’s `approve` / `transferFrom` flow where the shares are burned from receiver directly (as msg.sender) or if the msg.sender has EIP-20 approved allowance over the shares of the receiver. -- **MUST** revert if $amountTokenOut \lt minTokenOut$ (due to redeem limit being reached, slippage, or the user not approving enough `amountSharesToRedeem` to the SY contract, etc). - -```solidity -function exchangeRate() external view returns (uint256 res); -``` - -This method updates and returns the latest **exchange rate**, which is the **exchange rate** from SY token amount into asset amount, scaled by a fixed scaling factor of 1e18. - -- **MUST** return $ExchangeRate(t_{now})$ such that $ExchangeRate(t_{now}) \times syBalance / 1e18 = assetBalance$. -- **MUST NOT** include fees that are charged against the underlying yield token in the SY contract. - -```solidity -function getTokensIn() external view returns (address[] memory res); -``` - -This read-only method returns the list of all input tokens that can be used to deposit into the SY contract. - -- **MUST** return EIP-20 token addresses. -- **MUST** return at least one address. -- **MUST NOT** revert. - -```solidity -function getTokensOut() external view returns (address[] memory res); -``` - -This read-only method returns the list of all output tokens that can be converted into when exiting the SY contract. - -- **MUST** return EIP-20 token addresses. -- **MUST** return at least one address. -- **MUST NOT** revert. - -```solidity -function yieldToken() external view returns (address); -``` - -This read-only method returns the underlying yield-bearing token (representing a GYGP) address. - -- **MUST** return a token address that conforms to the EIP-20 interface, or zero address -- **MUST NOT** revert. -- **MUST** reflect the exact underlying yield-bearing token address if the SY token is a wrapped token. -- **MAY** return 0x or zero address if the SY token is natively implemented, and not from wrapping. - -```solidity -function previewDeposit(address tokenIn, uint256 amountTokenToDeposit) - external - view - returns (uint256 amountSharesOut); -``` - -This read-only method returns the amount of shares that a user would have received if they deposit *amountTokenToDeposit* of *tokenIn*. - -- **MUST** return less than or equal of *amountSharesOut* to the actual return value of the `deposit` method, and **SHOULD NOT** return greater than the actual return value of the `deposit` method. -- **MUST NOT** revert. - -```solidity -function previewRedeem(address tokenOut, uint256 amountSharesToRedeem) - external - view - returns (uint256 amountTokenOut); -``` - -This read-only method returns the amount of *tokenOut* that a user would have received if they redeem *amountSharesToRedeem* of *tokenOut*. - -- **MUST** return less than or equal of *amountTokenOut* to the actual return value of the `redeem` method, and **SHOULD NOT** return greater than the actual return value of the `redeem` method. -- **MUST NOT** revert. - -#### Events - -```solidity -event Deposit( - address indexed caller, - address indexed receiver, - address indexed tokenIn, - uint256 amountDeposited, - uint256 amountSyOut -); -``` - -`caller` has converted exact *tokenIn* tokens into SY (shares) and transferred those SY to `receiver`. - -- **MUST** be emitted when input tokens are deposited into the SY contract via `deposit` method. - -```solidity -event Redeem( - address indexed caller, - address indexed receiver, - address indexed tokenOut, - uint256 amountSyToRedeem, - uint256 amountTokenOut -); -``` - -`caller` has converted exact SY (shares) into input tokens and transferred those input tokens to `receiver`. - -- **MUST** be emitted when input tokens are redeemed from the SY contract via `redeem` method. - -**"SY" Word Choice:** - -"SY" (pronunciation: */sʌɪ/*), an abbreviation of Standardized Yield, was found to be appropriate to describe a broad universe of standardized composable yield-bearing digital assets. - -## Rationale - -[EIP-20](./eip-20.md) is enforced because implementation details such as transfer, token approvals, and balance calculation directly carry over to the SY tokens. This standardization makes the SY tokens immediately compatible with all EIP-20 use cases. - -[EIP-165](./eip-165.md) can optionally be implemented should you want integrations to detect the IStandardizedYield interface implementation. - -[EIP-2612](./eip-2612.md) can optionally be implemented in order to improve the UX of approving SY tokens on various integrations. - -## Backwards Compatibility - -This EIP is fully backwards compatible as its implementation extends the functionality of [EIP-20](./eip-20.md), however the optional metadata extensions, namely `name`, `decimals`, and `symbol` semantics MUST be implemented for all SY token implementations. - -## Security Considerations - -Malicious implementations which conform to the interface can put users at risk. It is recommended that all integrators (such as wallets, aggregators, or other smart contract protocols) review the implementation to avoid possible exploits and users losing funds. - -`yieldToken` must strongly reflect the address of the underlying wrapped yield-bearing token. For a native implementation wherein the SY token does not wrap a yield-bearing token, but natively represents a GYGP share, then the address returned MAY be a zero address. Otherwise, for wrapped tokens, you may introduce confusion on what the SY token represents, or may be deemed malicious. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5115.md diff --git a/EIPS/eip-5131.md b/EIPS/eip-5131.md index 54f093590c44e9..b6e1f6590301a3 100644 --- a/EIPS/eip-5131.md +++ b/EIPS/eip-5131.md @@ -1,343 +1,7 @@ --- eip: 5131 -title: SAFE Authentication For ENS -description: Using ENS Text Records to facilitate safer and more convenient signing operations. -author: Wilkins Chung (@wwhchung), Jalil Wahdatehagh (@jwahdatehagh), Cry (@crydoteth), Sillytuna (@sillytuna), Cyberpnk (@CyberpnkWin) -discussions-to: https://ethereum-magicians.org/t/eip-5131-ens-subdomain-authentication/9458 -status: Stagnant -type: Standards Track category: ERC -created: 2022-06-03 -requires: 137, 181, 634 +status: Moved --- -## Abstract -This EIP links one or more signing wallets via Ethereum Name Service Specification ([EIP-137](./eip-137.md)) to prove control and asset ownership of a main wallet. - -## Motivation -Proving ownership of an asset to a third party application in the Ethereum ecosystem is common. Users frequently sign payloads of data to authenticate themselves before gaining access to perform some operation. However, this method--akin to giving the third party root access to one's main wallet--is both insecure and inconvenient. - -***Examples:*** - 1. In order for you to edit your profile on OpenSea, you must sign a message with your wallet. - 2. In order to access NFT gated content, you must sign a message with the wallet containing the NFT in order to prove ownership. - 3. In order to gain access to an event, you must sign a message with the wallet containing a required NFT in order to prove ownership. - 4. In order to claim an airdrop, you must interact with the smart contract with the qualifying wallet. - 5. In order to prove ownership of an NFT, you must sign a payload with the wallet that owns that NFT. - -In all the above examples, one interacts with the dApp or smart contract using the wallet itself, which may be - - inconvenient (if it is controlled via a hardware wallet or a multi-sig) - - insecure (since the above operations are read-only, but you are signing/interacting via a wallet that has write access) - -Instead, one should be able to approve multiple wallets to authenticate on behalf of a given wallet. - -### Problems with existing methods and solutions -Unfortunately, we've seen many cases where users have accidentally signed a malicious payload. The result is almost always a significant loss of assets associated with the signing address. - -In addition to this, many users keep significant portions of their assets in 'cold storage'. With the increased security from 'cold storage' solutions, we usually see decreased accessibility because users naturally increase the barriers required to access these wallets. - -Some solutions propose dedicated registry smart contracts to create this link, or new protocols to be supported. This is problematic from an adoption standpoint, and there have not been any standards created for them. - -### Proposal: Use the Ethereum Name Service (EIP-137) -Rather than 're-invent the wheel', this proposal aims to use the widely adopted Ethereum Name Service in conjunction with the ENS Text Records feature ([EIP-634](./eip-634.md)) in order to achieve a safer and more convenient way to sign and authenticate, and provide 'read only' access to a main wallet via one or more secondary wallets. - -From there, the benefits are twofold. This EIP gives users increased security via outsourcing potentially malicious signing operations to wallets that are more accessible (hot wallets), while being able to maintain the intended security assumptions of wallets that are not frequently used for signing operations. - -#### Improving dApp Interaction Security -Many dApps requires one to prove control of a wallet to gain access. At the moment, this means that you must interact with the dApp using the wallet itself. This is a security issue, as malicious dApps or phishing sites can lead to the assets of the wallet being compromised by having them sign malicious payloads. - -However, this risk would be mitigated if one were to use a secondary wallet for these interactions. Malicious interactions would be isolated to the assets held in the secondary wallet, which can be set up to contain little to nothing of value. - -#### Improving Multiple Device Access Security -In order for a non-hardware wallet to be used on multiple devices, you must import the seed phrase to each device. Each time a seed phrase is entered on a new device, the risk of the wallet being compromised increases as you are increasing the surface area of devices that have knowledge of the seed phrase. - -Instead, each device can have its own unique wallet that is an authorized secondary wallet of the main wallet. If a device specific wallet was ever compromised or lost, you could simply remove the authorization to authenticate. - -Further, wallet authentication can be chained so that a secondary wallet could itself authorize one or many tertiary wallets, which then have signing rights for both the secondary address as well as the root main address. This, can allow teams to each have their own signer while the main wallet can easily invalidate an entire tree, just by revoking rights from the root stem. - -#### Improving Convenience -Many invididuals use hardware wallets for maximum security. However, this is often inconvenient, since many do not want to carry their hardware wallet with them at all times. - -Instead, if you approve a non-hardware wallet for authentication activities (such as a mobile device), you would be able to use most dApps without the need to have your hardware wallet on hand. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Let: - - `mainAddress` represent the wallet address we are trying to authenticate or prove asset ownership for. - - `mainENS` represent the reverse lookup ENS string for `mainAddress`. - - `authAddress` represent the address we want to use for signing in lieu of `mainAddress`. - - `authENS` represent the reverse lookup ENS string for `authAddress`. - - `authKey` represents a string in the format `[0-9A-Za-z]+`. - -Control of `mainAddress` and ownership of `mainAddress` assets by `authAddress` is proven if all the following conditions are met: - - `mainAddress` has an ENS resolver record and a reverse record set to `mainENS`. - - `authAddress` has an ENS resolver record and a reverse record set to `authENS`. - - `authENS` has an ENS TEXT record `eip5131:vault` in the format `:`. - - `mainENS` has an ENS TEXT record `eip5131:`. - -### Setting up one or many `authAddress` records on a single ENS domain -The `mainAddress` MUST have an ENS resolver record and reverse record configured. -In order to automatically discover the linked account, the `authAddress` SHOULD have an ENS resolver record and reverse record configured. - -1. Choose an unused ``. This can be any string in the format `[0-0A-Za-z]+`. -2. Set a TEXT record `eip5131:` on `mainENS`, with the value set to the desired `authAddress`. -3. Set a TEXT record `eip5131:vault` on `authENS`, with the value set to the `:mainAddress`. - -Currently this EIP does not enforce an upper-bound on the number of `authAddress` entries you can include. Users can repeat this process with as many address as they like. - -### Authenticating `mainAddress` via `authAddress` -Control of `mainAddress` and ownership of `mainAddress` assets is proven if any associated `authAddress` is the `msg.sender` or has signed the message. - -Practically, this would work by performing the following operations: -1. Get the resolver for `authENS` -2. Get the `eip5131:vault` TEXT record of `authENS` -3. Parse `:` to determine the `authKey` and `mainAddress`. -4. MUST get the reverse ENS record for `mainAddress` and verify that it matches ``. - - Otherwise one could set up other ENS nodes (with auths) that point to `mainAddress` and authenticate via those. -5. Get the `eip5131:` TEXT record of `mainENS` and ensure it matches `authAddress`. - -Note that this specification allows for both contract level and client/server side validation of signatures. It is not limited to smart contracts, which is why there is no proposed external interface definition. - -### Revocation of `authAddress` -To revoke permission of `authAddress`, delete the `eip5131:` TEXT record of `mainENS` or update it to point to a new `authAddress`. - -## Rationale - -### Usage of EIP-137 -The proposed specification makes use of EIP-137 rather than introduce another registry paradigm. The reason for this is due to the existing wide adoption of EIP-137 and ENS. - -However, the drawback to EIP-137 is that any linked `authAddress` must contain some ETH in order to set the `authENS` reverse record as well as the `eip5131:vault` TEXT record. This can be solved by a separate reverse lookup registry that enables `mainAddress` to set the reverse record and TEXT record with a message signed by `authAddress`. - -With the advent of L2s and ENS Layer 2 functionalities, off chain verification of linked addresses is possible even with domains managed across different chains. - -### One-to-Many Authentication Relationship -This proposed specification allows for a one (`mainAddress`) to many (`authAddress`) authentication relationship. i.e. one `mainAddress` can authorize many `authAddress` to authenticate, but an `authAddress` can only authenticate itself or a single `mainAddress`. - -The reason for this design choice is to allow for simplicity of authentication via client and smart contract code. You can determine which `mainAddress` the `authAddress` is signing for without any additional user input. - -Further, you can design UX without any user interaction necessary to 'pick' the interacting address by display assets owned by `authAddress` and `mainAddress` and use the appropriate address dependent on the asset the user is attempting to authenticate with. - -## Reference Implementation - -### Client/Server Side -In typescript, the validation function, using ethers.js would be as follows: -``` -export interface LinkedAddress { - ens: string, - address: string, -} - -export async function getLinkedAddress( - provider: ethers.providers.EnsProvider, address: string -): Promise { - const addressENS = await provider.lookupAddress(address); - if (!addressENS) return null; - - const vaultInfo = await (await provider.getResolver(addressENS))?.getText('eip5131:vault'); - if (!vaultInfo) return null; - - const vaultInfoArray = vaultInfo.split(':'); - if (vaultInfoArray.length !== 2) { - throw new Error('EIP5131: Authkey and vault address not configured correctly.'); - } - - const [ authKey, vaultAddress ] = vaultInfoArray; - - const vaultENS = await provider.lookupAddress(vaultAddress); - if (!vaultENS) { - throw new Error(`EIP5131: No ENS domain with reverse record set for vault.`); - }; - - const expectedSigningAddress = await ( - await provider.getResolver(vaultENS) - )?.getText(`eip5131:${authKey}`); - - if (expectedSigningAddress?.toLowerCase() !== address.toLowerCase()) { - throw new Error(`EIP5131: Authentication mismatch.`); - }; - - return { - ens: vaultENS, - address: vaultAddress - }; -} -``` - -### Contract side - -#### With a backend -If your application operates a secure backend server, you could run the client/server code above, then use the result in conjunction with specs like [EIP-1271](./eip-1271.md) : `Standard Signature Validation Method for Contracts` for a cheap and secure way to validate that the the message signer is indeed authenticated for the main address. - -#### Without a backend (JavaScript only) -Provided is a reference implementation for an internal function to verify that the message sender has an authentication link to the main address. - -``` -// SPDX-License-Identifier: MIT - -pragma solidity ^0.8.0; - -/// @author: manifold.xyz - -/** - * ENS Registry Interface - */ -interface ENS { - function resolver(bytes32 node) external view returns (address); -} - -/** - * ENS Resolver Interface - */ -interface Resolver { - function addr(bytes32 node) external view returns (address); - function name(bytes32 node) external view returns (string memory); - function text(bytes32 node, string calldata key) external view returns (string memory); -} - -/** - * Validate a signing address is associtaed with a linked address - */ -library LinkedAddress { - /** - * Validate that the message sender is an authentication address for mainAddress - * - * @param ensRegistry Address of ENS registry - * @param mainAddress The main address we want to authenticate for. - * @param mainENSNodeHash The main ENS Node Hash - * @param authKey The TEXT record of the authKey we are using for validation - * @param authENSNodeHash The auth ENS Node Hash - */ - function validateSender( - address ensRegistry, - address mainAddress, - bytes32 mainENSNodeHash, - string calldata authKey, - bytes32 authENSNodeHash - ) internal view returns (bool) { - return validate(ensRegistry, mainAddress, mainENSNodeHash, authKey, msg.sender, authENSNodeHash); - } - - /** - * Validate that the authAddress is an authentication address for mainAddress - * - * @param ensRegistry Address of ENS registry - * @param mainAddress The main address we want to authenticate for. - * @param mainENSNodeHash The main ENS Node Hash - * @param authAddress The address of the authentication wallet - * @param authENSNodeHash The auth ENS Node Hash - */ - function validate( - address ensRegistry, - address mainAddress, - bytes32 mainENSNodeHash, - string calldata authKey, - address authAddress, - bytes32 authENSNodeHash - ) internal view returns (bool) { - _verifyMainENS(ensRegistry, mainAddress, mainENSNodeHash, authKey, authAddress); - _verifyAuthENS(ensRegistry, mainAddress, authKey, authAddress, authENSNodeHash); - - return true; - } - - // ********************* - // Helper Functions - // ********************* - function _verifyMainENS( - address ensRegistry, - address mainAddress, - bytes32 mainENSNodeHash, - string calldata authKey, - address authAddress - ) private view { - // Check if the ENS nodes resolve correctly to the provided addresses - address mainResolver = ENS(ensRegistry).resolver(mainENSNodeHash); - require(mainResolver != address(0), "Main ENS not registered"); - require(mainAddress == Resolver(mainResolver).addr(mainENSNodeHash), "Main address is wrong"); - - // Verify the authKey TEXT record is set to authAddress by mainENS - string memory authText = Resolver(mainResolver).text(mainENSNodeHash, string(abi.encodePacked("eip5131:", authKey))); - require( - keccak256(bytes(authText)) == keccak256(bytes(_addressToString(authAddress))), - "Invalid auth address" - ); - } - - function _verifyAuthENS( - address ensRegistry, - address mainAddress, - string memory authKey, - address authAddress, - bytes32 authENSNodeHash - ) private view { - // Check if the ENS nodes resolve correctly to the provided addresses - address authResolver = ENS(ensRegistry).resolver(authENSNodeHash); - require(authResolver != address(0), "Auth ENS not registered"); - require(authAddress == Resolver(authResolver).addr(authENSNodeHash), "Auth address is wrong"); - - // Verify the TEXT record is appropriately set by authENS - string memory vaultText = Resolver(authResolver).text(authENSNodeHash, "eip5131:vault"); - require( - keccak256(abi.encodePacked(authKey, ":", _addressToString(mainAddress))) == - keccak256(bytes(vaultText)), - "Invalid auth text record" - ); - } - - bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; - - function sha3HexAddress(address addr) private pure returns (bytes32 ret) { - uint256 value = uint256(uint160(addr)); - bytes memory buffer = new bytes(40); - for (uint256 i = 39; i > 1; --i) { - buffer[i] = _HEX_SYMBOLS[value & 0xf]; - value >>= 4; - } - return keccak256(buffer); - } - - function _addressToString(address addr) private pure returns (string memory ptr) { - // solhint-disable-next-line no-inline-assembly - assembly { - ptr := mload(0x40) - - // Adjust mem ptr and keep 32 byte aligned - // 32 bytes to store string length; address is 42 bytes long - mstore(0x40, add(ptr, 96)) - - // Store (string length, '0', 'x') (42, 48, 120) - // Single write by offsetting across 32 byte boundary - ptr := add(ptr, 2) - mstore(ptr, 0x2a3078) - - // Write string backwards - for { - // end is at 'x', ptr is at lsb char - let end := add(ptr, 31) - ptr := add(ptr, 71) - } gt(ptr, end) { - ptr := sub(ptr, 1) - addr := shr(4, addr) - } { - let v := and(addr, 0xf) - // if > 9, use ascii 'a-f' (no conditional required) - v := add(v, mul(gt(v, 9), 39)) - // Add ascii for '0' - v := add(v, 48) - mstore8(ptr, v) - } - - // return ptr to point to length (32 + 2 for '0x' - 1) - ptr := sub(ptr, 33) - } - - return string(ptr); - } -} -``` - -## Security Considerations -The core purpose of this EIP is to enhance security and promote a safer way to authenticate wallet control and asset ownership when the main wallet is not needed and assets held by the main wallet do not need to be moved. Consider it a way to do 'read only' authentication. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5131.md diff --git a/EIPS/eip-5139.md b/EIPS/eip-5139.md index c3bd49758e581c..986243b12e3e38 100644 --- a/EIPS/eip-5139.md +++ b/EIPS/eip-5139.md @@ -1,602 +1,7 @@ --- eip: 5139 -title: Remote Procedure Call Provider Lists -description: Format for lists of RPC providers for Ethereum-like chains. -author: Sam Wilson (@SamWilsn) -discussions-to: https://ethereum-magicians.org/t/eip-5139-remote-procedure-call-provider-lists/9517 -status: Draft -type: Standards Track category: ERC -created: 2022-06-06 -requires: 155, 1577 +status: Moved --- -## Abstract -This proposal specifies a JSON schema for describing lists of remote procedure call (RPC) providers for Ethereum-like chains, including their supported [EIP-155](./eip-155.md) `CHAIN_ID`. - -## Motivation -The recent explosion of alternate chains, scaling solutions, and other mostly Ethereum-compatible ledgers has brought with it many risks for users. It has become commonplace to blindly add new RPC providers using [EIP-3085](./eip-3085.md) without evaluating their trustworthiness. At best, these RPC providers may be accurate, but track requests; and at worst, they may provide misleading information and frontrun transactions. - -If users instead are provided with a comprehensive provider list built directly by their wallet, with the option of switching to whatever list they so choose, the risk of these malicious providers is mitigated significantly, without sacrificing functionality for advanced users. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### List Validation & Schema - -List consumers (like wallets) MUST validate lists against the provided schema. List consumers MUST NOT connect to RPC providers present only in an invalid list. - -Lists MUST conform to the following JSON Schema: - -```json -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - - "title": "Ethereum RPC Provider List", - "description": "Schema for lists of RPC providers compatible with Ethereum wallets.", - - "$defs": { - "VersionBase": { - "type": "object", - "description": "Version of a list, used to communicate changes.", - - "required": [ - "major", - "minor", - "patch" - ], - - "properties": { - "major": { - "type": "integer", - "description": "Major version of a list. Incremented when providers are removed from the list or when their chain ids change.", - "minimum": 0 - }, - - "minor": { - "type": "integer", - "description": "Minor version of a list. Incremented when providers are added to the list.", - "minimum": 0 - }, - - "patch": { - "type": "integer", - "description": "Patch version of a list. Incremented for any change not covered by major or minor versions, like bug fixes.", - "minimum": 0 - }, - - "preRelease": { - "type": "string", - "description": "Pre-release version of a list. Indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its major, minor, and patch versions.", - "pattern": "^[1-9A-Za-z][0-9A-Za-z]*(\\.[1-9A-Za-z][0-9A-Za-z]*)*$" - } - } - }, - - "Version": { - "type": "object", - "additionalProperties": false, - - "allOf": [ - { - "$ref": "#/$defs/VersionBase" - } - ], - - "properties": { - "major": true, - "minor": true, - "patch": true, - "preRelease": true, - "build": { - "type": "string", - "description": "Build metadata associated with a list.", - "pattern": "^[0-9A-Za-z-]+(\\.[0-9A-Za-z-])*$" - } - } - }, - - "VersionRange": { - "type": "object", - "additionalProperties": false, - - "properties": { - "major": true, - "minor": true, - "patch": true, - "preRelease": true, - "mode": true - }, - - "allOf": [ - { - "$ref": "#/$defs/VersionBase" - } - ], - - "oneOf": [ - { - "properties": { - "mode": { - "type": "string", - "enum": ["^", "="] - }, - "preRelease": false - } - }, - { - "required": [ - "preRelease", - "mode" - ], - - "properties": { - "mode": { - "type": "string", - "enum": ["="] - } - } - } - ] - }, - - "Logo": { - "type": "string", - "description": "A URI to a logo; suggest SVG or PNG of size 64x64", - "format": "uri" - }, - - "ProviderChain": { - "type": "object", - "description": "A single chain supported by a provider", - "additionalProperties": false, - "required": [ - "chainId", - "endpoints" - ], - "properties": { - "chainId": { - "type": "integer", - "description": "Chain ID of an Ethereum-compatible network", - "minimum": 1 - }, - "endpoints": { - "type": "array", - "minItems": 1, - "uniqueItems": true, - "items": { - "type": "string", - "format": "uri" - } - } - } - }, - - "Provider": { - "type": "object", - "description": "Description of an RPC provider.", - "additionalProperties": false, - - "required": [ - "chains", - "name" - ], - - "properties": { - "name": { - "type": "string", - "description": "Name of the provider.", - "minLength": 1, - "maxLength": 40, - "pattern": "^[ \\w.'+\\-%/À-ÖØ-öø-ÿ:&\\[\\]\\(\\)]+$" - }, - "logo": { - "$ref": "#/$defs/Logo" - }, - "priority": { - "type": "integer", - "description": "Priority of this provider (where zero is the highest priority.)", - "minimum": 0 - }, - "chains": { - "type": "array", - "items": { - "$ref": "#/$defs/ProviderChain" - } - } - } - }, - - "Path": { - "description": "A JSON Pointer path.", - "type": "string" - }, - - "Patch": { - "items": { - "oneOf": [ - { - "additionalProperties": false, - "required": ["value", "op", "path"], - "properties": { - "path": { - "$ref": "#/$defs/Path" - }, - "op": { - "description": "The operation to perform.", - "type": "string", - "enum": ["add", "replace", "test"] - }, - "value": { - "description": "The value to add, replace or test." - } - } - }, - { - "additionalProperties": false, - "required": ["op", "path"], - "properties": { - "path": { - "$ref": "#/$defs/Path" - }, - "op": { - "description": "The operation to perform.", - "type": "string", - "enum": ["remove"] - } - } - }, - { - "additionalProperties": false, - "required": ["from", "op", "path"], - "properties": { - "path": { - "$ref": "#/$defs/Path" - }, - - "op": { - "description": "The operation to perform.", - "type": "string", - "enum": ["move", "copy"] - }, - "from": { - "$ref": "#/$defs/Path", - "description": "A JSON Pointer path pointing to the location to move/copy from." - } - } - } - ] - }, - "type": "array" - } - }, - - "type": "object", - "additionalProperties": false, - - "required": [ - "name", - "version", - "timestamp" - ], - - "properties": { - "name": { - "type": "string", - "description": "Name of the provider list", - "minLength": 1, - "maxLength": 40, - "pattern": "^[\\w ]+$" - }, - "logo": { - "$ref": "#/$defs/Logo" - }, - "version": { - "$ref": "#/$defs/Version" - }, - "timestamp": { - "type": "string", - "format": "date-time", - "description": "The timestamp of this list version; i.e. when this immutable version of the list was created" - }, - "extends": true, - "changes": true, - "providers": true - }, - - "oneOf": [ - { - "type": "object", - - "required": [ - "extends", - "changes" - ], - - "properties": { - "providers": false, - - "extends": { - "type": "object", - "additionalProperties": false, - - "required": [ - "version" - ], - - "properties": { - "uri": { - "type": "string", - "format": "uri", - "description": "Location of the list to extend, as a URI." - }, - "ens": { - "type": "string", - "description": "Location of the list to extend using EIP-1577." - }, - "version": { - "$ref": "#/$defs/VersionRange" - } - }, - - "oneOf": [ - { - "properties": { - "uri": false, - "ens": true - } - }, - { - "properties": { - "ens": false, - "uri": true - } - } - ] - }, - "changes": { - "$ref": "#/$defs/Patch" - } - } - }, - { - "type": "object", - - "required": [ - "providers" - ], - - "properties": { - "changes": false, - "extends": false, - "providers": { - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/Provider" - } - } - } - } - ] -} -``` - -For illustrative purposes, the following is an example list following the schema: - -```json -{ - "name": "Example Provider List", - "version": { - "major": 0, - "minor": 1, - "patch": 0, - "build": "XPSr.p.I.g.l" - }, - "timestamp": "2004-08-08T00:00:00.0Z", - "logo": "https://mylist.invalid/logo.png", - "providers": { - "some-key": { - "name": "Frustrata", - "chains": [ - { - "chainId": 1, - "endpoints": [ - "https://mainnet1.frustrata.invalid/", - "https://mainnet2.frustrana.invalid/" - ] - }, - { - "chainId": 3, - "endpoints": [ - "https://ropsten.frustrana.invalid/" - ] - } - ] - }, - "other-key": { - "name": "Sourceri", - "priority": 3, - "chains": [ - { - "chainId": 1, - "endpoints": [ - "https://mainnet.sourceri.invalid/" - ] - }, - { - "chainId": 42, - "endpoints": [ - "https://kovan.sourceri.invalid" - ] - } - ] - } - } -} -``` - -### Versioning - -List versioning MUST follow the [Semantic Versioning 2.0.0](../assets/eip-5139/semver.md) (SemVer) specification. - -The major version MUST be incremented for the following modifications: - - - Removing a provider. - - Changing a provider's key in the `providers` object. - - Removing the last `ProviderChain` for a chain id. - -The major version MAY be incremented for other modifications, as permitted by SemVer. - -If the major version is not incremented, the minor version MUST be incremented if any of the following modifications are made: - - - Adding a provider. - - Adding the first `ProviderChain` of a chain id. - -The minor version MAY be incremented for other modifications, as permitted by SemVer. - -If the major and minor versions are unchanged, the patch version MUST be incremented for any change. - -### Publishing - -Provider lists SHOULD be published to an Ethereum Name Service (ENS) name using [EIP-1577](./eip-1577.md)'s `contenthash` mechanism on mainnet. - -Provider lists MAY instead be published using HTTPS. Provider lists published in this way MUST allow reasonable access from other origins (generally by setting the header `Access-Control-Allow-Origin: *`.) - -### Priority - -Provider entries MAY contain a `priority` field. A `priority` value of zero SHALL indicate the highest priority, with increasing `priority` values indicating decreasing priority. Multiple providers MAY be assigned the same priority. All providers without a `priority` field SHALL have equal priority. Providers without a `priority` field SHALL always have a lower priority than any provider with a `priority` field. - -List consumers MAY use `priority` fields to choose when to connect to a provider, but MAY ignore it entirely. List consumers SHOULD explain to users how their implementation interprets `priority`. - -### List Subtypes - -Provider lists are subdivided into two categories: root lists, and extension lists. A root list contains a list of providers, while an extension list contains a set of modifications to apply to another list. - -#### Root Lists - -A root list has a top-level `providers` key. - -#### Extension Lists - -An extension list has top-level `extends` and `changes` keys. - -##### Specifying a Parent (`extends`) - -The `uri` and `ens` fields SHALL point to a source for the parent list. - -If present, the `uri` field MUST use a scheme specified in [Publishing](#publishing). - -If present, the `ens` field MUST specify an ENS name to be resolved using EIP-1577. - -The `version` field SHALL specify a range of compatible versions. List consumers MUST reject extension lists specifying an incompatible parent version. - -In the event of an incompatible version, list consumers MAY continue to use a previously saved parent list, but list consumers choosing to do so MUST display a prominent warning that the provider list is out of date. - -###### Default Mode - -If the `mode` field is omitted, a parent version SHALL be compatible if and only if the parent's version number matches the left-most non-zero portion in the major, minor, patch grouping. - -For example: - -```javascript -{ - "major": "1", - "minor": "2", - "patch": "3" -} -``` - -Is equivalent to: - -``` ->=1.2.3, <2.0.0 -``` - -And: - -```javascript -{ - "major": "0", - "minor": "2", - "patch": "3" -} -``` - -Is equivalent to: - -``` ->=0.2.3, <0.3.0 -``` - -###### Caret Mode (`^`) - -The `^` mode SHALL behave exactly as the default mode above. - -###### Exact Mode (`=`) - -In `=` mode, a parent version SHALL be compatible if and only if the parent's version number exactly matches the specified version. - -##### Specifying Changes (`changes`) - -The `changes` field SHALL be a JavaScript Object Notation (JSON) Patch document as specified in RFC 6902. - -JSON pointers within the `changes` field MUST be resolved relative to the `providers` field of the parent list. For example, see the following lists for a correctly formatted extension. - -###### Root List - -```json -TODO -``` - -###### Extension List - -```json -TODO -``` - -##### Applying Extension Lists - -List consumers MUST follow this algorithm to apply extension lists: - - 1. Is the current list an extension list? - * Yes: - 1. Ensure that this `from` has not been seen before. - 1. Retrieve the parent list. - 1. Verify that the parent list is valid according to the JSON schema. - 1. Ensure that the parent list is version compatible. - 1. Set the current list to the parent list and go to step 1. - * No: - 1. Go to step 2. - 1. Copy the current list into a variable `$output`. - 1. Does the current list have a child: - * Yes: - 1. Apply the child's `changes` to `providers` in `$output`. - 1. Verify that `$output` is valid according to the JSON schema. - 1. Set the current list to the child. - 1. Go to step 3. - * No: - 1. Replace the current list's `providers` with `providers` from `$output`. - 1. The current list is now the resolved list; return it. - - -List consumers SHOULD limit the number of extension lists to a reasonable number. - -## Rationale - -This specification has two layers (provider, then chain id) instead of a flatter structure so that wallets can choose to query multiple independent providers for the same query and compare the results. - -Each provider may specify multiple endpoints to implement load balancing or redundancy. - -List version identifiers conform to SemVer to roughly communicate the kinds of changes that each new version brings. If a new version adds functionality (eg. a new chain id), then users can expect the minor version to be incremented. Similarly, if the major version is not incremented, list subscribers can assume dapps that work in the current version will continue to work in the next one. - -## Security Considerations - -Ultimately it is up to the end user to decide on what list to subscribe to. Most users will not change from the default list maintained by their wallet. Since wallets already have access to private keys, giving them additional control over RPC providers seems like a small increase in risk. - -While list maintainers may be incentivized (possibly financially) to include or exclude particular providers, actually doing so may jeopardize the legitimacy of their lists. This standard facilitates swapping lists, so if such manipulation is revealed, users are free to swap to a new list with little effort. - -If the list chosen by the user is published using EIP-1577, the list consumer has to have access to ENS in some way. This creates a paradox: how do you query Ethereum without an RPC provider? This paradox creates an attack vector: whatever method the list consumer uses to fetch the list can track the user, and even more seriously, **can lie about the contents of the list**. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5139.md diff --git a/EIPS/eip-5143.md b/EIPS/eip-5143.md index 72afb4bc0d02d3..4801b06b35ff4c 100644 --- a/EIPS/eip-5143.md +++ b/EIPS/eip-5143.md @@ -1,224 +1,7 @@ --- eip: 5143 -title: Slippage Protection for Tokenized Vault -description: An extension of EIP-4626 supporting improved EOA interactions. -author: Hadrien Croubois (@amxx) -discussions-to: https://ethereum-magicians.org/t/eip-5143-slippage-protection-for-tokenized-vaults/9554 -status: Stagnant -type: Standards Track category: ERC -created: 2022-06-09 -requires: 20, 4626 +status: Moved --- -## Abstract - -The following standard extends the [EIP-4626](./eip-4626.md) Tokenized Vault standard with functions dedicated to the safe interaction between EOAs and the vault when price is subject to slippage. - -## Motivation - -[EIP-4626](./eip-4626.md) security considerations section states that: -> "If implementors intend to support EOA account access directly, they should consider adding an additional function call for deposit/mint/withdraw/redeem with the means to accommodate slippage loss or unexpected deposit/withdrawal limits, since they have no other means to revert the transaction if the exact output amount is not achieved." - -Yet, EIP-4626 does not standardize the corresponding function signatures and behaviors. For improved interroperability, and better support by wallets, it is essential that this optional functions are also standardized. - -## Specification - -This ERC is an extension of EIP-4626. Any contract implementing it MUST also implement EIP-4626. - -### Methods - -#### deposit - -Overloaded version of ERC-4626's `deposit`. - -Mints `shares` Vault shares to `receiver` by depositing exactly `assets` of underlying tokens. - -MUST emit the `Deposit` event. - -MUST support [EIP-20](./eip-20.md) `approve` / `transferFrom` on `asset` as a deposit flow. -MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the `deposit` execution, and are accounted for during `deposit`. - -MUST revert if all of `assets` cannot be deposited (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc). -MUST revert if depositing `assets` underlying asset mints less then `minShares` shares. - -Note that most implementations will require pre-approval of the Vault with the Vault's underlying `asset` token. - -```yaml -- name: deposit - type: function - stateMutability: nonpayable - - inputs: - - name: assets - type: uint256 - - name: receiver - type: address - - name: minShares - type: uint256 - - outputs: - - name: shares - type: uint256 -``` - -#### mint - -Overloaded version of ERC-4626's `mint`. - -Mints exactly `shares` Vault shares to `receiver` by depositing `assets` of underlying tokens. - -MUST emit the `Deposit` event. - -MUST support ERC-20 `approve` / `transferFrom` on `asset` as a mint flow. -MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the `mint` execution, and are accounted for during `mint`. - -MUST revert if all of `shares` cannot be minted (due to deposit limit being reached, slippage, the user not approving enough underlying tokens to the Vault contract, etc). -MUST revert if minting `shares` shares cost more then `maxAssets` underlying tokens. - -Note that most implementations will require pre-approval of the Vault with the Vault's underlying `asset` token. - -```yaml -- name: mint - type: function - stateMutability: nonpayable - - inputs: - - name: shares - type: uint256 - - name: receiver - type: address - - name: maxAssets - type: uint256 - - outputs: - - name: assets - type: uint256 -``` - -#### withdraw - -Overloaded version of ERC-4626's `withdraw`. - -Burns `shares` from `owner` and sends exactly `assets` of underlying tokens to `receiver`. - -MUST emit the `Withdraw` event. - -MUST support a withdraw flow where the shares are burned from `owner` directly where `owner` is `msg.sender` or `msg.sender` has ERC-20 approval over the shares of `owner`. -MAY support an additional flow in which the shares are transferred to the Vault contract before the `withdraw` execution, and are accounted for during `withdraw`. - -MUST revert if all of `assets` cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc). -MUST revert if withdrawing `assets` underlying tokens requires burning more then `maxShares` shares. - -Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: withdraw - type: function - stateMutability: nonpayable - - inputs: - - name: assets - type: uint256 - - name: receiver - type: address - - name: owner - type: address - - name: maxShares - type: uint256 - - outputs: - - name: shares - type: uint256 -``` - -#### redeem - -Overloaded version of ERC-4626's `redeem`. - -Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `receiver`. - -MUST emit the `Withdraw` event. - -MUST support a redeem flow where the shares are burned from `owner` directly where `owner` is `msg.sender` or `msg.sender` has ERC-20 approval over the shares of `owner`. -MAY support an additional flow in which the shares are transferred to the Vault contract before the `redeem` execution, and are accounted for during `redeem`. - -MUST revert if all of `shares` cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc). -MUST revert if redeeming `shares` shares sends less than `minAssets` underlying tokens to `receiver`. - -Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. - -```yaml -- name: redeem - type: function - stateMutability: nonpayable - - inputs: - - name: shares - type: uint256 - - name: receiver - type: address - - name: owner - type: address - - name: minAssets - type: uint256 - - outputs: - - name: assets - type: uint256 -``` - -## Rationale - -This ERC's functions do not replace ERC-4626 equivalent mechanisms. They are additional (overloaded) methods designed to protect EOAs interacting with the vault. - -When smart contracts interact with an ERC-4626 vault, they can preview any operation using the dedicated functions before executing the operation. This can be done -atomically, with no risk of price change. This is not true of EOA, which will preview their operations on a UI, sign a transaction, and have it mined later. -Between the preview and the transaction being executed, the blockchain state might change, resulting in unexpected outcomes. In particular, frontrunning -make EOA's interractons with an ERC-4626 vault possibly risky. - -Other projects in the DeFi spaces, such as decentralized exchanges, already include similar mechanisms so a user can request its transaction reverts if the -resulting exchange rate is not considered good enough. - -Implementing This ERC on top of an ERC-4626 contract can be done very easily. It just requires calling the corresponding ERC-4626 function and adding a revert -check on the returned value. - -### Alternative approaches - -This ERC aims at solving the security concerns (describes in the motivation section) at the vault level. For completeness, we have to mention that these issues can also be addressed using a generic ERC-4626 router, similar to how Uniswap V2 & V3 use a router to provide good user workflows on top of the Uniswap pairs. The router approach is possibly more versatile and leaves more room for evolutions (the router can be replaced at any point) but it also leads to more expensive operations because the router needs to take temporary custody of the tokens going into the vault. - -## Reference Implementation - -Given an existing ERC-4626 implementation - -``` solidity -contract ERC5143 is ERC4626 { - function deposit(uint256 assets, address receiver, uint256 minShares) public virtual returns (uint256) { - uint256 shares = deposit(assets, receiver); - require(shares >= minShares, "ERC5143: deposit slippage protection"); - return shares; - } - function mint(uint256 shares, address receiver, uint256 maxAssets) public virtual returns (uint256) { - uint256 assets = mint(shares, receiver); - require(assets <= maxAssets, "ERC5143: mint slippage protection"); - return assets; - } - function withdraw(uint256 assets, address receiver, address owner, uint256 maxShares) public virtual returns (uint256) { - uint256 shares = withdraw(assets, receiver, owner); - require(shares <= maxShares, "ERC5143: withdraw slippage protection"); - return shares; - } - function redeem(uint256 shares, address receiver, address owner, uint256 minAssets) public virtual returns (uint256) { - uint256 assets = redeem(shares, receiver, owner); - require(assets >= minAssets, "ERC5143: redeem slippage protection"); - return assets; - } -} -``` -## Security Considerations - -This ERC addresses one of the security consideration raised by ERC-4626. Other considerations still apply. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5143.md diff --git a/EIPS/eip-5164.md b/EIPS/eip-5164.md index 5337a6daa9f26d..90463ae650de76 100644 --- a/EIPS/eip-5164.md +++ b/EIPS/eip-5164.md @@ -1,329 +1,7 @@ --- eip: 5164 -title: Cross-Chain Execution -description: Defines an interface that supports execution across EVM networks. -author: Brendan Asselstine (@asselstine), Pierrick Turelier (@PierrickGT), Chris Whinfrey (@cwhinfrey) -discussions-to: https://ethereum-magicians.org/t/eip-5164-cross-chain-execution/9658 -status: Review -type: Standards Track category: ERC -created: 2022-06-14 +status: Moved --- -## Abstract - -This specification defines a cross-chain execution interface for EVM-based blockchains. Implementations of this specification will allow contracts on one chain to call contracts on another by sending a cross-chain message. - -The specification defines two components: the "Message Dispatcher" and the "Message Executor". The Message Dispatcher lives on the calling side, and the executor lives on the receiving side. When a message is sent, a Message Dispatcher will move the message through a transport layer to a Message Executor, where they are executed. Implementations of this specification must implement both components. - -## Motivation - -Many Ethereum protocols need to coordinate state changes across multiple EVM-based blockchains. These chains often have native or third-party bridges that allow Ethereum contracts to execute code. However, bridges have different APIs so bridge integrations are custom. Each one affords different properties; with varying degrees of security, speed, and control. Defining a simple, common specification will increase code re-use and allow us to use common bridge implementations. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -This specification allows contracts on one chain to send messages to contracts on another chain. There are two key interfaces that needs to be implemented: - -- `MessageDispatcher` -- `MessageExecutor` - -The `MessageDispatcher` lives on the origin chain and dispatches messages to the `MessageExecutor` for execution. The `MessageExecutor` lives on the destination chain and executes dispatched messages. - -There are also extensions of `MessageDispatcher`, each defining a method for initiating a message or message batch: - -- `SingleMessageDispatcher` -- `BatchMessageDispatcher` - -Alternatively, `MessageDispatcher`s may implement a custom interface for initiating messages. - -### MessageDispatcher - -The `MessageDispatcher` lives on the chain from which messages are sent. The Dispatcher's job is to broadcast messages through a transport layer to one or more `MessageExecutor` contracts. - -A unique `messageId` MUST be generated for each message or message batch. - -To ensure uniqueness, it is RECOMMENDED that a monotonically increasing nonce is used in the calculation of the `messageId`. - -#### MessageDispatcher Events - -**MessageDispatched** - -The `MessageDispatched` event MUST be emitted by the `MessageDispatcher` when an individual message is dispatched. - -```solidity -interface MessageDispatcher { - event MessageDispatched( - bytes32 indexed messageId, - address indexed from, - uint256 indexed toChainId, - address to, - bytes data, - ); -} -``` - -```yaml -- name: MessageDispatched - type: event - inputs: - - name: messageId - indexed: true - type: bytes32 - - name: from - indexed: true - type: address - - name: toChainId - indexed: true - type: uint256 - - name: to - type: address - - name: data - type: bytes -``` - -**MessageBatchDispatched** - -The `MessageBatchDispatched` event MUST be emitted by the `MessageDispatcher` when a batch of messages is dispatched. - -```solidity -struct Message { - address to; - bytes data; -} - -interface MessageDispatcher { - event MessageBatchDispatched( - bytes32 indexed messageId, - address indexed from, - uint256 indexed toChainId, - Message[] messages - ); -} -``` - -```yaml -- name: MessageBatchDispatched - type: event - inputs: - - name: messageId - indexed: true - type: bytes32 - - name: from - indexed: true - type: address - - name: toChainId - indexed: true - type: uint256 - - name: messages - type: Message[] -``` - -### SingleMessageDispatcher - -The `SingleMessageDispatcher` is an extension of `MessageDispatcher` that defines a method, `dispatchMessage`, for dispatching an individual message to be executed on the `toChainId`. - -#### SingleMessageDispatcher Methods - -**dispatchMessage** - -Will dispatch a message to be executed by the `MessageExecutor` on the destination chain specified by `toChainId`. - -`SingleMessageDispatcher`s MUST emit the `MessageDispatched` event when a message is dispatched. - -`SingleMessageDispatcher`s MUST revert if `toChainId` is not supported. - -`SingleMessageDispatcher`s MUST forward the message to a `MessageExecutor` on the `toChainId`. - -`SingleMessageDispatcher`s MUST use a unique `messageId` for each message. - -`SingleMessageDispatcher`s MUST return the `messageId` to allow the message sender to track the message. - -`SingleMessageDispatcher`s MAY require payment. - -```solidity -interface SingleMessageDispatcher is MessageDispatcher { - function dispatchMessage(uint256 toChainId, address to, bytes calldata data) external payable returns (bytes32 messageId); -} -``` - -```yaml -- name: dispatchMessage - type: function - stateMutability: payable - inputs: - - name: toChainId - type: uint256 - - name: to - type: address - - name: data - type: bytes - outputs: - - name: messageId - type: bytes32 -``` - -### BatchedMessageDispatcher - -The `BatchedMessageDispatcher` is an extension of `MessageDispatcher` that defines a method, `dispatchMessageBatch`, for dispatching a batch of messages to be executed on the `toChainId`. - -#### BatchedMessageDispatcher Methods - -**dispatchMessageBatch** - -Will dispatch a batch of messages to be executed by the `MessageExecutor` on the destination chain specified by `toChainId`. - -`BatchedMessageDispatcher`s MUST emit the `MessageBatchDispatched` event when a message batch is dispatched. - -`BatchedMessageDispatcher`s MUST revert if `toChainId` is not supported. - -`BatchedMessageDispatcher`s MUST forward the message batch to the `MessageExecutor` on the `toChainId`. - -`BatchedMessageDispatcher`s MUST use a unique `messageId` for each batch of messages. - -`BatchedMessageDispatcher`s MUST return the `messageId` to allow the message sender to track the batch of messages. - -`BatchedMessageDispatcher`s MAY require payment. - -```solidity -interface BatchedMessageDispatcher is MessageDispatcher { - function dispatchMessageBatch(uint256 toChainId, Message[] calldata messages) external payable returns (bytes32 messageId); -} -``` - -```yaml -- name: dispatchMessageBatch - type: function - stateMutability: payable - inputs: - - name: toChainId - type: uint256 - - name: messages - type: Message[] - outputs: - - name: messageId - type: bytes32 -``` - -### MessageExecutor - -The `MessageExecutor` executes dispatched messages and message batches. Developers must implement a `MessageExecutor` in order to execute messages on the receiving chain. - -The `MessageExecutor` will execute a messageId only once, but may execute messageIds in any order. This specification makes no ordering guarantees, because messages and message batches may travel non-sequentially through the transport layer. - -#### Execution - -`MessageExecutor`s SHOULD verify all message data with the bridge transport layer. - -`MessageExecutor`s MUST NOT successfully execute a message more than once. - -`MessageExecutor`s MUST revert the transaction when a message fails to be executed allowing the message to be retried at a later time. - -**Calldata** - -`MessageExecutor`s MUST append the ABI-packed (`messageId`, `fromChainId`, `from`) to the calldata for each message being executed. This allows the receiver of the message to verify the cross-chain sender and the chain that the message is coming from. - -```solidity -to.call(abi.encodePacked(data, messageId, fromChainId, from)); -``` - -```yaml -- name: calldata - type: bytes - inputs: - - name: data - type: bytes - - name: messageId - type: bytes32 - - name: fromChainId - type: uint256 - - name: from - type: address -``` - -#### Error handling - -**MessageAlreadyExecuted** - -`MessageExecutor`s MUST revert if a messageId has already been executed and SHOULD emit a `MessageIdAlreadyExecuted` custom error. - -```solidity -interface MessageExecutor { - error MessageIdAlreadyExecuted( - bytes32 messageId - ); -} -``` - -**MessageFailure** - -`MessageExecutor`s MUST revert if an individual message fails and SHOULD emit a `MessageFailure` custom error. - -```solidity -interface MessageExecutor { - error MessageFailure( - bytes32 messageId, - bytes errorData - ); -} -``` - -**MessageBatchFailure** - -`MessageExecutor`s MUST revert the entire batch if any message in a batch fails and SHOULD emit a `MessageBatchFailure` custom error. - -```solidity -interface MessageExecutor { - error MessageBatchFailure( - bytes32 messageId, - uint256 messageIndex, - bytes errorData - ); -} -``` - -#### MessageExecutor Events - -**MessageIdExecuted** - -`MessageIdExecuted` MUST be emitted once a message or message batch has been executed. - -```solidity -interface MessageExecutor { - event MessageIdExecuted( - uint256 indexed fromChainId, - bytes32 indexed messageId - ); -} -``` - -```yaml -- name: MessageIdExecuted - type: event - inputs: - - name: fromChainId - indexed: true - type: uint256 - - name: messageId - indexed: true - type: bytes32 -``` - -## Rationale - -The `MessageDispatcher` can be coupled to one or more `MessageExecutor`. It is up to bridges to decide how to couple the two. Users can easily bridge a message by calling `dispatchMessage` without being aware of the `MessageExecutor` address. Messages can also be traced by a client using the data logged by the `MessageIdExecuted` event. - -Some bridges may require payment in the native currency, so the `dispatchMessage` function is payable. - -## Backwards Compatibility - -This specification is compatible with existing governance systems as it offers simple cross-chain execution. - -## Security Considerations - -Bridge trust profiles are variable, so users must understand that bridge security depends on the implementation. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5164.md diff --git a/EIPS/eip-5169.md b/EIPS/eip-5169.md index aa041b853347e6..a2b2997a9ed3b6 100644 --- a/EIPS/eip-5169.md +++ b/EIPS/eip-5169.md @@ -1,179 +1,7 @@ --- eip: 5169 -title: Client Script URI for Token Contracts -description: Add a scriptURI to point to an executable script associated with the functionality of the token. -author: James (@JamesSmartCell), Weiwu (@weiwu-zhang) -discussions-to: https://ethereum-magicians.org/t/eip-5169-client-script-uri-for-token-contracts/9674 -status: Draft -type: Standards Track category: ERC -created: 2022-05-03 -requires: 20, 165, 721, 777, 1155 +status: Moved --- -## Abstract -This EIP provides a contract interface adding a `scriptURI()` function for locating executable scripts associated with the token. - -## Motivation -Often, smart contract authors want to provide some user functionality to their tokens through client scripts. The idea is made popular with function-rich NFTs. It's important that a token's contract is linked to its client script, since the client script may carry out trusted tasks such as creating transactions for the user. - -This EIP allows users to be sure they are using the correct script through the contract by providing a URI to an official script, made available with a call to the token contract itself (`scriptURI`). This URI can be any RFC 3986-compliant URI, such as a link to an IPFS multihash, GitHub gist, or a cloud storage provider. Each contract implementing this EIP implements a `scriptURI` function which returns the download URI to a client script. The script provides a client-side executable to the hosting token. Examples of such a script could be: -- A 'miniDapp', which is a cut-down DApp tailored for a single token. -- A 'TokenScript' which provides TIPS from a browser wallet. -- A 'TokenScript' that allows users to interact with contract functions not normally provided by a wallet, eg 'mint' function. -- An extension that is downloadable to the hardware wallet with an extension framework, such as Ledger. -- JavaScript instructions to operate a smartlock, after owner receives authorization token in their wallet. - -#### Overview - -With the discussion above in mind, we outline the solution proposed by this EIP. For this purpose, we consider the following variables: - -- `SCPrivKey`: The private signing key to administrate a smart contract implementing this EIP. Note that this doesn't have to be a new key especially added for this EIP. Most smart contracts made today already have an administration key to manage the tokens issued. It can be used to update the `scriptURI`. - -- `newScriptURI`: an array of URIs for different ways to find the client script. - -We can describe the life cycle of the `scriptURI` functionality: - -- Issuance - -1. The token issuer issues the tokens and a smart contract implementing this EIP, with the admin key for the smart contract being `SCPrivKey`. -2. The token issuer calls `setScriptURI` with the `scriptURI`. - -- Update `scriptURI` - -1. The token issuer stores the desired `script` at all the new URI locations and constructs a new `scriptURI` structure based on this. -2. The token issuer calls `setScriptURI` with the new `scriptURI` structure. - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY” and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -We define a scriptURI element using the `string[]`. -Based on this, we define the smart contract interface below: - -```solidity -interface IERC5169 { - /// @dev This event emits when the scriptURI is updated, - /// so wallets implementing this interface can update a cached script - event ScriptUpdate(string[] memory newScriptURI); - - /// @notice Get the scriptURI for the contract - /// @return The scriptURI - function scriptURI() external view returns(string[] memory); - - /// @notice Update the scriptURI - /// emits event ScriptUpdate(scriptURI memory newScriptURI); - function setScriptURI(string[] memory newScriptURI) external; -} -``` - -The interface MUST be implemented under the following constraints: - -- The smart contract implementing `IERC5169` MUST store variables `address owner` in its state. - -- The smart contract implementing `IERC5169` MUST set `owner=msg.sender` in its constructor. - -- The `ScriptUpdate(...)` event MUST be emitted when the ```setScriptURI``` function updates the `scriptURI`. - -- The `setScriptURI(...)` function MUST validate that `owner == msg.sender` *before* executing its logic and updating any state. - -- The `setScriptURI(...)` function MUST update its internal state such that `currentScriptURI = newScriptURI`. - -- The `scriptURI()` function MUST return the `currentScriptURI` state. - -- The `scriptURI()` function MAY be implemented as pure or view. - -- Any user of the script learned from `scriptURI` MUST validate the script is either at an immutable location, its URI contains its hash digest, or it implements the separate `Authenticity for Client Script` EIP, which asserts authenticity using signatures instead of a digest. - -## Rationale - -This method avoids the need for building secure and certified centralized hosting and allows scripts to be hosted anywhere: IPFS, GitHub or cloud storage. - -## Backwards Compatibility - -This standard is backwards-compatible with most existing token standards, including the following commonly-used ones: -- [EIP-20](./eip-20.md) -- [EIP-721](./eip-721.md) -- [EIP-777](./eip-777.md) -- [EIP-1155](./eip-1155.md) - -## Test Cases -### Test Contract -```solidity -import "@openzeppelin/contracts/access/Ownable.sol"; -import "./IERC5169.sol"; -contract ERC5169 is IERC5169, Ownable { - string[] private _scriptURI; - function scriptURI() external view override returns(string[] memory) { - return _scriptURI; - } - - function setScriptURI(string[] memory newScriptURI) external onlyOwner override { - _scriptURI = newScriptURI; - - emit ScriptUpdate(newScriptURI); - } -} -``` - -### Test Cases -```ts -const { expect } = require('chai'); -const { BigNumber, Wallet } = require('ethers'); -const { ethers, network, getChainId } = require('hardhat'); - -describe('ERC5169', function () { - before(async function () { - this.ERC5169 = await ethers.getContractFactory('ERC5169'); - }); - - beforeEach(async function () { - // targetNFT - this.erc5169 = await this.ERC5169.deploy(); - }); - - it('Should set script URI', async function () { - const scriptURI = [ - 'uri1', 'uri2', 'uri3' - ]; - - await expect(this.erc5169.setScriptURI(scriptURI)) - .emit(this.erc5169, 'ScriptUpdate') - .withArgs(scriptURI); - - const currentScriptURI = await this.erc5169.scriptURI(); - - expect(currentScriptURI.toString()).to.be.equal(scriptURI.toString()); - }); -``` - -#### Script location - -While the most straightforward solution to facilitate specific script usage associated with NFTs, is clearly to store such a script on the smart contract. However, this has several disadvantages: - -1. The smart contract signing key is needed to make updates, causing the key to become more exposed, as it is used more often. - -2. Updates require smart contract interaction. If frequent updates are needed, smart contract calls can become an expensive hurdle. - -3. Storage fee. If the script is large, updates to the script will be costly. A client script is typically much larger than a smart contract. - -For these reasons, storing volatile data, such as token enhancing functionality, on an external resource makes sense. Such an external resource can be either be hosted centrally, such as through a cloud provider, or privately hosted through a private server, or decentralized hosted, such as the interplanetary filesystem. - -While centralized storage for a decentralized functionality goes against the ethos of web3, fully decentralized solutions may come with speed, price or space penalties. This EIP handles this by allowing the function `ScriptURI` to return multiple URIs, which could be a mix of centralized, individually hosted and decentralized locations. - -While this EIP does not dictate the format of the stored script, the script itself could contain pointers to multiple other scripts and data sources, allowing for advanced ways to expand token scripts, such as lazy loading. -The handling of integrity of such secondary data sources is left dependent on the format of the script. - -## Security Considerations - -**When a server is involved** - -When the client script does not purely rely on connection to a blockchain node, but also calls server APIs, the trustworthiness of the server API is called into question. This EIP does not provide any mechanism to assert the authenticity of the API access point. Instead, as long as the client script is trusted, it's assumed that it can call any server API in order to carry out token functions. This means the client script can mistrust a server API access point. - -**When the scriptURI doesn't contain integrity (hash) information** - -We separately authored `Authenticity for Client Script` EIP to guide on how to use digital signatures efficiently and concisely to ensure authenticity and integrity of scripts not stored at a URI which is a digest of the script itself. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5169.md diff --git a/EIPS/eip-5173.md b/EIPS/eip-5173.md index 7a1336b9add7f3..0320897356e19a 100644 --- a/EIPS/eip-5173.md +++ b/EIPS/eip-5173.md @@ -1,419 +1,7 @@ --- eip: 5173 -title: NFT Future Rewards (nFR) -description: A multigenerational reward mechanism that rewards‌ all ‌owners of non-fungible tokens (NFT). -author: Yale ReiSoleil (@longnshort), dRadiant (@dRadiant), D Wang, PhD -discussions-to: https://ethereum-magicians.org/t/non-fungible-future-rewards-token-standard/9203 -status: Draft -type: Standards Track category: ERC -created: 2022-05-08 -requires: 165, 721 +status: Moved --- -## Abstract - -In this EIP, we propose the implementation of a Future Rewards (FR) extension which will enable owners of [EIP-721](./eip-721.md) tokens (NFTs) to participate in future price increases after they sell their tokens. - -Through the implementation of this nFR proposal, the creators, buyers and sellers create a giving circle in trading practice. A giving circle is formed when all participants work in a framework to build greater wealth through each other's success. One does not expect the same amount of return from the same person when they give someone a portion of their profits. There is no quid pro quo. Rather, they are confident that someone else in the same circle will give them the same benefits, with a smaller or greater monetary value, from other participants in the same circle later on. - -Owners of nFR compliant tokens can benefit in two ways from such a gift economic framework: - -1. An increase in price during their holding period; -2. They continue to receive Future Rewards (FRs) after the token is sold. - -The realized profits from the sale of nFR compliant tokens will be shared across the chain of historical ownership if the seller is not the original Minter and therefore not the very first seller. Through the NFT Future Rewards (nFR) framework, the same seller, as well as every other seller, will receive the same FR distributions. Everybody pays it forward, forming a giving circle. - -Giving circles are groups of people who work together to improve a situation that is typically much larger than it is at the moment. Some of the characteristics of a giving circle are community interdependence and delayed reciprocity. - -In a well-designed circle of giving, givers may be able to receive more than they give over time, so giving is not the only thing involved. As a result, the traditional model of platform versus user and user vs. user relationships has been fundamentally altered into one, shared objective: if others succeed, I succeed more. - - -## Motivation - -Not limited to NFT trading, it is common for an average trader to fall victim to spoofing, insider trading, front running, wash trading, and pump and dump, among a number of other techniques used by various actors. The current system guarantees that most traders will lose money because of their emotions, the constant oscillation between greed and fear. Under the current system, a trader has no advantage over many of the more sophisticated techniques used by various actors. - -Although this historical precedent has been followed in today's markets, just as crypto has revolutionized traditional trading, we now have the opportunity to transform this historic trail of unequal value distribution by tracking every transaction of every distinguishable token through the emergence of the non-fungible token standard. - -There needs to be a change in historical unfair trading practices so that: - -* With a success-based model, everyone is on the same page; -* A mutually beneficial economic rule benefits both buyers and sellers. - - -NFTs, in contrast to physical art and collectibles in the physical world, are not currently reflecting the contributions of their owners to their value. Since each [EIP-721](./eip-721.md) token can be tracked individually, and may be modified to record every change in the price of any specific NFT token, there is no reason that a Future Rewards program of this type should not be established. - -This nFR proposal establishes a standard interface for a profit sharing framework in all stages of the token's ownership history desired by all market participants. In a giving circle, art buyers/owners are compensated for their participation in the instrument’s trading price discovery process. - -We embrace and promote a new gift economic model, which is similar to the Copyleft and open-source spirit as opposed to traditional copyrights. The advancement of technology has enabled such implementation in trading for the first time. In the same way that open-source software has changed the software industry and society, we can also change the financial industry. - -As in trading, most traders lose money, but the proposed Future Rewards framework is designed to help average traders do better. - -Additionally, as we will explain later, it discourages any "under-the-table" deals that may circumvent the rules set forth by artists and marketplaces. - -### Is This Just a Ponzi Scheme? - -No, it is not. Ponzi schemes promise profits that are impossible to keep. - -As opposed to fixed-yield schemes, our proposal only distributes future profits when those profits are achieved rather than guaranteeing them. Should later holders fail to make a profit, future return shares will not be distributed. - -The early participants in price discovery will receive a share of profits as part of the FR implementation only and if a later owner has accumulated profits during their holdings of the token. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -The following is an extension of the [EIP-721](./eip-721.md) standard. - -[EIP-721](./eip-721.md)-compliant contracts MAY implement this EIP for rewards to provide a standard method of rewarding future buyers and previous owners with realized profits in the future. - -Implementers of this standard MUST have all of the following functions: - -```solidity - -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; - -/* - * - * @dev Interface for the Future Rewards Token Standard. - * - * A standardized way to receive future rewards for non-fungible tokens (NFTs.) - * - */ -interface IERC5173 is IERC165 { - - event FRClaimed(address indexed account, uint256 indexed amount); - - event FRDistributed(uint256 indexed tokenId, uint256 indexed soldPrice, uint256 indexed allocatedFR); - - function list(uint256 tokenId, uint256 salePrice) external; - - function unlist(uint256 tokenId) external; - - function buy(uint256 tokenId) payable external; - - function releaseFR(address payable account) external; - - function retrieveFRInfo(uint256 tokenId) external returns(uint8, uint256, uint256, uint256, uint256, address[] memory); - - function retrieveAllottedFR(address account) external returns(uint256); - - function retrieveListInfo(uint256 tokenId) external returns(uint256, address, bool); - -} - -``` - -An nFR contract MUST implement and update for each Token ID. The data in the `FRInfo` struct MAY either be stored wholly in a single mapping, or MAY be broken down into several mappings. The struct MUST either be exposed in a public mapping or mappings, or MUST have public functions that access the private data. This is for client-side data fetching and verification. - -```solidity - -struct FRInfo { - uint8 numGenerations; // Number of generations corresponding to that Token ID - uint256 percentOfProfit; // Percent of profit allocated for FR, scaled by 1e18 - uint256 successiveRatio; // The common ratio of successive in the geometric sequence, used for distribution calculation - uint256 lastSoldPrice; // Last sale price in ETH mantissa - uint256 ownerAmount; // Amount of owners the Token ID has seen - address[] addressesInFR; // The addresses currently in the FR cycle -} - -struct ListInfo { - uint256 salePrice; // ETH mantissa of the listed selling price - address lister; // Owner/Lister of the Token - bool isListed; // Boolean indicating whether the Token is listed or not -} - -``` - -Additionally, an nFR smart contract MUST store the corresponding `ListInfo` for each Token ID in a mapping. A method to retrieve a Token ID’s corresponding `ListInfo` MUST also be accessible publicly. - -An nFR smart contract MUST also store and update the amount of Ether allocated to a specific address using the `_allotedFR` mapping. The `_allottedFR` mapping MUST either be public or have a function to fetch the FR payment allotted to a specific address. - -### Percent Fixed Point - -The `allocatedFR` MUST be calculated using a percentage fixed point with a scaling factor of 1e18 (X/1e18) - such as "5e16" - for 5%. This is REQUIRED to maintain uniformity across the standard. The max and min values would be - 1e18 - 1. - -### Default FR Info - -A default `FRInfo` MUST be stored in order to be backward compatible with [EIP-721](./eip-721.md) mint functions. It MAY also have a function to update the `FRInfo`, assuming it has not been hard-coded. - -### EIP-721 Overrides - -An nFR-compliant smart contract MUST override the [EIP-721](./eip-721.md) `_mint`, `_transfer`, and `_burn` functions. When overriding the `_mint` function, a default FR model is REQUIRED to be established if the mint is to succeed when calling the [EIP-721](./eip-721.md) `_mint` function and not the nFR `_mint` function. It is also to update the owner amount and directly add the recipient address to the FR cycle. When overriding the `_transfer` function, the smart contract SHALL consider the NFT as sold for 0 ETH, and update the state accordingly after a successful transfer. This is to prevent FR circumvention. Additionally, the `_transfer` function SHALL prevent the caller from transferring the token to themselves, this can be done through a require statement that ensures the sender is not the recipient, otherwise, it’d be possible to fill up the FR sequence with one’s own address. Finally, when overriding the `_burn` function, the smart contract SHALL delete the `FRInfo` corresponding to that Token ID after a successful burn. - -Additionally, the [EIP-721](./eip-721.md) `_checkOnERC721Received` function MAY be explicitly called after mints and transfers if the smart contract aims to have safe transfers and mints. - -### Safe Transfers - -If the wallet/broker/auction application will accept safe transfers, then it MUST implement the [EIP-721](./eip-721.md) wallet interface. - -### Listing, Unlisting, and Buying - -The `list`, `unlist`, and `buy` functions MUST be implemented, as they provide the capability to sell a token. - -```solidity -function list(uint256 tokenId, uint256 salePrice) public virtual override { - //... -} - - -function unlist(uint256 tokenId) public virtual override { - //... -} - -function buy(uint256 tokenId) public virtual override payable { - //... -} - -``` - -The `list` function accepts a `tokenId` and a `salePrice` and updates the corresponding `ListInfo` for that given `tokenId` after ensuring that the `msg.sender` is either approved or the owner of the token. The function signifies that the token is listed and at what price it is listed for. - -The `unlist` function accepts a `tokenId` and it deletes the corresponding `ListInfo` after the owner verifications have been met. - -The `buy` function accepts a `tokenId` and MUST be payable. It MUST verify that the `msg.value` matches the token’s `salePrice` and that the token is listed, before proceeding and calling the FR `_transferFrom` function. This is to ensure the values are valid and will also allow for the necessary FR to be held in the contract. - - -### Future Rewards `_transferFrom` Function - -The FR `_transferFrom` function MUST be called by all nFR-supporting smart contracts, though the accommodations for non-nFR-supporting contracts MAY also be implemented to ensure backwards compatibility. - -```solidity - -function transferFrom(address from, address to, uint256 tokenId, uint256 soldPrice) public virtual override payable { - //... -} - -``` - -Based on the stored `lastSoldPrice`, the smart contract will determine whether the sale was profitable after calling the [EIP-721](./eip-721.md) transfer function and transferring the NFT. If it was not profitable, the smart contract SHALL update the last sold price for the corresponding Token ID, increment the owner amount, shift the generations, and transfer all of the `msg.value` to the `lister` depending on the implementation. Otherwise, if the transaction was profitable, the smart contract SHALL call the `_distributeFR` function, then update the `lastSoldPrice`, increment the owner amount, and finally shift generations. The `_distributeFR` function MUST return the difference between the allocated FR that is to be distributed amongst the `_addressesInFR` and the `msg.value` to the `lister`. Once the operations have completed, the function MUST clear the corresponding `ListInfo`. Similarly to the `_transfer` override, the FR `_transferFrom` SHALL ensure that the recipient is not the sender of the token. - -### Future Rewards Calculation - -Marketplaces that support this standard MAY implement various methods of calculating or transferring Future Rewards to the previous owners. - -```solidity - -function _calculateFR(uint256 totalProfit, uint256 buyerReward, uint256 successiveRatio, uint256 ownerAmount, uint256 windowSize) pure internal virtual returns(uint256[] memory) { - //... -} - -``` - -In this example (*Figure 1*), a seller is REQUIRED to share a portion of their net profit with 10 previous holders of the token. Future Rewards will also be paid to the same seller as the value of the token increases from up to 10 subsequent owners. - -When an owner loses money during their holding period, they MUST NOT be obligated to share Future Rewards distributions, since there is no profit to share. However, he SHALL still receive a share of Future Rewards distributions from future generations of owners, if they are profitable. - -![Figure 1: Geometric sequence distribution](../assets/eip-5173/Total_FR_Payout_Distribution-geo.png) - -*Figure 1: Geometric sequence distribution* - -The buyers/owners receive a portion ( r ) of the realized profit (P ) from an NFT transaction. The remaining proceeds go to the seller. - -As a result of defining a sliding window mechanism ( n ), we can determine which previous owners will receive distributions. The owners are arranged in a queue, starting with the earliest owner and ending with the owner immediately before the current owner (the Last Generation). The First Generation is the last of the next n generations. There is a fixed-size profit distribution window from the First Generation to the Last Generation. - -The profit distribution SHALL be only available to previous owners who fall within the window. - -In this example, there SHALL be a portion of the proceeds awarded to the Last Generation owner (the owner immediately prior to the current seller) based on the geometric sequence in which profits are distributed. The larger portion of the proceeds SHALL go to the Mid-Gen owners, the earlier the greater, until the last eligible owner is determined by the sliding window, the First Generation. Owners who purchase earlier SHALL receive a greater reward, with first-generation owners receiving the greatest reward. - -### Future Rewards Distribution - -![Figure 2: NFT Owners' Future Rewards (nFR)](../assets/eip-5173/nFR_Standard_Outline.jpeg) - -*Figure 2: NFT Owners' Future Rewards (nFR)* - -*Figure 2* illustrates an example of a five-generation Future Rewards Distribution program based on an owner's realized profit. - -```solidity - -function _distributeFR(uint256 tokenId, uint256 soldPrice) internal virtual { - //... - - emit FRDistributed(tokenId, soldPrice, allocatedFR); - } - -``` - -The `_distributeFR` function MUST be called in the FR `transferFrom` function if there is a profitable sale. The function SHALL calculate the difference between the current sale price and the `lastSoldPrice`, then it SHALL call the `_calculateFR` function to receive the proper distribution of FR. Then it SHALL distribute the FR accordingly, making order adjustments as necessary. Then, the contract SHALL calculate the total amount of FR that was distributed (`allocatedFR`), in order to return the difference of the `soldPrice` and `allocatedFR` to the `lister`. Finally, it SHALL emit the `FRDistributed` event. - -### Future Rewards Claiming - -The future Rewards payments SHOULD utilize a pull-payment model, similar to that demonstrated by OpenZeppelin with their PaymentSplitter contract. The event FRClaimed would be triggered after a successful claim has been made. - -```solidity - -function releaseFR(address payable account) public virtual override { - //... -} - -``` - -### Owner Generation Shifting - -The `_shiftGenerations` function MUST be called regardless of whether the sale was profitable or not. As a result, it will be called in the `_transfer` [EIP-721](./eip-721.md) override function and the FR `transferFrom` function. The function SHALL remove the oldest account from the corresponding `_addressesInFR` array. This calculation will take into account the current length of the array versus the total number of generations for a given token ID. - -## Rationale - -### Fixed Percentage to 10^18 - -Considering Fixed-Point Arithmetic is to be enforced, it is logical to have 1e18 represent 100% and 1e16 represent 1% for Fixed-Point operations. This method of handling percents is also commonly seen in many Solidity libraries for Fixed-Point operations. - -### Emitting Event for Payment - -Since each NFT contract is independent, and while a marketplace contract can emit events when an item is sold, choosing to emit an event for payment is important. As the royalty and FR recipient may not be aware of/watching for a secondary sale of their NFT, they would never know that they received a payment except that their ETH wallet has been increased randomly. - -The recipient of the secondary sale will therefore be able to verify that the payment has been received by calling the parent contract of the NFT being sold, as implemented in [EIP-2981](./eip-2981.md). - -### Number of Generations of All Owners ( n ) vs Number of Generations of Only Profitable Owners - -It is the number of generations of all owners, not just those who are profitable, that determines the number of owners from which the subsequent owners' profits will be shared, see *Figure 3*. As part of the effort to discourage "ownership hoarding," Future Rewards distributions will not be made to the current owner/purchaser if all the owners lose money holding the NFT. Further information can be found under Security Considerations. - -![Figure 3: Losing owners](../assets/eip-5173/Losing_owners.jpeg) - -*Figure 3: Losing owners* - -### Single vs Multigenerations - -In a single generation reward, the new buyer/owner receives a share of the next single generation's realized profit only. In a multigenerational reward system, buyers will have future rewards years after their purchase. The NFT should have a long-term growth potential and a substantial dividend payout would be possible in this case. - -We propose that the marketplace operator can choose between a single generational distribution system and a multigenerational distribution system. - -### Direct FR Payout by the Seller vs Smart Contract-managed Payout - -FR payouts directly derived from the sale proceeds are immediate and final. As part of the fraud detection detailed later in the Security Considerations section, we selected a method in which the smart contract calculates all the FR amounts for each generation of previous owners, and handles payout according to other criteria set by the marketplace, such as reduced or delayed payments for wallet addresses with low scores, or a series of consecutive orders detected using a time-heuristic analysis. - -### Equal vs Linear Reward Distributions -#### Equal FR Payout - -![Figure 4: Equal, linear reward distribution](../assets/eip-5173/Total_FR_Payout_Distribution-flat.png?raw=true) - -*Figure 4: Equal, linear reward distribution* - -FR distributions from the realization of profits by later owners are distributed equally to all eligible owners (*Figure 4*). The exponential reward curve, however, may be more desirable, as it gives a slightly larger share to the newest buyer. Additionally, this distribution gives the earliest generations the largest portions as their FR distributions near the end, so they receive higher rewards for their early involvement, but the distribution is not nearly as extreme as one based on arithmetic sequences (*Figure 5*). - -This system does not discriminate against any buyer because each buyer will go through the same distribution curve. - -#### Straight line arithmetic sequence FR payout - -![Figure 5: Arithmetic sequence distribution](../assets/eip-5173/Arithmetic_Sequence_FR_Payout_Distribution.png?raw=true) - -*Figure 5: Arithmetic sequence distribution* - -The profit is distributed according to the arithmetic sequence, which is 1, 2, 3, ... and so on. The first owner will receive 1 portion, the second owner will receive 2 portions, the third owner will receive 3 portions, etc. - -## Backwards Compatibility - -This proposal is fully compatible with current [EIP-721](./eip-721.md) standards and [EIP-2981](./eip-2981.md). It can also be easily adapted to work with [EIP-1155](./eip-1155.md). - -## Test Cases - -[This contract](../assets/eip-5173/Implementation/nFRImplementation.sol) contains the reference implementation for this proposal. - -[Here is a visualization of the test case](../assets/eip-5173/animate-1920x1080-1750-frames.gif?raw=true). - -## Reference Implementation - -This implementation uses OpenZeppelin contracts and the PRB Math library created by Paul R Berg for fixed-point arithmetic. It demonstrates the interface for the nFR standard, an nFR standard-compliant extension, and an [EIP-721](./eip-721.md) implementation using the extension. - -The code for the reference implementation is [here](../assets/eip-5173/Implementation/nFRImplementation.sol). - -### Distribution of NFT Royalties to Artists and Creators - -We agree that artists’ royalties should be uniform and on-chain. We support [EIP-2981](./eip-2981.md) NFT royalty Standard proposal. - -All platforms can support royalty rewards for the same NFT based on on-chain parameters and functions: - -- No profit, no profit sharing, no cost; -- The question of "who owned it" is often crucial to the provenance and value of a collectible; -- The previous owner should be re-compensated for their ownership; -- And the buyer/owner incentive in FR eliminates any motive to circumvent the royalty payout schemes; - -### Distribution of NFT Owners’ Future Rewards (FRs) - -#### Future Rewards calculation - -Any realized profits (P) when an NFT is sold are distributed among the buyers/owners. The previous owners will take a fixed portion of the profix (P), and this portion is called Future Rewards (FRs). The seller takes the rest of the profits. - -We define a sliding window mechanism to decide which previous owners will be involved in the profit distribution. Let's imagine the owners as a queue starting from the first hand owner to the current owner. The profit distribution window starts from the previous owner immediately to the current owner and extends towards the first owner, and the size of the windows is fixed. Only previous owners located inside the window will join the profit distribution. - -![Future Rewards calculation formula](../assets/eip-5173/nFR_distribution_formula.png?raw=true) - -In this equation: - -- P is the total profit, the difference between the selling price minus the buying price; -- r is buyer reward ratio of the total P; -- g is the common ratio of successive in the geometric sequence; -- n is the actual number of owners eligible and participating in the future rewards sharing. To calculate n, we have n = min(m, w), where m is the current number of owners for a token, and w is the window size of the profit distribution sliding window algorithm - -#### Converting into Code - -```solidity - -pragma solidity ^0.8.0; -//... - -/* Assumes usage of a Fixed Point Arithmetic library (prb-math) for both int256 and uint256, and OpenZeppelin Math utils for Math.min. */ -function _calculateFR(uint256 P, uint256 r, uint256 g, uint256 m, uint256 w) pure internal virtual returns(uint256[] memory) { - uint256 n = Math.min(m, w); - uint256[] memory FR = new uint256[](n); - - for (uint256 i = 1; i < n + 1; i++) { - uint256 pi = 0; - - if (successiveRatio != 1e18) { - int256 v1 = 1e18 - int256(g).powu(n); - int256 v2 = int256(g).powu(i - 1); - int256 v3 = int256(P).mul(int256(r)); - int256 v4 = v3.mul(1e18 - int256(g)); - pi = uint256(v4 * v2 / v1); - } else { - pi = P.mul(r).div(n); - } - - FR[i - 1] = pi; - } - - return FR; -} - -``` -The complete implementation code can be found [here](../assets/eip-5173/Implementation/nFRImplementation.sol). - -## Security Considerations - -### Payment Attacks - -As this EIP introduces royalty and realized profit rewards collection, distribution, and payouts to the EIP-721 standard, the attack vectors increase. As discussed by Andreas Freund regarding mitigations to phishing attacks, we recommend reentrancy protection for all payment functions to reduce the most significant attack vectors for payments and payouts. - -### Royalty Circumventing - -Many methods are being used to avoid paying royalties to creators under the current [EIP-721](./eip-721.md) standard. Through an under-the-table transaction, the new buyer's cost basis will be reduced to zero, increasing their FR liability to the full selling price. Everyone, either the buyer or seller, would pay a portion of the previous owner's net realized profits ( P x r ). Acting in his or her own interests, the buyer rejects any loyalty circumventing proposal. - -### FR Hoarding through Wash Sales - -Quantexa blog and beincrypto articles have reported widespread wash trading on all unregulated cryptocurrency trading platforms and NFT marketplaces. The use of wash trading by dishonest actors can lead to an unfair advantage, as well as inflated prices and money laundering. When a single entity becomes multiple generations of owners to accumulate more rewards in the future, the validity of the system is undermined. - -#### Wash trading by users -Using a different wallet address, an attacker can "sell" the NFT to themselves at a loss. It is possible to repeat this process n times in order to maximize their share of the subsequent FR distributions (*Figure 6*). A wallet ranking score can partially alleviate this problem. It is evident that a brand new wallet is a red flag, and the marketplace may withhold FR distribution from it if it has a short transaction history (i.e. fewer than a certain number of transactions). - -We do not want a large portion of future rewards to go to a small number of wash traders. Making such practices less profitable is one way to discourage wash trading and award hoarding. It can be partially mitigated, for example, by implementing a wallet-score and holding period-based incentive system. The rewards for both parties are reduced if a new wallet is used or if a holding period is less than a certain period. - -![Figure 6: Same owner using different wallets](../assets/eip-5173/Same_owner_using_different_wallets.jpeg) - -*Figure 6: Same owner using different wallets* - -#### Wash trading by the marketplace operator - -However, the biggest offender appears to be the marketplace, which engages heavily in wash trading, or simply does not care about it, according to Decrypt. The authors have personally experienced this phenomenon. A senior executive of a top-5 cryptocurrency exchange boasted during a mid-night drinking session in 2018, that they had "brushed" (wash-traded) certain newly listed tokens, which they called "marketmaking." The exchange is still ranked among the top five crypto exchanges today. - -Many of these companies engage in wash trading on their own or collude with certain users, and royalties and FR payments are reimbursed under the table. It is crucial that all exchanges have robust features to prevent self-trading. Users should be able to observe watchers transparently. Marketplaces should provide their customers with free access to an on-chain transaction monitoring service like Chainalysis Reactor. - -### Long/Cyclical FR-Entitled Owner Generations - -In most cases, malicious actors will create excessively long or cyclical Future Rewards Owner Generations that will result in applications that attempt to distribute FR or shift generations running out of gas and not functioning. Therefore, clients are responsible for verifying that the contract with which they interact has an appropriate number of generations, so that looping over will not deplete the gas. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5173.md diff --git a/EIPS/eip-5185.md b/EIPS/eip-5185.md index 000784dbf2696a..525124d9400dcc 100644 --- a/EIPS/eip-5185.md +++ b/EIPS/eip-5185.md @@ -1,232 +1,7 @@ --- eip: 5185 -title: NFT Updatable Metadata Extension -description: An interface extension for ERC-721/ERC-1155 controlled metadata updates -author: Christophe Le Bars (@clbrge) -discussions-to: https://ethereum-magicians.org/t/erc-721-erc-1155-updatable-metadata-extension/9077 -status: Stagnant -type: Standards Track category: ERC -requires: 721, 1155 -created: 2022-06-27 +status: Moved --- -## Abstract - -This specification defines a standard way to allow controlled NFTs' metadata updates along predefined formulas. Updates of the original metadata are restricted and defined by a set of recipes and the sequence and results of these recipes are deterministic and fully verifiable with on-chain metadata updates event. The proposal depends on and extends the [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). - -## Motivation - -Storing voluminous NFT metadata on-chain is often neither practical nor cost-efficient. - -Storing NFT metadata off-chain on distributed file systems like IPFS can answer some needs of verifiable correlation and permanence between an NFT tokenId and its metadata but updates come at the cost of being all or nothing (aka changing the `tokenURI`). Bespoke solutions can be easily developed for a specific NFT smart contract but a common specification is necessary for NFT marketplaces and third parties tools to understand and verify these metadata updates. - -This ERC allows the original JSON metadata to be modified step by step along a set of predefined JSON transformation formulas. Depending on NFT use-cases, the transformation formulas can be more or less restrictive. - -As examples, an NFT representing a house could only allow append-only updates to the list of successive owners, and a game using NFT characters could let some attributes change from time to time (e.g. health, experience, level, etc) while some other would be guaranteed to never change (e.g. physicals traits etc). - -This standard extension is compatible with NFTs bridged between Ethereum and L2 networks and allows efficient caching solutions. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -The **metadata updates extension** is OPTIONAL for [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) contracts. - -```solidity -/// @title ERC-721/ERC-1155 Updatable Metadata Extension -interface IERC5185UpdatableMetadata { - /// @notice A distinct Uniform Resource Identifier (URI) for a set of updates - /// @dev This event emits an URI (defined in RFC 3986) of a set of metadata updates. - /// The URI should point to a JSON file that conforms to the "NFT Metadata Updates JSON Schema" - /// Third-party platforms such as NFT marketplace can deterministically calculate the latest - /// metadata for all tokens using these events by applying them in sequence for each token. - event MetadataUpdates(string URI); -} -``` - -The original metadata SHOULD conform to the "ERC-5185 Updatable Metadata JSON Schema" which is a compatible extension of the "ERC-721 Metadata JSON Schema" defined in ERC-721. - -"ERC-5185 Updatable Metadata JSON Schema" : - -```json -{ - "title": "Asset Updatable Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents" - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "updatable": { - "type": "object", - "required": ["engine", "recipes"], - "properties": { - "engine": { - "type": "string", - "description": "Non ambiguous transformation method/language (with version) to process updates along recipes defined below" - }, - "schema": { - "type": "object", - "description": "if present, a JSON Schema that all sequential post transformation updated metadata need to conform. If a transformed JSON does not conform, the update should be considered voided." - }, - "recipes": { - "type": "object", - "description": "A catalog of all possibles recipes identified by their keys", - "patternProperties": { - ".*": { - "type": "object", - "description": "The key of this object is used to select which recipe to apply for each update", - "required": ["eval"], - "properties": { - "eval": { - "type": "string", - "description": "The evaluation formula to transform the last JSON metadata using the engine above (can take arguments)" - } - } - } - } - } - } - } - } -} -``` - -"NFT Metadata Updates JSON Schema" : - -```json -{ - "title": "Metadata Updates JSON Schema", - "type": "object", - "properties": { - "updates": { - "type": "array", - "description": "A list of updates to apply sequentially to calculate updated metadata", - "items": { "$ref": "#/$defs/update" }, - "$defs": { - "update": { - "type": "object", - "required": ["tokenId", "recipeKey"], - "properties": { - "tokenId": { - "type": "string", - "description": "The tokenId for which the update recipe should apply" - }, - "recipeKey": { - "type": "string", - "description": "recipeKey to use to get the JSON transformation expression in current metadata" - }, - "args": { - "type": "string", - "description": "arguments to pass to the JSON transformation" - } - } - } - } - } - } -} -``` - -### Engines - -Only one engine is currently defined in this extension proposal. - -If the engine in the original metadata is "jsonata@1.8.*", updated metadata is calculated starting from original metadata and applying each update sequentially (all updates which are present in all the URIs emitted by the event `MetadataUpdates` for which tokenId matches). - -For each step, the next metadata is obtained by the javascript calculation (or compatible jsonata implementation in other language) : - -```js -const nextMetadata = jsonata(evalString).evaluate(previousMetadata, args) -``` - -With `evalString` is found with `recipeKey` in the original metadata recipes list. - -If the key is not present in the original metadata list, `previousMetadata` is kept as the valid updated metadata. - -If the evaluation throws any errors, `previousMetadata` is kept as the valid updated metadata. - -If a validation Schema JSON has been defined and the result JSON `nextMetadata` does not conform, that update is not valid and `previousMetadata` is kept as the valid updated metadata. - -## Rationale - -There have been numerous interesting uses of [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) smart contracts that associate for each token essential and significant metadata. While some projects (e.g. EtherOrcs) have experimented successfully to manage these metadata on-chain, that experimental solution will always be limited by the cost and speed of generating and storing JSON on-chain. Symmetrically, while storing the JSON metadata at URI endpoint controlled by traditional servers permit limitless updates the the metadata for each NFT, it is somehow defeating in many uses cases, the whole purpose of using a trustless blockchain to manage NFT: indeed users may want or demand more permanence and immutability from the metadata associated with their NFT. - -Most use cases have chosen intermediate solutions like IPFS or arweave to provide some permanence or partial/full immutability of metadata. This is a good solution when an NFT represents a static asset whose characteristics are by nature permanent and immutable (like in the art world) but less so with other use cases like gaming or NFT representing a deed or title. Distinguishable assets in a game often should be allowed to evolve and change over time in a controlled way and titles need to record real life changes. - -The advantages of this standard is precisely to allow these types of controlled transformations over time of each NFT metadata by applying sequential transformations starting with the original metadata and using formulas themselves defined in the original metadata. - -The original metadata for a given NFT is always defined as the JSON pointed by the result of `tokenURI` for [EIP-721](./eip-721.md) and function `uri` for [EIP-1155](./eip-1155.md). - -The on-chain log trace of updates guarantee that anyone can recalculate and verify independently the current updated metadata starting from the original metadata. The fact that the calculation is deterministic allows easy caching of intermediate transformations and the efficient processing of new updates using these caches. - -The number of updates defined by each event is to be determined by the smart contract logic and use case, but it can easily scale to thousands or millions of updates per event. The function(s) that should emit `MetadataUpdates` and the frequency of these on-chain updates is left at the discretion of this standard implementation. - -The proposal is extremely gas efficient, since gas costs are only proportional to the frequency of committing changes. Many changes for many tokens can be batched in one transaction for the cost of only one `emit`. - -## Reference Implementation - -### Transformation engines - -We have been experimenting with this generic Metadata update proposal using the JSONata transformation language. - -Here is a very simple example of a NFT metadata for an imaginary 'little monster' game : - -```json -{ - "name": "Monster 1", - "description": "Little monsters you can play with.", - "attributes": [ - { "trait_type": "Level", "value": 0 }, - { "trait_type": "Stamina", "value": 100 } - ], - "updatable": { - "engine": "jsonata@1.8.*", - "recipes": { - "levelUp": { - "eval": "$ ~> | attributes[trait_type='Level'] | {'value': value + 1} |" - }, - "updateDescription": { - "eval": "$ ~> | $ | {'description': $newDescription} |" - } - } - } -} - ``` - -This updatable metadata can only be updated to increment by one the trait attribute "Level". - -An example JSON updates metadata would be : -```json -{ - "updates": [ - {"tokenId":"1","action":"levelUp"}, - {"tokenId":"2","action":"levelUp"}, - {"tokenId":"1","action":"updateDescription","args":{"newDescription":"Now I'm a big monster"}}, - {"tokenId":"1","action":"levelUp"}, - {"tokenId":"3","action":"levelUp"} - ] -} - ``` - -## Security Considerations - -A malicious recipe in the original metadata might be constructed as a DDoS vector for third parties marketplaces and tools that calculate NFT updated JSON metadata. They are encouraged to properly encapsulate software in charge of these calculations and put limits for the engine updates processing. - -Smart contracts should be careful and conscious of using this extension and still allow the metadata URI to be updated in some contexts (by not having the same URI returned by `tokenURI` or `uri` for a given tokenId over time). They need to take into account if previous changes could have been already broadcasted for that NFT by the contract, if these changes are compatible with the new "original metadata" and what semantic they decide to associate by combining these two kinds of "updates". - -## Backwards Compatibility - -The proposal is fully compatible with both [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). Third-party applications that don't support this EIP will still be able to use the original metadata for each NFT. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5185.md diff --git a/EIPS/eip-5187.md b/EIPS/eip-5187.md index bb1ff12a15deeb..d4905de87b3a80 100644 --- a/EIPS/eip-5187.md +++ b/EIPS/eip-5187.md @@ -1,148 +1,7 @@ --- eip: 5187 -title: Extend EIP-1155 with rentable usage rights -description: Separate ownership and usage rights of EIP-1155 to allow users to use NFTs for an allotted time and return them to owners after expiration. -author: DerivStudio (@DerivStudio) -discussions-to: https://ethereum-magicians.org/t/eip-draft-extending-erc1155-with-rentable-usage-rights/9553/4 -status: Draft -type: Standards Track category: ERC -created: 2022-04-17 -requires: 165, 1155 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-1155](./eip-1155.md). It proposes to introduce separable, rentable, and transferable usage rights (in the form of NFT-IDs), enabling the property owner (the only NFT holder) to rent out the NFT to multiple users (ID holders) at the same time for different terms, and be withdrawn by smart contract upon expiration. - -The property owner always retains ownership and is able to transfer the NFT to others during the lease. - -The proposal also supports the sublease and renewal of the rental so that users can freely transfer the usage rights among each other and extend the lease term. Early return of NFTs can also be achieved by subletting the usage rights back to the property owners. - -## Motivation - -The well-accepted [EIP-721](./eip-721.md) and EIP-1155 standards focused on the ownership of unique assets, quite sensible in the time of NFTs being used primarily as arts and collectibles, or, you can say, as private property rights. -### First Step: "Expirable" NFTs -The advent of private ownership in the real world has promoted the vigorous development of the modern economy, and we believe that the usage right will be the first detachable right widely applied in the blockchain ecosystem. As NFTs are increasingly applied in rights, finance, games, and the Metaverse, the value of NFT is no longer simply the proof of ownership, but with limitless practice use scenarios. For example, artists may wish to rent out their artworks to media or audiences within specific periods, and game guilds may wish to rent out game items to new players to reduce their entry costs. - -The lease/rental of NFTs in the crypto space is not a new topic, but the implementation of leasing has long relied on over-collateralization, centralized custody, or pure trust, which significantly limits the boom of the leasing market. Therefore, a new type of "expirable" NFTs that can be automatically withdrawn upon expiration through smart contract is proposed, at the technical level, to eliminate those bottlenecks. Based on that, a new leasing model that is decentralized, collateral-free, and operated purely "on-chain" may disrupt the way people trade and use NFTs. Thus, this EIP proposal is here to create "expirable" NFTs compatible with EIP-1155. -### Then, Make Everything Transferable -The way we achieve leasing is to separate ownership and usage rights, and beyond that, we focus more on making them freely priced and traded after separation, which is impossible to happen in the traditional financial field. Imagine the below scenarios: i) as a landlord, you can sell your house in rental to others without affecting the tenancy, and your tenants will then pay rent to the new landlord; ii) as a tenant, you can sublet the house to others without the consent of the landlord, and even the one sublets can continue subletting the house until the lease term is close the last tenant can apply for a renewal of the lease. All of this can happen in the blockchain world, and that's the beauty of blockchain. Without permission, without trust, code is the law. - -Making ownership and usage rights transferable may further revolutionize the game rules in NFT's field, both in capital allocation and NFT development. Buying NFT ownership is more like investing in stocks, and the price is determined by market expectations of the project; renting the usage right is less speculative, so the price is easier to determine based on supply and demand. The ownership market and the usage-right market will function to meet the needs of target participants and achieve a balance that is conducive to the long-term and stable development of NFT projects. -Based on the above, we propose this EIP standard to complement the current EIP scopes and introduce those functions as new standards. - - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -pragma solidity ^0.8.0; - -/// Note: the ERC-165 identifier for this interface is 0x6938e358. - interface IRental /* is IERC165,IERC1155 */ { - /** - * @notice This emits when user rent NFT - * - `id` The id of the current token - * - `user` The address to rent the NFT usage rights - * - `amount` The amount of usage rights - * - `expire` The specified period of time to rent - **/ - event Rented(uint256 indexed id,address indexed user,uint256 amount,uint256 expire); - - /** - * MUST trigger on any successful call to `renew(address user,uint256 id)` - * - `id` The id of the current token - * - `user` The user of the NFT - * - `expire` The new specified period of time to rent - **/ - event Renew(uint256 indexed id,address indexed user,uint256 expire); - - /** - * MUST trigger on any successful call to `renew(address user,uint256 id,uint256 expire)` - * - `id` The id of the current token - * - `from` The current user of the NFT - * - `to` The new user - **/ - event Sublet(uint256 indexed id,address indexed from,address to); - - /** - * @notice This emits when the NFT owner takes back the usage rights from the tenant (the `user`) - * - id The id of the current token - * - user The address to rent the NFT's usage rights - * - amount Amount of usage rights - **/ - event TakeBack(uint256 indexed id, address indexed user, uint256 amount); - - /** - * @notice Function to rent out usage rights - * - from The address to approve - * - to The address to rent the NFT usage rights - * - id The id of the current token - * - amount The amount of usage rights - * - expire The specified period of time to rent - **/ - function safeRent(address from,address to,uint256 id,uint256 amount,uint256 expire) external; - - /** - * @notice Function to take back usage rights after the end of the tenancy - * - user The address to rent the NFT's usage rights - * - tokenId The id of the current token - **/ - function takeBack(address user,uint256 tokenId) external; - - /** - * @notice Return the NFT to the address of the NFT property right owner. - **/ - function propertyRightOf(uint256 id) external view returns (address); - - /** - * @notice Return the total supply amount of the current token - **/ - function totalSupply(uint256 id) external view returns (uint256); - - /** - * @notice Return expire The specified period of time to rent - **/ - function expireAt(uint256 id,address user) external view returns(uint256); - - /** - * extended rental period - * - `id` The id of the current token - * - `user` The user of the NFT - * - `expire` The new specified period of time to rent - **/ - function renew(address user,uint256 id,uint256 expire) external; - - /** - * transfer of usage right - * - `id` The id of the current token - * - `user` The user of the NFT - * - `expire` The new specified period of time to rent - **/ - function sublet(address to,uint256 id) external; -} - - -``` - -## Rationale - -Implementing the proposal to create rentable NFTs has two main benefits. - -One is that NFTs with multiple usage rights allow NFT property owners to perform the safeRent function and rent out usage rights to multiple users at the same time. For each usage right leased and expires, the property owner can perform the takeBack function to retrieve the usage right. - -Another benefit is that the transfer of usage rights can be quite flexible. The user can transfer the usage rights to other users by calling the Sublet function during the lease period, and can also extend the lease period of the usage rights by asking the property owner to perform the Renewal function. It is worth mentioning that if the user sublet the NFT to the property owner, it will realize the early return of NFT before the end of the lease period. - -## Backwards Compatibility - -As mentioned at the beginning, this is an extension of EIP-1155. Therefore, it is fully backward compatible with EIP-1155. - -## Security Considerations - -Needs discussion. - -## Copyright - -Disclaimer of copyright and related rights through [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5187.md diff --git a/EIPS/eip-5189.md b/EIPS/eip-5189.md index 786275fc930984..c077cfb4fe7f38 100644 --- a/EIPS/eip-5189.md +++ b/EIPS/eip-5189.md @@ -1,225 +1,7 @@ --- eip: 5189 -title: Account Abstraction via Endorsed Operations -description: An account abstraction proposal that avoids protocol changes while maintaining compatibility with existing smart contract wallets. -author: Agustín Aguilar (@agusx1211), Philippe Castonguay (@phabc) -discussions-to: https://ethereum-magicians.org/t/erc-account-abstraction-via-endorsed-operations/9799 -type: Standards Track category: ERC -status: Stagnant -created: 2022-06-29 +status: Moved --- -## Abstract -This EIP proposes a form of account abstraction that ensures compatibility with existing smart contract wallets and provides flexibility for alternative designs while avoiding introducing changes to the consensus layer. Instead of defining a strict structure for meta-transactions, this proposal introduces the figure of `endorser` contracts. These smart contract instances are tasked with determining the quality of the submitted meta-transactions, thus safely helping bundlers determine if a meta-transaction should be kept in the mempool or not. Developers that intend to make their smart contract wallet compatible with this EIP must create and deploy an instance of an `endorser`; this instance must be seeded with a small amount of ETH to be burnt that incentivizes its good behavior. - -## Motivation -This account abstraction proposal aims to implement a generalized system for executing meta-transactions while maintaining the following goals: - -* **Achieve the primary goal of account abstraction:** allow users to use smart contract wallets containing arbitrary verification and execution logic instead of EOAs as their primary account. -* **Decentralization:** -* * Allow any bundler to participate in the process of including meta-transactions. -* * Work with all activity happening over a public mempool without having to concentrate transactions on centralized relayers. -* * Define structures that help maintain a healthy mempool without risking its participants from getting flooded with invalid or malicious payloads. -* * Avoid trust assumptions between bundlers, developers, and wallets. -* **Support existing smart contract wallet implementations:** Work with all the smart contract wallets already deployed and active while avoiding forcing each wallet instance to be manually upgraded. -* **Provide an unrestrictive framework:** Smart contract wallets are very different in design, limitations, and capabilities from one another; the proposal is designed to accommodate almost all possible variations. -* **No overhead:** Smart contract wallets already have a cost overhead compared to EOA alternatives, the proposal does not worsen the current situation. -* **Support other use cases:** -* * Privacy-preserving applications. -* * Atomic multi-operations (similar to EIP-3074). -* * Payment of transaction fees using ERC-20 tokens. -* * Scheduled execution of smart contracts without any user input. -* * Applications that require a generalistic relayer. - -## Specification -To avoid Ethereum consensus changes, we do not attempt to create new transaction types for account-abstracted transactions. Instead, meta-transactions are packed up in a struct called `Operation`, operations are structs composed by the following fields: - -| Field | Type | Description | -|-------------------|---------|--------------------------------------------------------------------------------------------------------| -| entrypoint | address | contract address that must be called with `callData` to execute the `operation`. | -| callData | bytes | data that must be passed to the `entrypoint` call to execute the `operation`. | -| gasLimit | uint64 | minimum gasLimit that must be passed when executing the `operation`. | -| endorser | address | address of the endorser contract that should be used to validate the `operation`. | -| endorserGasLimit | uint64 | amount of gas that should be passed to the endorser when validating the `operation`. | -| maxFeePerGas | uint256 | max amount of basefee that the `operation` execution is expected to pay, (similar to EIP-1559 `max_fee_per_gas`) | -| priorityFeePerGas | uint256 | fixed amount of fees that the `operation` execution is expected to pay to the bundler (similar to EIP-1559 `max_priority_fee_per_gas`). | - -These `Operation` objects can be sent to a dedicated operations mempool. A specialized class of actors called bundlers (either miners running special-purpose code, or just users that can relay transactions to miners) listen for operations on the mempool and execute these transactions. - -Transactions are executed by calling the `entrypoint` with the provided `callData`. The `entrypoint` can be any contract, but most commonly it will be the wallet contract itself, alternatively it can be an intermediary utility that deploys the wallet and then performs the transaction. - -#### Endorser functionality -Mempool participants need to be able to able to filter "good operations" (operations that pay the bundler the defined fee) from "bad operations" (operations that either miss payment or revert altogether). - -This categorization is facilitated by the `endorser`; the endorser must be a deployed smart contract that implements the following interface: - -```solidity -interface Endorser { - struct Dependency { - address addr; - bool balance; - bool code; - bool nonce; - bytes32[] slots; - } - - function isOperationReady( - address _entrypoint, - bytes calldata _data, - uint256 _gasLimit, - uint256 _maxFeePerGas, - uint256 _maxPriorityFeePerGas - ) external view returns ( - bool readiness, - Dependency[] memory dependencies - ); -} -``` - -It should also be registered in the `EndorserRegistry` with a minimum amount of burned ETH (Mempool operators are free to accept operations from endorsers without any burn, but they would increase their risk exposing themselves to denial of service attacks). - -When the `isOperationReady` method is called, the endorser must return this information: - -* **readiness:** when returning`true`, it means the transaction WILL be executed correctly and the bundler WILL be paid the offered gas fees (even if the underlying intent of the operation fails). -* **dependencies:** a comprehensive list of addresses and storage slots that must be monitored; any state change in these dependencies MUST trigger a re-evaluation of the operation's readiness. - -The information provided by the endorser helps the mempool operator maintain a pool of "good" meta-transactions that behave correctly; it DOES NOT guarantee that such transactions will be able to be executed correctly. Bundlers must always simulate the result of the execution before including a transaction in a block. - -#### Dependencies -| Field | Type | Description | -| -------- | -------- | -------- | -| addr | address | Contract address of the dependencies entry *(only one entry per address should be allowed)*. | -| balance | bool | `true` if the balance of `addr` should be considered a dependency of the `operation`. | -| code | bool | `true` if the code of `addr` should be considered a dependency of the `operation`. | -| nonce | bool | `true` if the nonce of `addr` should be considered a dependency of the `operation`. | -| slots | bytes32[] | List of all storage slots of `addr` that should be considered dependencies of `operation`. | - -The `endorser` does not need to include all accessed storage slots on the dependencies list, it only needs to include storage slots that after a change may also result in a change of readiness. - -> E.g. A wallet may pay fees using funds stored as WETH. During `isValidOperation()`, the endorser contract may call the `balanceOf` method of the `WETH` contract to determine if the wallet has enough `WETH` balance. Even though the ETH balance of the WETH contract and the code of the WETH contract are being accessed, the endorser only cares about the user's WETH balance for this operation and hence does not include these as dependencies. - -### Misbehavior detection -The `endorser` contracts may behave maliciously or erratically in the following ways: - -* (1) It may consider an operation `ready`, but when the operation is executed it transfers less than the agreed-upon fees to the bundler. -* (2) It may consider an operation `ready`, but when the operation is executed the top-level call fails. -* (3) It may change the status from `ready` to `not-ready` while none of the dependencies register any change. - -The bundler must always discard and re-evaluate the readiness status after a change on any of the dependencies of the `operation`, meaning that only operations considered `ready` are candidates for constructing the next block. - -If, when simulating the final inclusion of the operation, the bundler discovers that it does not result in correct payment (either because the transaction fails, or transferred amount is below the defined fee), then it should proceed to ban the `endorser` for one of the following reasons: - -1) The `endorser` returns `isOperationReady == true` even though the `operation` is not healthy to be included in a block. -2) The `operation` changed readiness status from `true` to `false` while all dependencies remained unchanged. - -After an `endorser` is banned, the mempool operator should drop all `operations` related to such endorser. - -> Notice: The mempool operator could call one last time `isOperationReady` to determine if the `endorser` should be banned because `(1)` or `(2)`, but this step is not strictly necessary since both scenarios lead to the `endoser` being banned. - -### Client behavior upon receiving an operation -When a client receives an `operation`, it must first run some basic sanity checks, namely that: - -* The `endorserGasLimit` is sufficiently low (<= `MAX_ENDORSER_GAS`). -* The endorser (i) is registered and has enough burn (>= `MIN_ENDORSER_BURN`), and (ii) it has not been internally flagged as banned. -* The `gasLimit` is at least the cost of a `CALL` with a non-zero value. -* The `maxFeePerGas` and `priorityPerGas` are above a configurable minimum value the client is willing to accept. -* If another operation exists in the mempool with the exact same dependency set AND the same endorser address, the `maxFeePerGas` and `priorityFeePerGas` of the newly received operation MUST be 12% higher than the one on the mempool to replace it. (Similar with how EOA with same nonce work) - -If the `operation` passes these checks, then the client MUST call `isOperationReady()` on the `endorser`. If the endorser considers the operation ready, then the client MUST add the operation to the mempool. Otherwise, the operation MUST discarded. - -The `endorser` result MUST be invalidated and its readiness be re-evaluated if any of the values of the provided dependencies change. If the operation readiness changes to `false`, the operation MUST be discarded. - -Before including the operation in a block, a last simulation MUST be performed, this time without calling the `endorser`, but by constructing the block and probing the result. All transactions in the block listed **before** the operation must be simulated and the endorser must be queried again there for readiness in-case some dependencies changed. - -If the operation fails during simulation, the endorser must be banned because (i) it returned a bad readiness state or (ii) it changed the operation readiness independently from the dependencies. - -Additional events that must invalidate the readiness are: - -* A transaction or operation modifies the same storage slots (as the dependencies) is queued before the given operation. - -#### Optional rules -Mempool clients could implement additional rules to further protect against maliciously constructed transactions. -* Limit the size of accepted dependencies to `MAX_OPERATION_DEPENDENCIES`, dropping operations that cross the boundary. -* Limit the number of times an operation may trigger a re-evaluation to `MAX_OPERATION_REEVALS`, dropping operations that cross the boundary. -* Limit the number of operations in the mempool that depend on the same dependency slots. - -If these rules are widely adopted, wallet developers should keep usage of dependencies to the lowest possible levels. - -#### Evaluation -To evaluate an `operation`, the client must call the `isOperationReady` method, with a `gasLimit` above or equal to `endorserGasLimit`. - -If the call fails, or the `endorser` returns `ready == false`, then the operation must be dropped from the mempool. - -If the call succeeds and returns `ready == true`, then the operation can be kept in the mempool and used when constructing the next block. The client must keep track of all fields returned as `dependencies`. If any of these register a change, then readiness should be reevaluated. - - -#### After operation inclusion -There is no limit in-place that defines that an operation can only be executed once. - -The bundler MUST NOT drop an `operation` after successfully including such operation in a block, the `operation` must remain in the mempool and a last `isOperationReady` call must be performed. - -If the `endorser` still returns `readiness == true` (after inclusion) then the operation SHOULD be treated as any other healthy operation, and thus it COULD be kept in the mempool. - -### Endorser registry -The endorser registry serves as a place to register the burn of each endorser, anyone can increase the burn of any endorser by calling the `addBurn` function. - -All burn is effectively locked forever; slashing can't be reliably proved on-chain without protocol alterations, so it remains a virtual event on which mempool operators will ignore the deposited ETH. - -#### Implementation -(EXAMPLE) - -```solidity -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.15; - - -contract EndorserRegistry { - event Burned( - address indexed _endorser, - address indexed _sender, - uint256 _new, - uint256 _total - ); - - mapping(address => uint256) public burn; - - function addBurn(address _endorser) external payable returns (uint256) { - uint256 total = burn[_endorser] + msg.value; - burn[_endorser] = total; - - emit Burned(_endorser, msg.sender, msg.value, total); - - return total; - } -} -``` - -## Rationale -The main challenge with a purely smart contract wallet-based account abstraction system is DoS safety: how can a bundler that includes an operation make sure that it will pay fees without executing the entire operation? - -Bundlers could execute the entire operation to determine if it is healthy or not, but this operation may be expensive and complex for the following reasons: - -* The bundler does not have a way to simulate the transaction with a reduced amount of gas; it has to use the whole `gasLimit`, exposing itself to a higher level of griefing. -* The bundler does not have a way to know if a change to the state will affect the operation or not, and thus it has to re-evaluate the operation after every single change. -* The bundler does not have a way to know if a change to the state will invalidate a large portion of the mempool. - -In this proposal, we add the `endorser` as a tool for the bundlers to validate arbitrary operations in a controlled manner, without the bundler having to know any of the inner workings of such operation. - -In effect, we move the responsibility from the wallet to the wallet developer; the developer must code, deploy and burn ETH for the `endorser`; this is a nearly ideal scenario because developers know how their wallet operations work, and thus they can build tools to evaluate these operations efficiently. - -Additionally, the specification is kept as simple as possible as enforcing a highly structured behavior and schema for smart contract wallet transactions may stagnate the adoption of more innovative types of wallets and the adoption of a shared standard among them. - -#### Differences with alternative proposals -1) This proposal does not require monitoring for forbidden opcodes or storage access boundaries. Wallets have complete freedom to use any EVM capabilities during validation and execution. -2) This proposal does not specify any replay protection logic since all existing smart contract wallets already have their own, and designs can vary among them. Nonces can be communicated to the bundler using a `dependency`. -3) This proposal does not specify a pre-deployment logic because it can be handled directly by the entrypoint. -4) This proposal does not require wallets to accept `execution` transactions from a trusted entrypoint contract, reducing overhead and allowing existing wallets to be compatible with the proposal. -5) This proposal does not distinguish between `execution` and `signature` payloads, this distinction remains implementation-specific. - - -## Backwards Compatibility -This EIP does not change he consensus layer, nor does impose changes on existing smart contract wallets, so there are no backwards compatibility issues. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5189.md diff --git a/EIPS/eip-5192.md b/EIPS/eip-5192.md old mode 100755 new mode 100644 index 30e5d147e25d5d..d359d2343d5c6f --- a/EIPS/eip-5192.md +++ b/EIPS/eip-5192.md @@ -1,71 +1,7 @@ --- eip: 5192 -title: Minimal Soulbound NFTs -description: Minimal interface for soulbinding EIP-721 NFTs -author: Tim Daubenschütz (@TimDaub), Anders (@0xanders) -discussions-to: https://ethereum-magicians.org/t/eip-5192-minimal-soulbound-nfts/9814 -status: Final -type: Standards Track category: ERC -created: 2022-07-01 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes a minimal interface to make tokens soulbound using the feature detection functionality of [EIP-165](./eip-165.md). A soulbound token is a non-fungible token bound to a single account. - -## Motivation - -The Ethereum community has expressed a need for non-transferrable, non-fungible, and socially-priced tokens similar to World of Warcraft’s soulbound items. But the lack of a token standard leads many developers to simply throw errors upon a user's invocation of transfer functionalities. Over the long term, this will lead to fragmentation and less composability. - -In this document, we outline a minimal addition to [EIP-721](./eip-721.md) that allows wallet implementers to check for a token contract's permanent (non-)transferability using [EIP-165](./eip-165.md). - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Contract Interface - -A token with a `uint256 tokenId` may be bound to a receiving account with `function locked(...)` returning `true`. In this case, all [EIP-721](./eip-721.md) functions of the contract that transfer the token from one account to another must throw. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface IERC5192 { - /// @notice Emitted when the locking status is changed to locked. - /// @dev If a token is minted and the status is locked, this event should be emitted. - /// @param tokenId The identifier for a token. - event Locked(uint256 tokenId); - - /// @notice Emitted when the locking status is changed to unlocked. - /// @dev If a token is minted and the status is unlocked, this event should be emitted. - /// @param tokenId The identifier for a token. - event Unlocked(uint256 tokenId); - - /// @notice Returns the locking status of an Soulbound Token - /// @dev SBTs assigned to zero address are considered invalid, and queries - /// about them do throw. - /// @param tokenId The identifier for an SBT. - function locked(uint256 tokenId) external view returns (bool); -} -``` - -To aid recognition that an [EIP-721](./eip-721.md) token implements "soulbinding" via this EIP upon calling [EIP-721](./eip-721.md)'s `function supportsInterface(bytes4 interfaceID) external view returns (bool)` with `interfaceID=0xb45a3c0e`, a contract implementing this EIP must return `true`. - -## Rationale - -The above model is the simplest possible path towards a canonical interface for Soulbound tokens. It reflects upon the numerous Soulbound token implementations that simply revert upon transfers. - -## Backwards Compatibility - -This proposal is fully backward compatible with [EIP-721](./eip-721.md). - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5192.md diff --git a/EIPS/eip-5202.md b/EIPS/eip-5202.md index b7b35009adcdf8..a91ed535bbce97 100644 --- a/EIPS/eip-5202.md +++ b/EIPS/eip-5202.md @@ -1,105 +1,7 @@ --- eip: 5202 -title: Blueprint contract format -description: Define a bytecode container format for indexing and utilizing blueprint contracts -author: Charles Cooper (@charles-cooper), Edward Amor (@skellet0r) -discussions-to: https://ethereum-magicians.org/t/erc-5202-standard-factory-contract-format/9851 -status: Review -type: Standards Track category: ERC -created: 2022-06-23 -requires: 170 +status: Moved --- -## Abstract -Define a standard for "blueprint" contracts, or contracts which represent initcode that is stored on-chain. - -## Motivation -To decrease deployer contract size, a useful pattern is to store initcode on chain as a "blueprint" contract, and then use `EXTCODECOPY` to copy the initcode into memory, followed by a call to `CREATE` or `CREATE2`. However, this comes with the following problems: - -- It is hard for external tools and indexers to detect if a contract is a "regular" runtime contract or a "blueprint" contract. Heuristically searching for patterns in bytecode to determine if it is initcode poses maintenance and correctness problems. -- Storing initcode byte-for-byte on-chain is a correctness and security problem. Since the EVM does not have a native way to distinguish between executable code and other types of code, unless the initcode explicitly implements ACL rules, *anybody* can call such a "blueprint" contract and execute the initcode directly as ordinary runtime code. This is particularly problematic if the initcode stored by the blueprint contract has side effects such as writing to storage or calling external contracts. If the initcode stored by the blueprint contract executes a `SELFDESTRUCT` opcode, the blueprint contract could even be removed, preventing the correct operation of downstream deployer contracts that rely on the blueprint existing. For this reason, it would be good to prefix blueprint contracts with a special preamble to prevent execution. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -A blueprint contract MUST use the preamble `0xFE71`. 6 bits are allocated to the version, and 2 bits to the length encoding. The first version begins at 0 (`0b000000`), and versions increment by 1. The value `0b11` for `` is reserved. In the case that the length bits are `0b11`, the third byte is considered a continuation byte (that is, the version requires multiple bytes to encode). The exact encoding of a multi-byte version is left to a future ERC. - -A blueprint contract MUST contain at least one byte of initcode. - -A blueprint contract MAY insert any bytes (data or code) between the version byte(s) and the initcode. If such variable length data is used, the preamble must be `0xFE71`. The `` represent a number between 0 and 2 (inclusive) describing how many bytes `` takes, and `` is the big-endian encoding of the number of bytes that `` takes. - -## Rationale -- To save gas and storage space, the preamble should be as minimal as possible. - -- It is considered "bad" behavior to try to CALL a blueprint contract directly, therefore the preamble starts with `INVALID (0xfe)` to end execution with an exceptional halting condition (rather than a "gentler" opcode like `STOP (0x00)`). - -- To help distinguish a blueprint contract from other contracts that may start with `0xFE`, a "magic" byte is used. The value `0x71` was arbitrarily chosen by taking the last byte of the keccak256 hash of the bytestring "blueprint" (i.e.: `keccak256(b"blueprint")[-1]`). - -- An empty initcode is disallowed by the spec to prevent what might be a common mistake. - -- Users may want to include arbitrary data or code in their preamble. To allow indexers to ignore these bytes, a variable length encoding is proposed. To allow the length to be only zero or one bytes (in the presumably common case that `len(data bytes)` is smaller than 256), two bits of the third byte are reserved to specify how many bytes the encoded length takes. - -- In case we need an upgrade path, version bits are included. While we do not expect to exhaust the version bits, in case we do, a continuation sequence is reserved. Since only two bytes are required for `` (as [EIP-170](./eip-170.md) restricts contract length to 24KB), a `` value of 3 would never be required to describe ``. For that reason, the special `` value of `0b11` is reserved as a continuation sequence marker. - -- The length of the initcode itself is not included by default in the preamble because it takes space, and it can be trivially determined using `EXTCODESIZE`. - -- The EOF ([EIP-3540](./eip-3540.md)) could provide another way of specifying blueprint contracts, by adding another section kind (3 - initcode). However, it is not yet in the EVM, and we would like to be able to standardize blueprint contracts today, without relying on EVM changes. If, at some future point, section kind 3 becomes part of the EOF spec, and the EOF becomes part of the EVM, this ERC will be considered to be obsolesced since the EOF validation spec provides much stronger guarantees than this ERC. - - -## Backwards Compatibility -Needs discussion - -## Reference Implementation - -```python -from typing import Optional, Tuple - -def parse_blueprint_preamble(bytecode: bytes) -> Tuple[int, Optional[bytes], bytes]: - """ - Given bytecode as a sequence of bytes, parse the blueprint preamble and - deconstruct the bytecode into: - the ERC version, preamble data and initcode. - Raises an exception if the bytecode is not a valid blueprint contract - according to this ERC. - arguments: - bytecode: a `bytes` object representing the bytecode - returns: - (version, - None if is 0, otherwise the bytes of the data section, - the bytes of the initcode, - ) - """ - if bytecode[:2] != b"\xFE\x71": - raise Exception("Not a blueprint!") - - erc_version = (bytecode[2] & 0b11111100) >> 2 - - n_length_bytes = bytecode[2] & 0b11 - if n_length_bytes == 0b11: - raise Exception("Reserved bits are set") - - data_length = int.from_bytes(bytecode[3:3 + n_length_bytes], byteorder="big") - - if n_length_bytes == 0: - preamble_data = None - else: - data_start = 3 + n_length_bytes - preamble_data = bytecode[data_start:data_start + data_length] - - initcode = bytecode[3 + n_length_bytes + data_length:] - - if len(initcode) == 0: - raise Exception("Empty initcode!") - - return erc_version, preamble_data, initcode -``` - -## Security Considerations - -There could be contracts on-chain already which happen to start with the same prefix as proposed in this ERC. However, this is not considered a serious risk, because the way it is envisioned that indexers will use this is to verify source code by compiling it and prepending the preamble. - -As of 2022-07-08, no contracts deployed on the Ethereum mainnet have a bytecode starting with `0xFE71`. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5202.md diff --git a/EIPS/eip-5216.md b/EIPS/eip-5216.md index 1e16fd4ce598cb..70a3f279d40a93 100644 --- a/EIPS/eip-5216.md +++ b/EIPS/eip-5216.md @@ -1,104 +1,7 @@ --- eip: 5216 -title: EIP-1155 Approval By Amount Extension -description: Extension for EIP-1155 secure approvals -author: Iván Mañús (@ivanmmurciaua), Juan Carlos Cantó (@EscuelaCryptoES) -discussions-to: https://ethereum-magicians.org/t/eip-erc1155-approval-by-amount/9898 -status: Last Call -last-call-deadline: 2022-11-12 -type: Standards Track category: ERC -created: 2022-07-11 -requires: 20, 165, 1155 +status: Moved --- -## Abstract - -This EIP defines standard functions for granular approval of [EIP-1155](./eip-1155.md) tokens by both `id` and `amount`. This EIP extends [EIP-1155](./eip-1155.md). - -## Motivation - -[EIP-1155](./eip-1155.md)'s popularity means that multi-token management transactions occur on a daily basis. Although it can be used as a more comprehensive alternative to [EIP-721](./eip-721.md), EIP-1155 is most commonly used as intended: creating multiple `id`s, each with multiple tokens. While many projects interface with these semi-fungible tokens, by far the most common interactions are with NFT marketplaces. - -Due to the nature of the blockchain, programming errors or malicious operators can cause permanent loss of funds. It is therefore essential that transactions are as trustless as possible. EIP-1155 uses the `setApprovalForAll` function, which approves ALL tokens with a specific `id`. This system has obvious minimum required trust flaws. This EIP combines ideas from [EIP-20](./eip-20.md) and [EIP-721](./eip-721.md) in order to create a trust mechanism where an owner can allow a third party, such as a marketplace, to approve a limited (instead of unlimited) number of tokens of one `id`. - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Contracts using this EIP MUST implement the `IERC1155ApprovalByAmount` interface. - -### Interface implementation - -```solidity -/** - * @title ERC-1155 Approval By Amount Extension - * Note: the ERC-165 identifier for this interface is 0x1be07d74 - */ -interface IERC1155ApprovalByAmount is IERC1155 { - - /** - * @notice Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to - * `id` and with an amount: `amount`. - */ - event ApprovalByAmount(address indexed account, address indexed operator, uint256 id, uint256 amount); - - /** - * @notice Grants permission to `operator` to transfer the caller's tokens, according to `id`, and an amount: `amount`. - * Emits an {ApprovalByAmount} event. - * - * Requirements: - * - `operator` cannot be the caller. - */ - function approve(address operator, uint256 id, uint256 amount) external; - - /** - * @notice Returns the amount allocated to `operator` approved to transfer `account`'s tokens, according to `id`. - */ - function allowance(address account, address operator, uint256 id) external view returns (uint256); -} -``` - -The `approve(address operator, uint256 id, uint256 amount)` function MUST be either `public` or `external`. - -The `allowance(address account, address operator, uint256 id)` function MUST be either `public` or `external` and MUST be `view`. - -The `safeTrasferFrom` function (as defined by EIP-1155) MUST: - -- Not revert if the user has approved `msg.sender` with a sufficient `amount` -- Subtract the transferred amount of tokens from the approved amount if `msg.sender` is not approved with `setApprovalForAll` - -In addition, the `safeBatchTransferFrom` MUST: - -- Add an extra condition that checks if the `allowance` of all `ids` have the approved `amounts` (See `_checkApprovalForBatch` function reference implementation) - -The `ApprovalByAmount` event MUST be emitted when a certain number of tokens are approved. - -The `supportsInterface` method MUST return `true` when called with `0x1be07d74`. - -## Rationale - -The name "EIP-1155 Approval By Amount Extension" was chosen because it is a succinct description of this EIP. Users can approve their tokens by `id` and `amount` to `operator`s. - -By having a way to approve and revoke in a manner similar to [EIP-20](./eip-20.md), the trust level can be more directly managed by users: - -- Using the `approve` function, users can approve an operator to spend an `amount` of tokens for each `id`. -- Using the `allowance` function, users can see the approval that an operator has for each `id`. - -The [EIP-20](./eip-20.md) name patterns were used due to similarities with [EIP-20](./eip-20.md) approvals. - -## Backwards Compatibility - -This standard is compatible with [EIP-1155](./eip-1155.md). - -## Reference Implementation - -The reference implementation can be found [here](../assets/eip-5216/ERC1155ApprovalByAmount.sol). - -## Security Considerations - -Users of this EIP must thoroughly consider the amount of tokens they give permission to `operators`, and should revoke unused authorizations. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5216.md diff --git a/EIPS/eip-5218.md b/EIPS/eip-5218.md index 5c3222b821afd8..20c14cd8a73e6c 100644 --- a/EIPS/eip-5218.md +++ b/EIPS/eip-5218.md @@ -1,239 +1,7 @@ --- eip: 5218 -title: NFT Rights Management -description: An interface for creating copyright licenses that transfer with an NFT. -author: James Grimmelmann (@grimmelm), Yan Ji (@iseriohn), Tyler Kell (@relyt29) -discussions-to: https://ethereum-magicians.org/t/eip-5218-nft-rights-management/9911 -status: Draft -type: Standards Track category: ERC -created: 2022-07-11 -requires: 721 +status: Moved --- - - -## Abstract - -The following standard defines an API for managing NFT licenses. This standard provides basic functionality to create, transfer, and revoke licenses, and to determine the current licensing state of an NFT. The standard does not define the legal details of the license. Instead, it provides a structured framework for recording licensing details. - -We consider use cases of NFT creators who wish to give the NFT holder a copyright license to use a work associated with the NFT. The license can optionally be revoked under conditions specified by the creator. The holder of an active license can issue sublicenses to others to carry out the rights granted under the license. - - -## Motivation - -The [EIP-721](./eip-721.md) standard defines an API to track and transfer ownership of an NFT. When an NFT is to represent some off-chain asset, however, we would need some legally effective mechanism to *tether* the on-chain asset (NFT) to the off-chain property. One important case of off-chain property is creative work such as an image or music file. Recently, most NFT projects involving creative works have used licenses to clarify what legal rights are granted to the NFT owner. But these licenses are almost always off-chain and the NFTs themselves do not indicate what licenses apply to them, leading to uncertainty about rights to use the work associated with the NFT. It is not a trivial task to avoid all the copyright vulnerabilities in NFTs, nor have existing EIPs addressed rights management of NFTs beyond the simple cases of direct ownership (see [EIP-721](./eip-721.md)) or rental (see [EIP-4907](./eip-4907.md)). - -This EIP attempts to provide a standard to facilitate rights management of NFTs in the world of Web3. In particular, [EIP-5218](./eip-5218.md) smart contracts allow all licenses to an NFT, including the *root license* issued to the NFT owner and *sublicenses* granted by a license holder, to be recorded and easily tracked with on-chain data. These licenses can consist of human-readable legal code, machine-readable summaries such as those written in CC REL, or both. An EIP-5218 smart contract points to a license by recording a URI, providing a reliable reference for users to learn what legal rights they are granted and for NFT creators and auditors to detect unauthorized infringing uses. - - - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -**Every EIP-5218 compliant contract *must* implement the `IERC5218` interface**: - -```solidity -pragma solidity ^0.8.0; - -/// @title EIP-5218: NFT Rights Management -interface IERC5218 is IERC721 { - - /// @dev This emits when a new license is created by any mechanism. - event CreateLicense(uint256 _licenseId, uint256 _tokenId, uint256 _parentLicenseId, address _licenseHolder, string _uri, address _revoker); - - /// @dev This emits when a license is revoked. Note that under some - /// license terms, the sublicenses may be `implicitly` revoked following the - /// revocation of some ancestral license. In that case, your smart contract - /// may only emit this event once for the ancestral license, and the revocation - /// of all its sublicenses can be implied without consuming additional gas. - event RevokeLicense(uint256 _licenseId); - - /// @dev This emits when the a license is transferred to a new holder. The - /// root license of an NFT should be transferred with the NFT in an ERC721 - /// `transfer` function call. - event TransferLicense(uint256 _licenseId, address _licenseHolder); - - /// @notice Check if a license is active. - /// @dev A non-existing or revoked license is inactive and this function must - /// return `false` upon it. Under some license terms, a license may become - /// inactive because some ancestral license has been revoked. In that case, - /// this function should return `false`. - /// @param _licenseId The identifier for the queried license - /// @return Whether the queried license is active - function isLicenseActive(uint256 _licenseId) external view returns (bool); - - /// @notice Retrieve the token identifier a license was issued upon. - /// @dev Throws unless the license is active. - /// @param _licenseId The identifier for the queried license - /// @return The token identifier the queried license was issued upon - function getLicenseTokenId(uint256 _licenseId) external view returns (uint256); - - /// @notice Retrieve the parent license identifier of a license. - /// @dev Throws unless the license is active. If a license doesn't have a - /// parent license, return a special identifier not referring to any license - /// (such as 0). - /// @param _licenseId The identifier for the queried license - /// @return The parent license identifier of the queried license - function getParentLicenseId(uint256 _licenseId) external view returns (uint256); - - /// @notice Retrieve the holder of a license. - /// @dev Throws unless the license is active. - /// @param _licenseId The identifier for the queried license - /// @return The holder address of the queried license - function getLicenseHolder(uint256 _licenseId) external view returns (address); - - /// @notice Retrieve the URI of a license. - /// @dev Throws unless the license is active. - /// @param _licenseId The identifier for the queried license - /// @return The URI of the queried license - function getLicenseURI(uint256 _licenseId) external view returns (string memory); - - /// @notice Retrieve the revoker address of a license. - /// @dev Throws unless the license is active. - /// @param _licenseId The identifier for the queried license - /// @return The revoker address of the queried license - function getLicenseRevoker(uint256 _licenseId) external view returns (address); - - /// @notice Retrieve the root license identifier of an NFT. - /// @dev Throws unless the queried NFT exists. If the NFT doesn't have a root - /// license tethered to it, return a special identifier not referring to any - /// license (such as 0). - /// @param _tokenId The identifier for the queried NFT - /// @return The root license identifier of the queried NFT - function getLicenseIdByTokenId(uint256 _tokenId) external view returns (uint256); - - /// @notice Create a new license. - /// @dev Throws unless the NFT `_tokenId` exists. Throws unless the parent - /// license `_parentLicenseId` is active, or `_parentLicenseId` is a special - /// identifier not referring to any license (such as 0) and the NFT - /// `_tokenId` doesn't have a root license tethered to it. Throws unless the - /// message sender is eligible to create the license, i.e., either the - /// license to be created is a root license and `msg.sender` is the NFT owner, - /// or the license to be created is a sublicense and `msg.sender` is the holder - /// of the parent license. - /// @param _tokenId The identifier for the NFT the license is issued upon - /// @param _parentLicenseId The identifier for the parent license - /// @param _licenseHolder The address of the license holder - /// @param _uri The URI of the license terms - /// @param _revoker The revoker address - /// @return The identifier of the created license - function createLicense(uint256 _tokenId, uint256 _parentLicenseId, address _licenseHolder, string memory _uri, address _revoker) external returns (uint256); - - /// @notice Revoke a license. - /// @dev Throws unless the license is active and the message sender is the - /// eligible revoker. This function should be used for revoking both root - /// licenses and sublicenses. Note that if a root license is revoked, the - /// NFT should be transferred back to its creator. - /// @param _licenseId The identifier for the queried license - function revokeLicense(uint256 _licenseId) external; - - /// @notice Transfer a sublicense. - /// @dev Throws unless the sublicense is active and `msg.sender` is the license - /// holder. Note that the root license of an NFT should be tethered to and - /// transferred with the NFT. Whenever an NFT is transferred by calling the - /// ERC721 `transfer` function, the holder of the root license should be - /// changed to the new NFT owner. - /// @param _licenseId The identifier for the queried license - /// @param _licenseHolder The new license holder - function transferSublicense(uint256 _licenseId, address _licenseHolder) external; -} -``` - -Licenses to an NFT in general have a tree structure as below: - -The license tree - -There is one root license to the NFT itself, granting the NFT owner some rights to the linked work. The NFT owner (i.e., the root license holder) may create sublicenses, holders of which may also create sublicenses recursively. - -The full log of license creation, transfer, and revocation *must* be traceable via event logs. Therefore, all license creations and transfers *must* emit a corresponding log event. Revocation may differ a bit. An implementation of this EIP may emit a `Revoke` event only when a license is revoked in a function call, or for every revoked license, both are sufficient to trace the status of all licenses. The former costs less gas if revoking a license automatically revokes all sublicenses under it, while the latter is efficient in terms of interrogation of a license status. Implementers should make the tradeoffs depending on their license terms. - -The `revoker` of a license may be the licensor, the license holder, or a smart contract address which calls the `revokeLicense` function when some conditions are met. Implementers should be careful with the authorization, and may make the `revoker` smart contract forward compatible with transfers by not hardcoding the addresses of `licensor` or `licenseHolder`. - -The license `URI` may point to a JSON file that conforms to the "EIP-5218 Metadata JSON Schema" as below, which adopts the "three-layer" design of the Creative Commons Licenses: - -```json -{ - "title": "License Metadata", - "type": "object", - "properties": { - "legal-code": { - "type": "string", - "description": "The legal code of the license." - }, - "human-readable": { - "type": "string", - "description": "The human readable license deed." - }, - "machine-readable": { - "type": "string", - "description": "The machine readable code of the license that can be recognized by software, such as CC REL." - } - } -} -``` - -Note that this EIP doesn't include a function to update license URI so the license terms should be persistent by default. It is recommended to store the license metadata on a decentralized storage service such as IPFS or adopt the IPFS-style URI which encodes the hash of the metadata for integrity verification. On the other hand, license updatability, if necessary in certain scenarios, can be realized by revoking the original license and creating a new license, or adding a updating function, the eligibile caller of which must be carefully specified in the license and securely implemented in the smart contract. - -The `supportsInterface` method MUST return `true` when called with `0xac7b5ca9`. - -## Rationale - -This EIP aims to allow tracing all licenses to an NFT to facilitate right management. The EIP-721 standard only logs the property but not the legal rights tethered to NFTs. Even when logging the license via the optional EIP-721 Metadata extension, sublicenses are not traceable, which doesn't comply with the transparency goals of Web3. Some implementations attempt to get around this limitation by minting NFTs to represent a particular license, such as the BAYC #6068 Royalty-Free Usage License. This is not an ideal solution because the linking between different licenses to an NFT is ambiguous. An auditor has to investigate all NFTs in the blockchain and inspect the metadata which hasn't been standardized in terms of sublicense relationship. To avoid these problems, this EIP logs all licenses to an NFT in a tree data structure, which is compatible with EIP-721 and allows efficient traceability. - -This EIP attempts to tether NFTs with copyright licenses to the creative work by default and is not subject to the high legal threshold for copyright ownership transfers which require an explicit signature from the copyright owner. To transfer and track copyright ownership, one may possibly integrate EIP-5218 and [EIP-5289](./eip-5289.md) after careful scrutinizing and implement a smart contract that atomically (1) signs the legal contract via EIP-5289, and (2) transfers the NFT together with the copyright ownership via EIP-5218. Either both take place or both revert. - -## Backwards Compatibility - -This standard is compatible with the current EIP-721 standards: a contract can inherit from both EIP-721 and EIP-5218 at the same time. - -## Test Cases - -Test cases are available [here](../assets/eip-5218/contracts/test/Contract.t.sol). - -## Reference Implementation - -A reference implementation maintains the following data structures: - -```solidity - struct License { - bool active; // whether the license is active - uint256 tokenId; // the identifier of the NFT the license is tethered to - uint256 parentLicenseId; // the identifier of the parent license - address licenseHolder; // the license holder - string uri; // the license URI - address revoker; // the license revoker - } - mapping(uint256 => License) private _licenses; // maps from a license identifier to a license object - mapping(uint256 => uint256) private _licenseIds; // maps from an NFT to its root license identifier -``` - -Each NFT has a license tree and starting from each license, one can trace back to the root license via `parentLicenseId` along the path. - -In the reference implementation, once a license is revoked, all sublicenses under it are revoked. This is realized in a *lazy* manner for lower gas cost, i.e., assign `active=false` only for licenses that are explicitly revoked in a `revokeLicense` function call. Therefore, `isLicenseActive` returns `true` only if all its ancestral licenses haven't been revoked. - -For non-root licenses, the creation, transfer and revocation are straightforward: - -1. Only the holder of an active license can create sublicenses. -2. Only the holder of an active license can transfer it to a different license holder. -3. Only the revoker of an active license can revoke it. - -The root license must be compatible with `EIP-721`: - -1. When an NFT is minted, a license is granted to the NFT owner. -2. When an NFT is transferred, the license holder is changed to the new owner of the NFT. -3. When a root license is revoked, the NFT is returned to the NFT creator, and the NFT creator may later transfer it to a new owner with a new license. - -The complete implementation can be found [here](../assets/eip-5218/contracts/src/RightsManagement.sol). - -In addition, the [IC3 NFT License](../assets/eip-5218/ic3license/ic3license.pdf) is specifically designed to work with this interface and provides a reference to the language of NFT licenses. - -## Security Considerations - -Implementors of the `IERC5218` standard must consider thoroughly the permissions they give to `licenseHolder` and `revoker`. If the license is ever to be transferred to a different license holder, the `revoker` smart contract should not hardcode the `licenseHolder` address to avoid undesirable scenarios. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5218.md diff --git a/EIPS/eip-5219.md b/EIPS/eip-5219.md index 1845aad71f2208..0fc809df47fd20 100644 --- a/EIPS/eip-5219.md +++ b/EIPS/eip-5219.md @@ -1,67 +1,7 @@ --- eip: 5219 -title: Contract Resource Requests -description: Allows the requesting of resources from contracts -author: Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/pr-5219-discussion-contract-rest/9907 -status: Review -type: Standards Track category: ERC -created: 2022-07-10 +status: Moved --- -## Abstract - -This EIP standardizes an interface to make resource requests to smart contracts and to receive HTTP-like responses. - -## Motivation - -Ethereum is the most-established blockchain for building decentralized applications (referred to as `DApp`s). Due to this, the Ethereum DApp ecosystem is very diverse. However, one issue that plagues DApps is the fact that they are not fully decentralized. Specifically, to interface a "decentralized" application, one first needs to access a *centralized* website containing the DApp's front-end code, presenting a few issues. The following are some risks associated with using centralized websites to interface with decentralized applications: - -- Trust Minimization: An unnecessarily large number of entities need to be trusted -- Censorship: A centralized website is not resistant to being censored -- Permanence: The interface may not have a mechanism that permits it to be permanently stored -- Interoperability: Smart Contracts cannot directly interact with DApp interfaces - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Name Resolution - -EIPs that propose a name resolution mechanism MAY reference this EIP and MAY recommend that clients support their mechanism. Clients MAY also support regular DNS, as defined in RFC 1034 and RFC 1035. - -### Separation of Concerns - -It is RECOMMENDED to separate the application logic from the front-end logic (the contract implementing the interface defined in [Contract Interface](#contract-interface)). - -### Contract Interface - -DApp contracts MUST implement the interface defined in the following file: [Contract Interface](../assets/eip-5219/IDecentralizedApp.sol). - -## Rationale - -The `request` method was chosen to be readonly because all data should be sent to the contract from the parsed DApp. Here are some reasons why: - -- Submitting a transaction to send a request would be costly and would require waiting for the transaction to be mined, resulting in quite possibly the worst user-experience possible. -- Complicated front-end logic should not be stored in the smart contract, as it would be costly to deploy and would be better ran on the end-user's machine. -- Separation of Concerns: the front-end contract shouldn't have to worry about interacting with the back-end smart contract. -- Other EIPs can be used to request state changing operations in conjunction with a `307 Temporary Redirect` status code. - -Instead of mimicking a full HTTP request, a highly slimmed version was chosen for the following reasons: - -- The only particularly relevant HTTP method is `GET` -- Query parameters can be encoded in the resource. -- Request headers are, for the most part, unnecessary for `GET` requests. - -## Backwards Compatibility - -This EIP is backwards compatible with all standards listed in the [Name Resolution](#name-resolution) section. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5219.md diff --git a/EIPS/eip-5247.md b/EIPS/eip-5247.md index bb7779d680fa84..b16f5d4602a906 100644 --- a/EIPS/eip-5247.md +++ b/EIPS/eip-5247.md @@ -1,147 +1,7 @@ --- eip: 5247 -title: Smart Contract Executable Proposal Interface -description: An interface to create and execute proposals. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-5247-executable-proposal-standard/9938 -status: Draft -type: Standards Track category: ERC -created: 2022-07-13 +status: Moved --- -## Abstract - -This EIP presents an interface for "smart contract executable proposals": proposals that are submitted to, recorded on, and possibly executed on-chain. Such proposals include a series of information about -function calls including the target contract address, ether value to be transmitted, gas limits and calldatas. - -## Motivation - -It is oftentimes necessary to separate the code that is to be executed from the actual execution of the code. - -A typical use case for this EIP is in a Decentralized Autonomous Organization (DAO). A proposer will create a smart proposal and advocate for it. Members will then choose whether or not to endorse the proposal and vote accordingly (see [EIP-1202](./eip-1202.md)). Finallym when consensus has been formed, the proposal is executed. - -A second typical use-case is that one could have someone who they trust, such as a delegator, trustee, or an attorney-in-fact, or any bilateral collaboration format, where a smart proposal will be first composed, discussed, approved in some way, and then put into execution. - -A third use-case is that a person could make an "offer" to a second person, potentially with conditions. The smart proposal can be presented as an offer and the second person can execute it if they choose to accept this proposal. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.17; - -interface IERC5247 { - event ProposalCreated( - address indexed proposer, - uint256 indexed proposalId, - address[] targets, - uint256[] values, - uint256[] gasLimits, - bytes[] calldatas, - bytes extraParams - ); - - event ProposalExecuted( - address indexed executor, - uint256 indexed proposalId, - bytes extraParams - ); - - function createProposal( - uint256 proposalId, - address[] calldata targets, - uint256[] calldata values, - uint256[] calldata gasLimits, - bytes[] calldata calldatas, - bytes calldata extraParams - ) external returns (uint256 registeredProposalId); - - function executeProposal(uint256 proposalId, bytes calldata extraParams) external; -} -``` - -## Rationale - -* Originally, this interface was part of part of [EIP-1202](./eip-1202.md). However, the proposal itself can potentially have many use cases outside of voting. It is possible that voting may not need to be upon a proposal in any particular format. Hence, we decide to *decouple the voting interface and proposal interface*. -* Arrays were used for `target`s, `value`s, `calldata`s instead of single variables, allowing a proposal to carry arbitrarily long multiple functional calls. -* `registeredProposalId` is returned in `createProposal` so the standard can support implementation to decide their own format of proposal id. - -## Test Cases - -A simple test case can be found as - -```ts - it("Should work for a simple case", async function () { - const { contract, erc721, owner } = await loadFixture(deployFixture); - const callData1 = erc721.interface.encodeFunctionData("mint", [owner.address, 1]); - const callData2 = erc721.interface.encodeFunctionData("mint", [owner.address, 2]); - await contract.connect(owner) - .createProposal( - 0, - [erc721.address, erc721.address], - [0,0], - [0,0], - [callData1, callData2], - []); - expect(await erc721.balanceOf(owner.address)).to.equal(0); - await contract.connect(owner).executeProposal(0, []); - expect(await erc721.balanceOf(owner.address)).to.equal(2); - }); -``` - -See [testProposalRegistry.ts](../assets/eip-5247/testProposalRegistry.ts) for the whole testset. - -## Reference Implementation - -A simple reference implementation can be found. - -```solidity - function createProposal( - uint256 proposalId, - address[] calldata targets, - uint256[] calldata values, - uint256[] calldata gasLimits, - bytes[] calldata calldatas, - bytes calldata extraParams - ) external returns (uint256 registeredProposalId) { - require(targets.length == values.length, "GeneralForwarder: targets and values length mismatch"); - require(targets.length == gasLimits.length, "GeneralForwarder: targets and gasLimits length mismatch"); - require(targets.length == calldatas.length, "GeneralForwarder: targets and calldatas length mismatch"); - registeredProposalId = proposalCount; - proposalCount++; - - proposals[registeredProposalId] = Proposal({ - by: msg.sender, - proposalId: proposalId, - targets: targets, - values: values, - calldatas: calldatas, - gasLimits: gasLimits - }); - emit ProposalCreated(msg.sender, proposalId, targets, values, gasLimits, calldatas, extraParams); - return registeredProposalId; - } - function executeProposal(uint256 proposalId, bytes calldata extraParams) external { - Proposal storage proposal = proposals[proposalId]; - address[] memory targets = proposal.targets; - string memory errorMessage = "Governor: call reverted without message"; - for (uint256 i = 0; i < targets.length; ++i) { - (bool success, bytes memory returndata) = proposal.targets[i].call{value: proposal.values[i]}(proposal.calldatas[i]); - Address.verifyCallResult(success, returndata, errorMessage); - } - emit ProposalExecuted(msg.sender, proposalId, extraParams); - } -``` - -See [ProposalRegistry.sol](../assets/eip-5247/ProposalRegistry.sol) for more information. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5247.md diff --git a/EIPS/eip-5252.md b/EIPS/eip-5252.md index d2fc038b4246d1..c2eaacf9529487 100644 --- a/EIPS/eip-5252.md +++ b/EIPS/eip-5252.md @@ -1,231 +1,7 @@ --- eip: 5252 -title: Account-bound Finance -description: An EIP-5114 extension that aids in preventing arbitrary loss of funds -author: Hyungsuk Kang (@hskang9), Viktor Pernjek (@smuxx) -discussions-to: https://ethereum-magicians.org/t/pr-5252-discussion-account-bound-finance/10027 -status: Draft -type: Standards Track category: ERC -created: 2022-06-29 -requires: 20, 721, 1155, 5114 +status: Moved --- -## Abstract -This EIP proposes a form of smart contract design pattern and a new type of account abstraction on how one's finance should be managed, ensuring transparency of managing investments and protection with self-sovereignty even from its financial operators. This EIP enables greater self-sovereignty of one's assets using a personal finance contract for each individual. The seperation between an investor's funds and the operation fee is clearly specified in the personal smart contract, so investors can ensure safety from arbitrary loss of funds by the operating team's control. - -This EIP extends [EIP-5114](./eip-5114.md) to further enable transferring fund to other accounts for mobility between managing multiple wallets. - -## Motivation - -Decentralized finance (DeFi) faces a trust issue. Smart contracts are often proxies, with the actual logic of the contract hidden away in a separate logic contract. Many projects include a multi-signature "wallet" with unnecessarily-powerful permissions. And it is not possible to independently verify that stablecoins have enough real-world assets to continue maintaining their peg, creating a large loss of funds (such as happened in the official bankruptcy announcement of Celsius and UST de-pegging and anchor protocol failure). One should not trust exchanges or other third parties with one's own investments with the operators' clout in Web3.0. - -Smart contracts are best implemented as a promise between two parties written in code, but current DeFi contracts are often formed using less than 7 smart contracts to manage their whole investors' funds, and often have a trusted key that has full control. This is evidently an issue, as investors have to trust contract operators with their funds, meaning that users do not actually own their funds. - -The pattern with personal finance contract also offers more transparency than storing mixed fund financial data in the operating team's contract. With a personal finance contract, an account's activity is easier to track than one global smart contract's activity. The pattern introduces a Non-Fungiible Account-Bound Token (ABT) to store credentials from the personal finance contract. - -#### Offchain-identity vs Soul-bound token on credentials - -This EIP provides a better alternative to off-chain identity solutions which take over the whole system because their backends eventually rely on the trust of the operator, not cryptographic proof (e.g. Proof-of-work, Proof-of-stake, etc). Off-chain identity as credentials are in direct opposition to the whole premise of crypto. Soulbound tokens are a better, verifiable credential, and data stored off-chain is only to store token metadata. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -The specification consists of two patterns for **Interaction** and **Governance**. - -### Interaction - -#### Interfaces - -The interaction pattern consists of 4 components for interaction; manager, factory, finance, account-bound token, and extension. - -Interaction contract pattern is defined with these contracts: -- A soul-bound or account bound token contract to give access to interact with a financial contract with credentials -- A manager contract that interacts first contact with an investor -- A factory contract that creates a financial contract for each user -- A finance contract that can interact with the investor - -#### Requirements - -A soul-bound or account bound token contract is defined with these properties: -1. It SHALL be non-fungible and MUST satisfy [EIP-721](./eip-721.md). -2. Credentials SHOULD be represented with its metadata with `tokenURI()` function. -3. It MUST only reference factory to verify its minting. -4. If it is transferrable, it is account-bound. If not, it is soul-bound. - -A manager contract is defined with these properties: -1. It MUST be the only kind of contract which calls factory to create. -2. It SHOULD store all related configurations for financial parameters. - -A factory contract is defined with these properties: -1. It SHALL clone the finance contract with uniform implementation. -2. It MUST be the only contract that can mint account-bound token. -3. It MUST keep an recent id of account bound token. - -A finance contract is defined with these properties: -1. A finance contract MUST only be initialized once from factory contract in constructor. -2. Funds in the contract SHALL NOT be transferred to other contracts nor accounts unless sender who owns soul-bound or account bound token signs to do so. -3. Every state-changing function of the smart contract MUST only accept sender who owns soul-bound or account bound-token except global function(e.g. liquidation). -4. Global function SHOULD be commented as `/* global */` to clarify the function is can be accessed with anyone. -4. Each finance contract SHOULD be able to represent transaction that has happened only with those who had account-bound token. -5. If soul-bound token is used for access, the finance contract MUST be able to represent transaction that has happened only between whom had the private key and the finance contract. - -#### Contracts - -
-Diagram -
Fig 1 - Contract Diagram of EIP-5252
-
- - -**`Manager`**: **`Manager`** contract acts as an entry point to interact with the investor. The contract also stores parameters for **`Finance`** contract. - -**`Factory`**: **`Factory`** contract manages contract bytecode to create for managing investor's fund and clones **`Finance`** contract on **`Manager`** contract's approval. It also mints account-bound tokens to interact with the `Finance` contract. - -**`Finance`**: **`Finance`** contract specifies all rules on managing an investor's fund. The contract is only accessible with an account that has an Account-bound token. When an investor deposits a fund to **`Manager`** contract, the contract sends the fund to **`Finance`** contract account after separating fees for operation. - -**`Account-bound token`**: **`Account-bound token`** contract in this EIP can bring the **`Finance`** contract's data and add metadata. For example, if there is a money market lending -**`Finance`** contract, its **`Account-bound token`** can show how much balance is in agreement using SVG. - -**`Extension`**: **`Extension`** contract is another contract that can utilize locked funds in **`Finance`** contract. The contract can access with **`Finance`** contract on operator's approval managed in **`Manager`** contract. Example use case of `Extension` can be a membership. - -**`Metadata`**: **`Metadata`** contract is the contract where it stores metadata related to account credentials. Credential related data are stored with specific key. Images are usually displayed as SVG, but offchain image is possible. - ---- - -### Governance - -The governance pattern consists of 2 components; influencer and governor. - -#### Interfaces - -#### Requirements - -An influencer contract is defined with these properties: -1. The contract SHALL manage multiplier for votes. -2. The contract SHALL set a decimal to calculated normalized scores. -3. The contract SHALL set a function where governance can decide factor parameters. - -A governor contract is defined with these properties: -1. The contract MUST satisfy Governor contract from OpenZeppelin. -2. The contract SHALL refer influencer contract for multiplier -3. The contract MUST limit transfer of account bound token once claimed for double vote prevention. - -#### From Token Governance To Contribution Based Governance - -| | Token Governance | Credential-based Governance | -|---------------|----------------------------------|--------------------------------------------------| -| Enforcement | More tokens, more power | More contribution, More power | -| Incentives | More tokens, more incentives | More contribution, more incentives | -| Penalty | No penalty | Loss of power | -| Assignment | One who holds the token | One who has the most influence | - -
Token Governance vs Credential Based Governance
- -Token governance is not sustainable in that it gives **more** power to "those who most want to rule". Any individual who gets more than 51% of the token supply can forcefully take control. - - -New governance that considers contributions to the protocol is needed because: - -- **Rulers can be penalized on breaking the protocol** -- **Rulers can be more effectively incentivized on maintaining the protocol** - -The power should be given to "those who are most responsible". Instead of locked or owned tokens, voting power is determined with contributions marked in Account Bound Tokens (ABT). This EIP defines this form of voting power as **`Influence`**. - -#### Calculating Influence - -**`Influence`** is a multiplier on staked tokens that brings more voting power of a DAO to its contributors. To get **`Influence`**, a score is calculated on weighted contribution matrix. Then, the score is normalized to give a member's position in whole distribution. Finally, the multiplier is determined on the position in every community members. - -#### Calculating score - -The weights represent relative importance on each factor. The total importance is the total sum of the factors. More factors that can be normalized at the time of submitting proposal can be added by community. - -| | Description | -|----|------------------------------------------------| -| α | Contribution value per each **`Finance`** contract from current proposal| -| β | Time they maintained **`Finance`** per each contract from current timestamp of a proposal| - -```math -(score per each ABT) = α * (contribution value) + β * (time that abt was maintained from now) -``` - -#### Normalization - -Normalization is applied for data integrity on user's contribution in a DAO. -Normalized score can be calculated from the state of submitting a proposal - -```math -(Normalized score per each ABT) = α * (contribution value)/(total contribution value at submitting tx) + β * (time that abt was maintained)/(time passed from genesis to proposal creation) -``` - -and have a value between 0 and 1 (since α + β = 1). - -#### Multiplier - -The multiplier is determined linearly from base factor (b) and multiplier(m). - -The equation for influence is : - -```math -(influence) = m * (sum(normalized_score)) -``` - -#### Example - -For example, if a user has 3 **`Account-bound tokens`** with normalized score of each 1.0, 0.5, 0.3 and the locked token is 100, and multiplier is 0.5 and base factor is 1.5. Then the total influence is - -```math -0.5 * {(1.0 + 0.5 + 0.3) / 3} + 1.5 = 1.8 - - The total voting power would be - -```math -(voting power) = 1.8 * sqrt(100) = 18 -``` - -#### Stakers vs Enforcers - -| | Stakers | Enforcers | -|--------------|-----------------------|-----------------------------------------------------------------------------------------| -| Role | stake governance token for voting | Contributed on the system, can make proposal to change rule, more voting power like 1.5 | -| Populations | many | small | -| Contribution | Less effect | More effect | -| Influence | sqrt(locked token) | Influence * sqrt(locked token) | - -
Fig 1 - Stakers vs Enforcers
- -**Stakers**: Stakers are people who vote to enforcers' proposals and get dividend for staked tokens - -**Enforcers**: Enforcers are people who takes risk on managing protocol and contributes to the protocol by making a proposal and change to it. - -#### Contracts - -**`Influencer`**: An **`Influencer`** contract stores influence configurations and measures the contribution of a user from his activities done in a registered Account Bound Token contract. The contract puts a lock on that Account Bound Token until the proposal is finalized. - -**`Governor`**: **`Governor`** contract is compatible with the current governor contract in OpenZeppelin. For its special use case, it configures factors where the influencer manages and has access to changing parameters of **`Manager`** configs. Only the `Enforcer` can propose new parameters. - -## Rationale - -#### Gas saving for end user -The gas cost of using multiple contracts (as opposed to a single one) actually saves gas long-run if the clone factory pattern is applied. One contract storing users' states globally means each user is actually paying for the storage cost of other users after interacting with the contract. This, for example, means that MakerDAO's contract operating cost is sometimes over 0.1 ETH, limitimg users' minimum deposit for CDP in order to save gas costs. To solve inefficient n-times charging gas cost interaction for future users, one contract per user is used. - -#### Separation between investor's and operation fund -The separation between an investor's funds and operation fee is clearly specified in the smart contract, so investors can ensure safety from arbitrary loss of funds by the operating team's control. - -## Backwards Compatibility -This EIP has no known backward compatibility issues. - -## Reference Implementation - -[Reference implementation](../assets/eip-5252/README.md) is a simple deposit account contract as `Finance` contract and its contribution value α is measured with deposit amount with ETH. - -## Security Considerations - -- **`Factory`** contracts must ensure that each **`Finance`** contract is registered in the factory and check that **`Finance`** contracts are sending transactions related to their bounded owner. - -- Reentrancy attack guard should be applied or change state before delegatecall in each user function in **`Manager`** contract or **`Finance`** contract. Otherwise, **`Finance`** can be generated as double and ruin whole indices. - -- Once a user locks influence on a proposal's vote, an **`Account Bound Token`** cannot be transferred to another wallet. Otherwise, double influence can happen. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5252.md diff --git a/EIPS/eip-5267.md b/EIPS/eip-5267.md index 7201e790a638d1..44c2f824c79f7f 100644 --- a/EIPS/eip-5267.md +++ b/EIPS/eip-5267.md @@ -1,175 +1,7 @@ --- eip: 5267 -title: Retrieval of EIP-712 domain -description: A way to describe and retrieve an EIP-712 domain to securely integrate EIP-712 signatures. -author: Francisco Giordano (@frangio) -discussions-to: https://ethereum-magicians.org/t/eip-5267-retrieval-of-eip-712-domain/9951 -status: Final -type: Standards Track category: ERC -created: 2022-07-14 -requires: 155, 712, 2612 +status: Moved --- -## Abstract - -This EIP complements [EIP-712](./eip-712.md) by standardizing how contracts should publish the fields and values that describe their domain. This enables applications to retrieve this description and generate appropriate domain separators in a general way, and thus integrate EIP-712 signatures securely and scalably. - -## Motivation - -EIP-712 is a signature scheme for complex structured messages. In order to avoid replay attacks and mitigate phishing, the scheme includes a "domain separator" that makes the resulting signature unique to a specific domain (e.g., a specific contract) and allows user-agents to inform end users the details of what is being signed and how it may be used. A domain is defined by a data structure with fields from a predefined set, all of which are optional, or from extensions. Notably, EIP-712 does not specify any way for contracts to publish which of these fields they use or with what values. This has likely limited adoption of EIP-712, as it is not possible to develop general integrations, and instead applications find that they need to build custom support for each EIP-712 domain. A prime example of this is [EIP-2612](./eip-2612.md) (permit), which has not been widely adopted by applications even though it is understood to be a valuable improvement to the user experience. The present EIP defines an interface that can be used by applications to retrieve a definition of the domain that a contract uses to verify EIP-712 signatures. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Compliant contracts MUST define `eip712Domain` exactly as declared below. All specified values MUST be returned even if they are not used, to ensure proper decoding on the client side. - -```solidity -function eip712Domain() external view returns ( - bytes1 fields, - string name, - string version, - uint256 chainId, - address verifyingContract, - bytes32 salt, - uint256[] extensions -); -``` - -The return values of this function MUST describe the domain separator that is used for verification of EIP-712 signatures in the contract. They describe both the form of the `EIP712Domain` struct (i.e., which of the optional fields and extensions are present) and the value of each field, as follows. - -- `fields`: A bit map where bit `i` is set to 1 if and only if domain field `i` is present (`0 ≤ i ≤ 4`). Bits are read from least significant to most significant, and fields are indexed in the order that is specified by EIP-712, identical to the order in which they are listed in the function type. -- `name`, `version`, `chainId`, `verifyingContract`, `salt`: The value of the corresponding field in `EIP712Domain`, if present according to `fields`. If the field is not present, the value is unspecified. The semantics of each field is defined in EIP-712. -- `extensions`: A list of EIP numbers, each of which MUST refer to an EIP that extends EIP-712 with new domain fields, along with a method to obtain the value for those fields, and potentially conditions for inclusion. The value of `fields` does not affect their inclusion. - -The return values of this function (equivalently, its EIP-712 domain) MAY change throughout the lifetime of a contract, but changes SHOULD NOT be frequent. The `chainId` field, if used, SHOULD change to mirror the [EIP-155](./eip-155.md) id of the underlying chain. Contracts MAY emit the event `EIP712DomainChanged` defined below to signal that the domain could have changed. - -```solidity -event EIP712DomainChanged(); -``` - -## Rationale - -A notable application of EIP-712 signatures is found in EIP-2612 (permit), which specifies a `DOMAIN_SEPARATOR` function that returns a `bytes32` value (the actual domain separator, i.e., the result of `hashStruct(eip712Domain)`). This value does not suffice for the purposes of integrating with EIP-712, as the RPC methods defined there receive an object describing the domain and not just the separator in hash form. Note that this is not a flaw of the RPC methods, it is indeed part of the security proposition that the domain should be validated and informed to the user as part of the signing process. On its own, a hash does not allow this to be implemented, given it is opaque. The present EIP fills this gap in both EIP-712 and EIP-2612. - -Extensions are described by their EIP numbers because EIP-712 states: "Future extensions to this standard can add new fields [...] new fields should be proposed through the EIP process." - -## Backwards Compatibility - -This is an optional extension to EIP-712 that does not introduce backwards compatibility issues. - -Upgradeable contracts that make use of EIP-712 signatures MAY be upgraded to implement this EIP. - -User-agents or applications that use this EIP SHOULD additionally support those contracts that due to their immutability cannot be upgraded to implement it. The simplest way to achieve this is to hardcode common domains based on contract address and chain id. However, it is also possible to implement a more general solution by guessing possible domains based on a few common patterns using the available information, and selecting the one whose hash matches a `DOMAIN_SEPARATOR` or `domainSeparator` function in the contract. - -## Reference Implementation - -### Solidity Example - -```solidity -pragma solidity 0.8.0; - -contract EIP712VerifyingContract { - function eip712Domain() external view returns ( - bytes1 fields, - string memory name, - string memory version, - uint256 chainId, - address verifyingContract, - bytes32 salt, - uint256[] memory extensions - ) { - return ( - hex"0d", // 01101 - "Example", - "", - block.chainid, - address(this), - bytes32(0), - new uint256[](0) - ); - } -} -``` - -This contract's domain only uses the fields `name`, `chainId`, and `verifyingContract`, therefore the `fields` value is `01101`, or `0d` in hexadecimal. - -Assuming this contract is on Ethereum mainnet and its address is 0x0000000000000000000000000000000000000001, the domain it describes is: - -```json5 -{ - name: "Example", - chainId: 1, - verifyingContract: "0x0000000000000000000000000000000000000001" -} -``` - -### JavaScript - -A domain object can be constructed based on the return values of an `eip712Domain()` invocation. - -```javascript -/** Retrieves the EIP-712 domain of a contract using EIP-5267 without extensions. */ -async function getDomain(contract) { - const { fields, name, version, chainId, verifyingContract, salt, extensions } = - await contract.eip712Domain(); - - if (extensions.length > 0) { - throw Error("Extensions not implemented"); - } - - return buildBasicDomain(fields, name, version, chainId, verifyingContract, salt); -} - -const fieldNames = ['name', 'version', 'chainId', 'verifyingContract', 'salt']; - -/** Builds a domain object without extensions based on the return values of `eip712Domain()`. */ -function buildBasicDomain(fields, name, version, chainId, verifyingContract, salt) { - const domain = { name, version, chainId, verifyingContract, salt }; - - for (const [i, field] of fieldNames.entries()) { - if (!(fields & (1 << i))) { - delete domain[field]; - } - } - - return domain; -} -``` - -#### Extensions - -Suppose EIP-XYZ defines a new field `subdomain` of type `bytes32` and a function `getSubdomain()` to retrieve its value. - -The function `getDomain` from above would be extended as follows. - -```javascript -/** Retrieves the EIP-712 domain of a contract using EIP-5267 with support for EIP-XYZ. */ -async function getDomain(contract) { - const { fields, name, version, chainId, verifyingContract, salt, extensions } = - await contract.eip712Domain(); - - const domain = buildBasicDomain(fields, name, version, chainId, verifyingContract, salt); - - for (const n of extensions) { - if (n === XYZ) { - domain.subdomain = await contract.getSubdomain(); - } else { - throw Error(`EIP-${n} extension not implemented`); - } - } - - return domain; -} -``` - -Additionally, the type of the `EIP712Domain` struct needs to be extended with the `subdomain` field. This is left out of scope of this reference implementation. - -## Security Considerations - -While this EIP allows a contract to specify a `verifyingContract` other than itself, as well as a `chainId` other than that of the current chain, user-agents and applications should in general validate that these do match the contract and chain before requesting any user signatures for the domain. This may not always be a valid assumption. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5267.md diff --git a/EIPS/eip-5269.md b/EIPS/eip-5269.md index eb1b25ea608d9e..2dc062e47ebe50 100644 --- a/EIPS/eip-5269.md +++ b/EIPS/eip-5269.md @@ -1,276 +1,7 @@ --- eip: 5269 -title: EIP/ERC Detection and Discovery -description: An interface to identify if major behavior or optional behavior specified in an ERC is supported for a given caller. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc5269-human-readable-interface-detection/9957 -status: Review -type: Standards Track category: ERC -created: 2022-07-15 -requires: 5750 +status: Moved --- -## Abstract - -An interface for better identification and detection of EIP/ERC by numbers. -It designates a field in which it's called `majorEIPIdentifier` which is normally known or referred to as "EIP number". For example, `ERC-721` aka [EIP-721](./eip-721.md) has a `majorEIPIdentifier = 721`. This EIP has a `majorEIPIdentifier = 5269`. - -Calling it a `majorEIPIdentifier` instead of `EIPNumber` makes it future-proof: anticipating there is a possibility where future EIP is not numbered or if we want to incorporate other types of standards. - -It also proposes a new concept of `minorEIPIdentifier` which is left for authors of -individual EIP to define. For example, EIP-721's author may define `ERC721Metadata` -interface as `minorEIPIdentifier= keccak256("ERC721Metadata")`. - -It also proposes an event to allow smart contracts to optionally declare the EIPs they support. - -## Motivation - -This EIP is created as a competing standard for [EIP-165](./eip-165.md). - -Here are the major differences between this EIP and [EIP-165](./eip-165.md). - -1. [EIP-165](./eip-165.md) uses the hash of a method's signature which declares the existence of one method or multiple methods, -therefore it requires at least one method to *exist* in the first place. In some cases, some EIP/ERCs interface does not have a method, such as some EIPs related to data format and signature schemes or the "Soul-Bound-ness" aka SBT which could just revert a transfer call without needing any specific method. -1. [EIP-165](./eip-165.md) doesn't provide query ability based on the caller. -The compliant contract of this EIP will respond to whether it supports certain EIP *based on* a given caller. - -Here is the motivation for this EIP given EIP-165 already exists: - -1. Using EIP/ERC numbers improves human readability as well as make it easier to work with named contract such as ENS. - -2. Instead of using an EIP-165 identifier, we have seen an increasing interest to use EIP/ERC numbers as the way to identify or specify an EIP/ERC. For example - -- [EIP-5267](./eip-5267.md) specifies `extensions` to be a list of EIP numbers. -- [EIP-600](./eip-600.md), and [EIP-601](./eip-601.md) specify an `EIP` number in the `m / purpose' / subpurpose' / EIP' / wallet'` path. -- [EIP-5568](./eip-5568.md) specifies `The instruction_id of an instruction defined by an EIP MUST be its EIP number unless there are exceptional circumstances (be reasonable)` -- [EIP-6120](./eip-6120.md) specifies `struct Token { uint eip; ..., }` where `uint eip` is an EIP number to identify EIPs. -- `EIP-867`(Stagnant) proposes to create `erpId: A string identifier for this ERP (likely the associated EIP number, e.g. “EIP-1234”).` - -3. Having an ERC/EIP number detection interface reduces the need for a lookup table in smart contract to -convert a function method or whole interface in any EIP/ERC in the bytes4 EIP-165 identifier into its respective EIP number and massively simplifies the way to specify EIP for behavior expansion. - -4. We also recognize a smart contract might have different behavior given different caller accounts. One of the most notable use cases is that when using Transparent Upgradable Pattern, a proxy contract gives an Admin account and Non-Admin account different treatment when they call. - -## Specification - -In the following description, we use EIP and ERC inter-exchangeably. This was because while most of the time the description applies to an ERC category of the Standards Track of EIP, the ERC number space is a subspace of EIP number space and we might sometimes encounter EIPs that aren't recognized as ERCs but has behavior that's worthy of a query. - -1. Any compliant smart contract MUST implement the following interface - -```solidity -// DRAFTv1 -pragma solidity ^0.8.9; - -interface IERC5269 { - event OnSupportEIP( - address indexed caller, // when emitted with `address(0x0)` means all callers. - uint256 indexed majorEIPIdentifier, - bytes32 indexed minorEIPIdentifier, // 0 means the entire EIP - bytes32 eipStatus, - bytes extraData - ); - - /// @dev The core method of EIP/ERC Interface Detection - /// @param caller, a `address` value of the address of a caller being queried whether the given EIP is supported. - /// @param majorEIPIdentifier, a `uint256` value and SHOULD BE the EIP number being queried. Unless superseded by future EIP, such EIP number SHOULD BE less or equal to (0, 2^32-1]. For a function call to `supportEIP`, any value outside of this range is deemed unspecified and open to implementation's choice or for future EIPs to specify. - /// @param minorEIPIdentifier, a `bytes32` value reserved for authors of individual EIP to specify. For example the author of [EIP-721](/EIPS/eip-721) MAY specify `keccak256("ERC721Metadata")` or `keccak256("ERC721Metadata.tokenURI")` as `minorEIPIdentifier` to be quired for support. Author could also use this minorEIPIdentifier to specify different versions, such as EIP-712 has its V1-V4 with different behavior. - /// @param extraData, a `bytes` for [EIP-5750](/EIPS/eip-5750) for future extensions. - /// @return eipStatus, a `bytes32` indicating the status of EIP the contract supports. - /// - For FINAL EIPs, it MUST return `keccak256("FINAL")`. - /// - For non-FINAL EIPs, it SHOULD return `keccak256("DRAFT")`. - /// During EIP procedure, EIP authors are allowed to specify their own - /// eipStatus other than `FINAL` or `DRAFT` at their discretion such as `keccak256("DRAFTv1")` - /// or `keccak256("DRAFT-option1")`and such value of eipStatus MUST be documented in the EIP body - function supportEIP( - address caller, - uint256 majorEIPIdentifier, - bytes32 minorEIPIdentifier, - bytes calldata extraData) - external view returns (bytes32 eipStatus); -} -``` - -In the following description, `EIP_5269_STATUS` is set to be `keccak256("DRAFTv1")`. - -In addition to the behavior specified in the comments of `IERC5269`: - -1. Any `minorEIPIdentifier=0` is reserved to be referring to the main behavior of the EIP being queried. -2. The Author of compliant EIP is RECOMMENDED to declare a list of `minorEIPIdentifier` for their optional interfaces, behaviors and value range for future extension. -3. When this EIP is FINAL, any compliant contract MUST return an `EIP_5269_STATUS` for the call of `supportEIP((any caller), 5269, 0, [])` - -*Note*: at the current snapshot, the `supportEIP((any caller), 5269, 0, [])` MUST return `EIP_5269_STATUS`. - -4. Any complying contract SHOULD emit an `OnSupportEIP(address(0), 5269, 0, EIP_5269_STATUS, [])` event upon construction or upgrade. -5. Any complying contract MAY declare for easy discovery any EIP main behavior or sub-behaviors by emitting an event of `OnSupportEIP` with relevant values and when the compliant contract changes whether the support an EIP or certain behavior for a certain caller or all callers. -6. For any `EIP-XXX` that is NOT in `Final` status, when querying the `supportEIP((any caller), xxx, (any minor identifier), [])`, it MUST NOT return `keccak256("FINAL")`. It is RECOMMENDED to return `0` in this case but other values of `eipStatus` is allowed. Caller MUST treat any returned value other than `keccak256("FINAL")` as non-final, and MUST treat 0 as strictly "not supported". -7. The function `supportEIP` MUST be mutability `view`, i.e. it MUST NOT mutate any global state of EVM. - -## Rationale - -1. When data type `uint256 majorEIPIdentifier`, there are other alternative options such as: - -- (1) using a hashed version of the EIP number, -- (2) use a raw number, or -- (3) use an EIP-165 identifier. - -The pros for (1) are that it automatically supports any evolvement of future EIP numbering/naming conventions. -But the cons are it's not backward readable: seeing a `hash(EIP-number)` one usually can't easily guess what their EIP number is. - -We choose the (2) in the rationale laid out in motivation. - -2. We have a `bytes32 minorEIPIdentifier` in our design decision. Alternatively, it could be (1) a number, forcing all EIP authors to define its numbering for sub-behaviors so we go with a `bytes32` and ask the EIP authors to use a hash for a string name for their sub-behaviors which they are already doing by coming up with interface name or method name in their specification. - -3. Alternatively, it's possible we add extra data as a return value or an array of all EIP being supported but we are unsure how much value this complexity brings and whether the extra overhead is justified. - -4. Compared to [EIP-165](./eip-165.md), we also add an additional input of `address caller`, given the increasing popularity of proxy patterns such as those enabled by [EIP-1967](./eip-1967.md). One may ask: why not simply use `msg.sender`? This is because we want to allow query them without transaction or a proxy contract to query whether interface ERC-`number` will be available to that particular sender. - -1. We reserve the input `majorEIPIdentifier` greater than or equals `2^32` in case we need to support other collections of standards which is not an ERC/EIP. - -## Test Cases - -```typescript - -describe("ERC5269", function () { - async function deployFixture() { - // ... - } - - describe("Deployment", function () { - // ... - it("Should emit proper OnSupportEIP events", async function () { - let { txDeployErc721 } = await loadFixture(deployFixture); - let events = txDeployErc721.events?.filter(event => event.event === 'OnSupportEIP'); - expect(events).to.have.lengthOf(4); - - let ev5269 = events!.filter( - (event) => event.args!.majorEIPIdentifier.eq(5269)); - expect(ev5269).to.have.lengthOf(1); - expect(ev5269[0].args!.caller).to.equal(BigNumber.from(0)); - expect(ev5269[0].args!.minorEIPIdentifier).to.equal(BigNumber.from(0)); - expect(ev5269[0].args!.eipStatus).to.equal(ethers.utils.id("DRAFTv1")); - - let ev721 = events!.filter( - (event) => event.args!.majorEIPIdentifier.eq(721)); - expect(ev721).to.have.lengthOf(3); - expect(ev721[0].args!.caller).to.equal(BigNumber.from(0)); - expect(ev721[0].args!.minorEIPIdentifier).to.equal(BigNumber.from(0)); - expect(ev721[0].args!.eipStatus).to.equal(ethers.utils.id("FINAL")); - - expect(ev721[1].args!.caller).to.equal(BigNumber.from(0)); - expect(ev721[1].args!.minorEIPIdentifier).to.equal(ethers.utils.id("ERC721Metadata")); - expect(ev721[1].args!.eipStatus).to.equal(ethers.utils.id("FINAL")); - - // ... - }); - - it("Should return proper eipStatus value when called supportEIP() for declared supported EIP/features", async function () { - let { erc721ForTesting, owner } = await loadFixture(deployFixture); - expect(await erc721ForTesting.supportEIP(owner.address, 5269, ethers.utils.hexZeroPad("0x00", 32), [])).to.equal(ethers.utils.id("DRAFTv1")); - expect(await erc721ForTesting.supportEIP(owner.address, 721, ethers.utils.hexZeroPad("0x00", 32), [])).to.equal(ethers.utils.id("FINAL")); - expect(await erc721ForTesting.supportEIP(owner.address, 721, ethers.utils.id("ERC721Metadata"), [])).to.equal(ethers.utils.id("FINAL")); - // ... - - expect(await erc721ForTesting.supportEIP(owner.address, 721, ethers.utils.id("WRONG FEATURE"), [])).to.equal(BigNumber.from(0)); - expect(await erc721ForTesting.supportEIP(owner.address, 9999, ethers.utils.hexZeroPad("0x00", 32), [])).to.equal(BigNumber.from(0)); - }); - - it("Should return zero as eipStatus value when called supportEIP() for non declared EIP/features", async function () { - let { erc721ForTesting, owner } = await loadFixture(deployFixture); - expect(await erc721ForTesting.supportEIP(owner.address, 721, ethers.utils.id("WRONG FEATURE"), [])).to.equal(BigNumber.from(0)); - expect(await erc721ForTesting.supportEIP(owner.address, 9999, ethers.utils.hexZeroPad("0x00", 32), [])).to.equal(BigNumber.from(0)); - }); - }); -}); -``` - -See [`TestERC5269.ts`](../assets/eip-5269/test/TestERC5269.ts). - -## Reference Implementation - -Here is a reference implementation for this EIP: - -```solidity -contract ERC5269 is IERC5269 { - bytes32 constant public EIP_STATUS = keccak256("DRAFTv1"); - constructor () { - emit OnSupportEIP(address(0x0), 5269, bytes32(0), EIP_STATUS, ""); - } - - function _supportEIP( - address /*caller*/, - uint256 majorEIPIdentifier, - bytes32 minorEIPIdentifier, - bytes calldata /*extraData*/) - internal virtual view returns (bytes32 eipStatus) { - if (majorEIPIdentifier == 5269) { - if (minorEIPIdentifier == bytes32(0)) { - return EIP_STATUS; - } - } - return bytes32(0); - } - - function supportEIP( - address caller, - uint256 majorEIPIdentifier, - bytes32 minorEIPIdentifier, - bytes calldata extraData) - external virtual view returns (bytes32 eipStatus) { - return _supportEIP(caller, majorEIPIdentifier, minorEIPIdentifier, extraData); - } -} -``` - -See [`ERC5269.sol`](../assets/eip-5269/contracts/ERC5269.sol). - -Here is an example where a contract of [EIP-721](./eip-721.md) also implement this EIP to make it easier -to detect and discover: - -```solidity -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "../ERC5269.sol"; -contract ERC721ForTesting is ERC721, ERC5269 { - - bytes32 constant public EIP_FINAL = keccak256("FINAL"); - constructor() ERC721("ERC721ForTesting", "E721FT") ERC5269() { - _mint(msg.sender, 0); - emit OnSupportEIP(address(0x0), 721, bytes32(0), EIP_FINAL, ""); - emit OnSupportEIP(address(0x0), 721, keccak256("ERC721Metadata"), EIP_FINAL, ""); - emit OnSupportEIP(address(0x0), 721, keccak256("ERC721Enumerable"), EIP_FINAL, ""); - } - - function supportEIP( - address caller, - uint256 majorEIPIdentifier, - bytes32 minorEIPIdentifier, - bytes calldata extraData) - external - override - view - returns (bytes32 eipStatus) { - if (majorEIPIdentifier == 721) { - if (minorEIPIdentifier == 0) { - return keccak256("FINAL"); - } else if (minorEIPIdentifier == keccak256("ERC721Metadata")) { - return keccak256("FINAL"); - } else if (minorEIPIdentifier == keccak256("ERC721Enumerable")) { - return keccak256("FINAL"); - } - } - return super._supportEIP(caller, majorEIPIdentifier, minorEIPIdentifier, extraData); - } -} - -``` - -See [`ERC721ForTesting.sol`](../assets/eip-5269/contracts/testing/ERC721ForTesting.sol). - -## Security Considerations - -Similar to [EIP-165](./eip-165.md) callers of the interface MUST assume the smart contract -declaring they support such EIP interfaces doesn't necessarily correctly support them. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5269.md diff --git a/EIPS/eip-5283.md b/EIPS/eip-5283.md index 867be6676e0470..d8c5a14dbcb5da 100644 --- a/EIPS/eip-5283.md +++ b/EIPS/eip-5283.md @@ -4,7 +4,7 @@ title: Semaphore for Reentrancy Protection description: A Precompile-based parallelizable reentrancy protection using the call stack author: Sergio D. Lerner (@SergioDemianLerner) discussions-to: https://ethereum-magicians.org/t/eip-5283-a-semaphore-for-parallelizable-reentrancy-protection/10236 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-07-17 @@ -59,9 +59,9 @@ abstract contract ReentrancyGuard2 { } ``` -### Parallellizable storage-based RPGs +### Parallelizable storage-based RPGs -The only way to paralellize prexistent contracts that are using the storage RPG construction is that the VM automatically detects that a storage variable is used for the RPG, and proves that is works as required. This requires static code analysys. This is difficult to implement in consensus for two reasons. First, the CPU cost of detection and/or proving may be high. Second, some contract functions may not be protected by the RPG, meaning that some execution paths do not alter the RPG, which may complicate proving. Therefore this proposal aims to protect future contracts and let them be parallelizable, rather than to paralellize already deployed ones. +The only way to parallelize preexistent contracts that are using the storage RPG construction is that the VM automatically detects that a storage variable is used for the RPG, and proves that it works as required. This requires static code analysis. This is difficult to implement in consensus for two reasons. First, the CPU cost of detection and/or proving may be high. Second, some contract functions may not be protected by the RPG, meaning that some execution paths do not alter the RPG, which may complicate proving. Therefore this proposal aims to protect future contracts and let them be parallelizable, rather than to parallelize already deployed ones. ### Alternatives diff --git a/EIPS/eip-5289.md b/EIPS/eip-5289.md index f4152db7e8ba2b..107a94c17e94f4 100644 --- a/EIPS/eip-5289.md +++ b/EIPS/eip-5289.md @@ -1,93 +1,7 @@ --- eip: 5289 -title: Ethereum Notary Interface -description: Allows Smart Contracts to be Legally Binding Off-Chain -author: Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/pr-5289-discussion-notary-interface/9980 -status: Review -type: Standards Track category: ERC -created: 2022-07-16 -requires: 165, 5568 +status: Moved --- -## Abstract - -Currently, the real-world applications of smart contracts are limited by the fact that they aren't legally binding. This EIP proposes a standard that allows smart contracts to be legally binding by providing IPFS links to legal documents and ensuring that the users of the smart contract have privity with the relevant legal documents. - -## Motivation - -NFTs have oftentimes been branded as a way to hold and prove copyright of a specific work. However, this, in practice, has almost never been the case. Most of the time, NFTs have no legally-binding meaning, and in the rare cases that do, the NFT simply provides a limited license for the initial holder to use the work (but cannot provide any license for any future holders). - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Legal Contract Library Interface - -```solidity -/// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "./IERC165.sol"; - -interface IERC5289Library is IERC165 { - /// @notice Emitted when signDocument is called - event DocumentSigned(address indexed signer, uint16 indexed documentId); - - /// @notice An immutable link to the legal document (RECOMMENDED to be hosted on IPFS). This MUST use a common file format, such as PDF, HTML, TeX, or Markdown. - function legalDocument(uint16 documentId) external view returns (string memory); - - /// @notice Returns whether or not the given user signed the document. - function documentSigned(address user, uint16 documentId) external view returns (bool signed); - - /// @notice Returns when the the given user signed the document. - /// @dev If the user has not signed the document, the timestamp may be anything. - function documentSignedAt(address user, uint16 documentId) external view returns (uint64 timestamp); - - /// @notice Sign a document - /// @dev This MUST be validated by the smart contract. This MUST emit DocumentSigned or throw. - function signDocument(address signer, uint16 documentId) external; -} -``` - -### Requesting a Signature - -To request that certain documents be signed, revert with an [EIP-5568](./eip-5568.md) signal. The format of the `instruction_data` is an ABI-encoded `(address, uint16)` pair, where the address is the address of the library, and the `uint16` is the `documentId` of the document: - -```solidity -throw WalletSignal24(0, 5289, abi.encode(0xcbd99eb81b2d8ca256bb6a5b0ef7db86489778a7, 12345)); -``` - -### Signing a Document - -When a signature is requested, wallets MUST call `legalDocument`, display the resulting document to the user, and prompt them to either sign the document or cancel: - -![image](../assets/eip-5289/example-popup.png) - -If the user agrees, the wallet MUST call `signDocument`. - -## Rationale - -- `uint64` was chosen for the timestamp return type as 64-bit time registers are standard. -- `uint16` was chosen for the document ID as 65536 documents are likely sufficient for any use case, and the contract can always be re-deployed. -- `signDocument` doesn't take an ECDSA signature for future compatibility with account abstraction. In addition, future extensions can supply this functionality. -- IPFS is mandatory because the authenticity of the signed document can be proven. - -## Backwards Compatibility - -No backwards compatibility issues found. - -## Reference Implementation - -### Legal Contract Library - -See [`IERC5289Library`](../assets/eip-5289/interfaces/IERC5289Library.sol), [`ERC5289Library`](../assets/eip-5289/ERC5289Library.sol). - -## Security Considerations - -Users can claim that their private key was stolen and used to fraudulently "sign" contracts. As such, **documents must only be permissive in nature, not restrictive.** For example, a document granting a license to use the image attached to an NFT would be acceptable, as there is no reason for the signer to plausibly deny signing the document. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5289.md diff --git a/EIPS/eip-5298.md b/EIPS/eip-5298.md index 5f885097c80ab4..7f515627047102 100644 --- a/EIPS/eip-5298.md +++ b/EIPS/eip-5298.md @@ -1,153 +1,7 @@ --- eip: 5298 -title: ENS Trust to hold NFTs under ENS name -description: An interface for a smart contract acting as a "trust" that holds tokens by ENS name. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-eip-5198-ens-as-token-holder/10374 -status: Review -type: Standards Track category: ERC -created: 2022-07-12 -requires: 137, 721, 1155 +status: Moved --- -## Abstract - -This EIP standardizes an interface for smart contracts to hold of [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) tokens on behalf of ENS domains. - -## Motivation - -Currently, if someone wants to receive a token, they have to set up a wallet address. This EIP decouples NFT ownership from wallet addresses. - -## Specification - -1. Compliant contracts MUST implement `ERC721TokenReceiver`, as defined in [EIP-721](./eip-721.md). -2. Compliant contracts implement the following interface: - -```solidity -interface IERC_ENS_TRUST is ERC721Receiver, ERC1155Receiver { - function claimTo(address to, bytes32 ensNode, address operator, uint256 tokenId) payable external; -} -``` - -3. `claimTo` MUST check if `msg.sender` is the owner of the ENS node identified by `bytes32 ensNode` (and/or approved by the domain in implementation-specific ways). The compliant contract then MUST make a call to the `safeTransferFrom` function of [EIP-721](./eip-712.md) or [EIP-1155](./eip-1155.md). - -4. Any `ensNode` is allowed. - -## Rationale - -1. ENS was chosen because it is a well-established scoped ownership namespace. -This is nonetheless compatible with other scoped ownership namespaces. - -2. We didn't expose getters or setters for ensRoot because it is outside of the scope of this EIP. - -## Backwards Compatibility - -No backward compatibility issues were found. - -## Test Cases - -```ts -import { loadFixture } from "@nomicfoundation/hardhat-network-helpers"; -import { expect } from "chai"; -import { ethers } from "hardhat"; - -describe("FirstENSBankAndTrust", function () { - - describe("Receive and Claim Token", function () { - - it("Should ACCEPT/REJECT claimTo based on if ENS owner is msg.sender", async function () { - ... - // Steps of testing: - // mint to charlie - // charlie send to ENSTrust and recorded under bob.xinbenlvethsf.eth - // bob try to claimTo alice, first time it should be rejected - // bob then set the ENS record - // bob claim to alice, second time it should be accepted - - // mint to charlie - await erc721ForTesting.mint(charlie.address, fakeTokenId); - - // charlie send to ENSTrust and recorded under bob.xinbenlvethsf.eth - await erc721ForTesting.connect(charlie)["safeTransferFrom(address,address,uint256,bytes)"]( - charlie.address, firstENSBankAndTrust.address, - fakeTokenId, - fakeReceiverENSNamehash - ); - - // bob try to claimTo alice, first time it should be rejected - await expect(firstENSBankAndTrust.connect(bob).claimTo( - alice.address, - fakeReceiverENSNamehash, - firstENSBankAndTrust.address, - fakeTokenId - )) - .to.be.rejectedWith("ENSTokenHolder: node not owned by sender"); - - // bob then set the ENS record - await ensForTesting.setOwner( - fakeReceiverENSNamehash, bob.address - ); - - // bob claim to alice, second time it should be accepted - await expect(firstENSBankAndTrust.connect(bob).claimTo( - alice.address, - fakeReceiverENSNamehash, - erc721ForTesting.address, - fakeTokenId - )); - }); - }); -}); -``` - -## Reference Implementation - -```solidity -pragma solidity ^0.8.9; - -contract FirstENSBankAndTrust is IERC721Receiver, Ownable { - function getENS() public view returns (ENS) { - return ENS(ensAddress); - } - - function setENS(address newENSAddress) public onlyOwner { - ensAddress = newENSAddress; - } - - // @dev This function is called by the owner of the token to approve the transfer of the token - // @param data MUST BE the ENS node of the intended token receiver this ENSHoldingServiceForNFT is holding on behalf of. - function onERC721Received( - address operator, - address /*from*/, - uint256 tokenId, - bytes calldata data - ) external override returns (bytes4) { - require(data.length == 32, "ENSTokenHolder: last data field must be ENS node."); - // --- START WARNING --- - // DO NOT USE THIS IN PROD - // this is just a demo purpose of using extraData for node information - // In prod, you should use a struct to store the data. struct should clearly identify the data is for ENS - // rather than anything else. - bytes32 ensNode = bytes32(data[0:32]); - // --- END OF WARNING --- - - addToHolding(ensNode, operator, tokenId); // conduct the book keeping - return ERC721_RECEIVER_MAGICWORD; - } - - function claimTo(address to, bytes32 ensNode, address tokenContract uint256 tokenId) public { - require(getENS().owner(ensNode) == msg.sender, "ENSTokenHolder: node not owned by sender"); - removeFromHolding(ensNode, tokenContract, tokenId); - IERC721(tokenContract).safeTransferFrom(address(this), to, tokenId); - } -} -``` - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5298.md diff --git a/EIPS/eip-5313.md b/EIPS/eip-5313.md index 7c7e53f0cfe77f..e6756e76569dfb 100644 --- a/EIPS/eip-5313.md +++ b/EIPS/eip-5313.md @@ -1,61 +1,7 @@ --- eip: 5313 -title: Light Contract Ownership -description: An interface for identifying ownership of contracts -author: William Entriken (@fulldecent) -discussions-to: https://ethereum-magicians.org/t/eip-5313-light-contract-ownership/10052 -status: Final -type: Standards Track category: ERC -created: 2022-07-22 -requires: 165, 173 +status: Moved --- -## Abstract - -This specification defines the minimum interface required to identify an account that controls a contract. - -## Motivation - -This is a slimmed-down alternative to [EIP-173](./eip-173.md). - -## Specification - -The key word “MUST” in this document is to be interpreted as described in RFC 2119. - -Every contract compliant with this EIP MUST implement the `EIP5313` interface. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.15; - -/// @title EIP-5313 Light Contract Ownership Standard -interface EIP5313 { - /// @notice Get the address of the owner - /// @return The address of the owner - function owner() view external returns(address); -} -``` - -## Rationale - -Key factors influencing the standard: - -- Minimize the number of functions in the interface -- Backwards compatibility with existing contracts - -This standard can be (and has been) extended by other standards to add additional ownership functionality. The smaller scope of this specification allows more and more straightforward ownership implementations, see limitations explained in EIP-173 under "other schemes that were considered". - -Implementing [EIP-165](./eip-165.md) could be a valuable addition to this interface specification. However, this EIP is being written to codify existing protocols that connect contracts (often NFTs), with third-party websites (often a well-known NFT marketplace). - -## Backwards Compatibility - -Every contract that implements EIP-173 already implements this specification. - -## Security Considerations - -Because this specification does not extend EIP-165, calling this EIP's `owner` function cannot result in complete certainty that the result is indeed the owner. For example, another function with the same function signature may return some value that is then interpreted to be the true owner. If this EIP is used solely to identify if an account is the owner of a contract, then the impact of this risk is minimized. But if the interrogator is, for example, sending a valuable NFT to the identified owner of any contract on the network, then the risk is heightened. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5313.md diff --git a/EIPS/eip-5334.md b/EIPS/eip-5334.md index e0c213975a2408..a87552359aa2c8 100644 --- a/EIPS/eip-5334.md +++ b/EIPS/eip-5334.md @@ -1,115 +1,7 @@ --- eip: 5334 -title: EIP-721 User And Expires And Level Extension -description: Add a time-limited role with restricted permissions to EIP-721 tokens. -author: Yan (@yan253319066) -discussions-to: https://ethereum-magicians.org/t/erc-721-user-and-expires-and-level-extension/10097 -status: Draft -type: Standards Track category: ERC -created: 2022-07-25 -requires: 165, 721 +status: Moved --- -## Abstract - -An [EIP-721](./eip-721.md) extension that adds an additional role (`user`) which can be granted to addresses, and a time where the role is automatically revoked (`expires`) and (`level`) . The `user` role represents permission to "use" the NFT, but not the ability to transfer it or set users. - -## Motivation - -Some NFTs have certain utilities. For example, virtual land can be "used" to build scenes, and NFTs representing game assets can be "used" in-game. In some cases, the owner and user may not always be the same. There may be an owner of the NFT that rents it out to a “user”. The actions that a “user” should be able to take with an NFT would be different from the “owner” (for instance, “users” usually shouldn’t be able to sell ownership of the NFT).  In these situations, it makes sense to have separate roles that identify whether an address represents an “owner” or a “user” and manage permissions to perform actions accordingly. - -Some projects already use this design scheme under different names such as “operator” or “controller” but as it becomes more and more prevalent, we need a unified standard to facilitate collaboration amongst all applications. - -Furthermore, applications of this model (such as renting) often demand that user addresses have only temporary access to using the NFT. Normally, this means the owner needs to submit two on-chain transactions, one to list a new address as the new user role at the start of the duration and one to reclaim the user role at the end. This is inefficient in both labor and gas and so an “expires” and “level” function is introduced that would facilitate the automatic end of a usage term without the need of a second transaction. - -Here are some of the problems that are solved by this standard: - -### Clear Rights Assignment - -With Dual “owner” and “user” roles, it becomes significantly easier to manage what lenders and borrowers can and cannot do with the NFT (in other words, their rights). Additionally, owners can control who the user is and it’s easy for other projects to assign their own rights to either the owners or the users. - -### Simple On-chain Time Management - -Once a rental period is over, the user role needs to be reset and the “user” has to lose access to the right to use the NFT. This is usually accomplished with a second on-chain transaction but that is gas inefficient and can lead to complications because it’s imprecise. With the `expires` function, there is no need for another transaction because the “user” is invalidated automatically after the duration is over. - -### Easy Third-Party Integration - -In the spirit of permission less interoperability, this standard makes it easier for third-party protocols to manage NFT usage rights without permission from the NFT issuer or the NFT application. Once a project has adopted the additional `user` role and `expires` and `level`, any other project can directly interact with these features and implement their own type of transaction. For example, a PFP NFT using this standard can be integrated into both a rental platform where users can rent the NFT for 30 days AND, at the same time, a mortgage platform where users can use the NFT while eventually buying ownership of the NFT with installment payments. This would all be done without needing the permission of the original PFP project. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Contract Interface -Solidity Interface with NatSpec & OpenZeppelin v4 Interfaces (also available at [`IERC5334.sol`](../assets/eip-5334/IERC5334.sol)): - -```solidity -interface IERC5334 { - - // Logged when the user of a NFT, expires, or level is changed - /// @notice Emitted when the `user` of an NFT or the `expires` of the `user` is changed or the user `level` is changed - /// The zero address for user indicates that there is no user address - event UpdateUser(uint256 indexed tokenId, address indexed user, uint64 expires, uint8 level); - - /// @notice set the user and expires and level of a NFT - /// @dev The zero address indicates there is no user - /// Throws if `tokenId` is not valid NFT - /// @param user The new user of the NFT - /// @param expires UNIX timestamp, The new user could use the NFT before expires - /// @param level user level - function setUser(uint256 tokenId, address user, uint64 expires, uint8 level) external; - - /// @notice Get the user address of an NFT - /// @dev The zero address indicates that there is no user or the user is expired - /// @param tokenId The NFT to get the user address for - /// @return The user address for this NFT - function userOf(uint256 tokenId) external view returns(address); - - /// @notice Get the user expires of an NFT - /// @dev The zero value indicates that there is no user - /// @param tokenId The NFT to get the user expires for - /// @return The user expires for this NFT - function userExpires(uint256 tokenId) external view returns(uint256); - - /// @notice Get the user level of an NFT - /// @dev The zero value indicates that there is no user - /// @param tokenId The NFT to get the user level for - /// @return The user level for this NFT - function userLevel(uint256 tokenId) external view returns(uint256); -} -``` - -The `userOf(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `userExpires(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `userLevel(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `setUser(uint256 tokenId, address user, uint64 expires)` function MAY be implemented as `public` or `external`. - -The `UpdateUser` event MUST be emitted when a user address is changed or the user expires is changed or the user level is changed. - - - -## Rationale - -TBD - -## Backwards Compatibility - -As mentioned in the specifications section, this standard can be fully EIP-721 compatible by adding an extension function set. - -In addition, new functions introduced in this standard have many similarities with the existing functions in EIP-721. This allows developers to easily adopt the standard quickly. - -## Reference Implementation -A reference implementation of this standard can be found in the assets folder. - - -## Security Considerations - -This EIP standard can completely protect the rights of the owner, the owner can change the NFT user and expires and level at any time. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5334.md diff --git a/EIPS/eip-5345.md b/EIPS/eip-5345.md index 8a9c6ff246d66c..68bc9fffeb1f63 100644 --- a/EIPS/eip-5345.md +++ b/EIPS/eip-5345.md @@ -4,7 +4,7 @@ title: Silent Signing Extension for JSON-RPC description: Temporary transaction signing without user interaction author: Stanley Wu (@fruit37), Mücahit Büyükyılmaz (@anndro), Muhammed Emin Aydın (@muhammedea) discussions-to: https://ethereum-magicians.org/t/walletconnect-silent-signing-extension/10137 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2022-07-26 diff --git a/EIPS/eip-5375.md b/EIPS/eip-5375.md index 3eaa5516c7ee1f..75cedb8e50b7f6 100644 --- a/EIPS/eip-5375.md +++ b/EIPS/eip-5375.md @@ -1,304 +1,7 @@ --- eip: 5375 -title: NFT Author Information and Consent -description: An extension of EIP-721 for NFT authorship and author consent. -author: Samuele Marro (@samuelemarro), Luca Donno (@lucadonnoh) -discussions-to: https://ethereum-magicians.org/t/eip-5375-nft-authorship/10182 -status: Final -type: Standards Track category: ERC -created: 2022-07-30 -requires: 55, 155, 712, 721, 1155 +status: Moved --- -## Abstract - -This EIP standardizes a JSON format for storing off-chain information about NFT authors. Specifically, it adds a new field which provides a list of author names, addresses, and proofs of _authorship consent_: proofs that the authors have agreed to be named as authors. Note that a proof of authorship _consent_ is not a proof of authorship: an address can consent without having authored the NFT. - -## Motivation - -There is currently no standard to identify authors of an NFT, and existing techniques have issues: - -- Using the mint `tx.origin` or `msg.sender` - - Assumes that the minter and the author are the same - - Does not support multiple authors -- Using the first Transfer event for a given ID - - Contract/minter can claim that someone else is the author without their consent - - Does not support multiple authors -- Using a custom method/custom JSON field - - Requires per-contract support by NFT platforms - - Contract/minter can claim that someone else is the author without their consent - -The first practice is the most common. However, there are several situations where the minter and the author might not be the same, such as: - -- NFTs minted by a contract -- Lazy minting -- NFTs minted by an intermediary (which can be particularly useful when the author is not tech-savvy and/or the minting process is convoluted) - -This document thus defines a standard which allows the minter to provide authorship information, while also preventing authorship claims without the author's consent. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -All addresses used in this standard MUST follow the casing rules described in [EIP-55](./eip-55.md). - -### Definitions - -- **Authors**: creators of an NFT -- **Minter**: entity responsible for the actual minting transaction; the minter and the authors MAY be the same -- **Verifier**: entity that wants to verify the authorship of an NFT (e.g. a user or an NFT marketplace) -- **Author Consent Proof (ACP)**: a signed message that proves that the signer agrees to be considered the author of the NFT - -### Authorship Support - -The standard introduces a new JSON field, named `authorInfo`. It provides a REQUIRED interface for authorship claiming, as well as an OPTIONAL interface for author consent proofs. - -`authorInfo` is a top-level field of the NFT metadata. Specifically: - -- If a contract supports the metadata extension for [EIP-721](./eip-721.md), the JSON document pointed by `tokenURI(uint256 _tokenId)` MUST include the top-level field `authorInfo` -- If a contract supports the metadata extension for [EIP-1155](./eip-1155.md), the JSON document pointed by `uri(uint256 _id)` MUST include a top-level field `authorInfo` - -The JSON schema of `authorInfo` (named `ERC5375AuthorInfoSchema`) is defined as follows: - -```json -{ - "type": "object", - "properties": { - "consentInfo": { - "type": "object", - "description": "Helper fields for consent verification", - "properties": { - "chainId": { - "type": "integer", - "description": "EIP-155 chain id" - }, - "id": { - "type": "string", - "description": "NFT id" - }, - "contractAddress": { - "type": "string", - "description": "0x-prefixed address of the smart contract" - } - } - }, - "authors": { - "type": "array", - "items": "ERC5375AuthorSchema" - } - }, - "required": [ "authors" ] -} -``` - -Note that `authors` MAY be an empty array. - -`ERC5375AuthorSchema` is defined as follows: - -```json -{ - "type": "object", - "properties": { - "address": { - "type": "string", - "description": "0x-prefixed address of the author" - }, - "consent": { - "type": "ERC5375AuthorConsentSchema", - "description": "Author consent information" - } - }, - "required": [ "address" ] -} -``` - -Moreover, if the `consent` field is present, the `consentInfo` field of `authorInfo` MUST be present. - -`ERC5375AuthorConsentSchema` is defined as follows: - -```json -{ - "type": "object", - "properties": { - "consentData": { - "type": "object", - "properties": { - "version": { - "type": "string", - "description": "NFT authorship consent schema version" - }, - "issuer": { - "type": "string", - "description": "0x-prefixed address of the author" - }, - "metadataFields": { - "type": "object" - } - }, - "required": ["version", "issuer", "metadataFields"] - }, - "publicKey": { - "type": "string", - "description": "EVM public key of the author" - }, - "signature": { - "type": "string", - "description": "EIP-712 signature of the consent message" - } - }, - "required": ["consentData", "publicKey", "signature"] -} -``` - -where `metadataFields` is an object containing the JSON top-level fields (excluding `authorInfo`) that the author will certify. Note that the keys of `metadataFields` MAY be a (potentially empty) subset of the set of fields. - -`consentData` MAY support additional fields as defined by other EIPs. `consentData` MUST contain all the information (which is not already present in other fields) required to verify the validity of an authorship consent proof. - -### Author Consent - -Consent is obtained by signing an [EIP-712](./eip-712.md) compatible message. Specifically, the structure is defined as follows: - -```solidity -struct Author { - address subject; - uint256 tokenId; - string metadata; -} -``` - -where `subject` is the address of the NFT contract, `tokenId` is the id of the NFT and `metadata` is the JSON encoding of the fields listed in `metadataFields`. `metadata`: - -- MUST contain exactly the same fields as the ones listed in `metadataFields`, in the same order -- MUST escape all non-ASCII characters. If the escaped character contains hexadecimal letters, they MUST be uppercase -- MUST not contain any whitespace that is not part of a field name or value - -For example, if the top-level JSON fields are: - -```json -{ - "name": "The Holy Hand Grenade of Antioch", - "description": "Throw in the general direction of your favorite rabbit, et voilà", - "damage": 500, - "authors": [...], - ... -} -``` - -and the content of `metadataFields` is `["name", "description"]`, the content of `metadata` is: - -```json -{ - "name": "The Holy Hand Grenade of Antioch", - "description": "Throw in the general direction of your favorite rabbit, et voil\u00E0" -} -``` - -Similarly to `consentData`, this structure MAY support additional fields as defined by other EIPs. - -The domain separator structure is - -```solidity -struct EIP712Domain { - string name; - string version; - uint256 chainId; -} -``` - -where `name` and `version` are the same fields described in `consentData` - -This structure MAY support additional fields as defined by other EIPs. - -### Author Consent Verification - -Verification is performed using EIP-712 on an author-by-author basis. Specifically, given a JSON document D1, a consent proof is valid if all of the following statements are true: - -- D1 has a top-level `authorInfo` field that matches `ERC5375AuthorInfoSchema` -- `consent` exists and matches `ERC5375AuthorConsentSchema`; -- If calling `tokenURI` (for EIP-721) or `uri` (for EIP-1155) returns the URI of a JSON document D2, all the top-level fields listed in `metadataFields` MUST exist and have the same value; -- The EIP-712 signature in `signature` (computed using the fields specified in the JSON document) is valid; - -Verifiers MUST NOT assume that an NFT with a valid consent proof from address X means that X is the actual author. On the other hand, verifiers MAY assume that if an NFT does not provide a valid consent proof for address X, then X is not the actual author. - -## Rationale - -### Why provide only an author consent proof? - -Adding support for full authorship proofs (i.e. Alice is the author and no one else is the author) requires a protocol to prove that someone is the only author of an NFT. -In other words, we need to answer the question: "Given an NFT Y and a user X claiming to be the author, is X the original author of Y?". - -For the sake of the argument, assume that there exists a protocol that, given an NFT Y, can determine the original author of Y. Even if such method existed, an attacker could slightly modify Y, thus obtaining a new NFT Y', and rightfully claim to be the author of Y', despite the fact that it is not an original work. Real-world examples include changing some pixels of an image or replacing some words of a text with synonyms. -Preventing this behavior would require a general formal definition of when two NFTs are semantically equivalent. Even if defining such a concept were possible, it would still be beyond the scope of this EIP. - -Note that this issue is also present when using the minter's address as a proxy for the author. - -### Why off-chain? - -There are three reasons: - -- Adding off-chain support does not require modifications to existing smart contracts; -- Off-chain storage is usually much cheaper than on-chain storage, thus reducing the implementation barrier; -- While there may be some use cases for full on-chain authorship proofs (e.g. a marketplace providing special features for authors), there are limited applications for on-chain author consent, due to the fact that it is mostly used by users to determine the subjective value of an NFT. - -### Why repeat id, chainId and contractAddress? - -In many cases, this data can be derived from contextual information. However, requiring their inclusion in the JSON document ensures that author consent can be verified using only the JSON document. - -### Why not implement a revocation system? - -Authorship is usually final: either someone created an NFT or they didn't. Moreover, a revocation system would impose additional implementation requirements on smart contracts and increase the complexity of verification. Smart contracts MAY implement a revocation system, such as the one defined in other EIPs. - -#### Why escape non-ASCII characters in the signature message? - -EIP-712 is designed with the possibility of on-chain verification in mind; while on-chain verification is not a priority for this EIP, non-ASCII characters are escaped due to the high complexity of dealing with non-ASCII strings in smart contracts. - -### Usability Improvements for Authors - -Since the author only needs to sign an EIP-712 message, this protocol allows minters to handle the technical aspects of minting while still preserving the secrecy of the author's wallet. Specifically, the author only needs to: - -- Obtain an EVM wallet; -- Learn how to read and sign a EIP-712 message (which can often be simplified by using a Dapp) - -without needing to: - -- Obtain the chain's native token (e.g. through trading or bridging); -- Sign a transaction; -- Understand the pricing mechanism of transactions; -- Verify if a transaction has been included in a block - -This reduces the technical barrier for authors, thus increasing the usability of NFTs, without requiring authors to hand over their keys to a tech-savvy intermediary. - -### Limitations of Address-Based Consent - -The standard defines a protocol to verify that a certain _address_ provided consent. However, it does not guarantee that the address corresponds to the expected author (such as the one provided in the `name` field). Proving a link between an address and the entity behind it is beyond the scope of this document. - -## Backwards Compatibility - -No backward compatibility issues were found. - -## Security Considerations - -### Attacks - -A potential attack that exploits this EIP involves tricking authors into signing authorship consent messages against their wishes. For this reason, authors MUST verify that all signature fields match the required ones. - -A more subtle approach involves not adding important fields to `metadataFields`. By doing so, the author signature might be valid even if the minter changes critical information. - -### Deprecated Features - -`ERC5375AuthorInfoSchema` also originally included a field to specify a human-readable name for the author (without any kind of verification). This was scrapped due to the high risk of author spoofing, i.e.: - -- Alice mints an NFT using Bob's name and Alice's address -- Charlie does not check the address and instead relies on the provided name -- Charlie buys Alice's NFT while believing that it was created by Bob - -For this reason, smart contract developers SHOULD NOT add support for unverifiable information to the JSON document. We believe that the most secure way to provide complex authorship information (e.g. the name of the author) is to prove that the information is associated with the _author's address_, instead of with the NFT itself. - -### Replay Attack Resistance - -The chain id, the contract address and the token id uniquely identify an NFT; for this reason, there is no need to implement additional replay attack countermeasures (e.g. a nonce system). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5375.md diff --git a/EIPS/eip-5380.md b/EIPS/eip-5380.md index 1da37a40cf1650..0802cb770cf3f4 100644 --- a/EIPS/eip-5380.md +++ b/EIPS/eip-5380.md @@ -1,92 +1,7 @@ --- eip: 5380 -title: EIP-721 Entitlement Extension -description: Allows token owners to grant the ability for others to use specific properties of those tokens -author: Pandapip1 (@Pandapip1), Tim Daubenschütz (@TimDaub) -discussions-to: https://ethereum-magicians.org/t/pr-5380-eip-4907-alternative-design/10190 -status: Review -type: Standards Track category: ERC -created: 2022-03-11 -requires: 165, 721 +status: Moved --- -## Abstract - -This EIP proposes a new interface that allows [EIP-721](./eip-721.md) token owners to grant limited usage of those tokens to other addresses. - -## Motivation - -There are many scenarios in which it makes sense for the owner of a token to grant certain properties to another address. One use case is renting tokens. If the token in question represents a trading card in an on-chain TCG (trading card game), one might want to be able to use that card in the game without having to actually buy it. Therefore, the owner might grant the renter the "property" of it being able to be played in the TCG. However, this property should only be able to be assigned to one person at a time, otherwise a contract could simply "rent" the card to everybody. If the token represents usage rights instead, the property of being allowed to use the associated media does not need such a restriction, and there is no reason that the property should be as scarce as the token. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Base - -```solidity -/// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface ERC721Entitlement is ERC165 { - /// @notice Emitted when the amount of entitlement a user has changes. If user is the zero address, then the user is the owner - event EntitlementChanged(address indexed user, address indexed contract, uint256 indexed tokenId); - - /// @notice Set the user associated with the given EIP-721 token as long as the owner is msg.sender. - /// @dev SHOULD NOT revert if the owner is not msg.sender. - /// @param user The user to grant the entitlement to - /// @param contract The property to grant - /// @param tokenId The tokenId to grant the properties of - function entitle(address user, address contract, uint256 tokenId) external; - - /// @notice Get the maximum number of users that can receive this entitlement - /// @param contract The contract to query - /// @param tokenId The tokenId to query - function maxEntitlements(address contract, uint256 tokenId) external view (uint256 max); - - /// @notice Get the user associated with the given contract and tokenId. - /// @dev Defaults to maxEntitlements(contract, tokenId) assigned to contract.ownerOf(tokenId) - /// @param user The user to query - /// @param contract The contract to query - /// @param tokenId The tokenId to query - function entitlementOf(address user, address contract, uint256 tokenId) external view returns (uint256 amt); -} -``` - -`supportsInterface` MUST return true when called with `ERC721Entitlement`'s interface ID. - -### Enumerable - -This OPTIONAL interface is RECOMMENDED. - -```solidity -/// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface ERC721EntitlementEnumerable is ERC721Entitlement /* , ERC165 */ { - /// @notice Enumerate tokens with nonzero entitlement assigned to a user - /// @dev Throws if the index is out of bounds or if user == address(0) - /// @param user The user to query - /// @param index A counter - function entitlementOfUserByIndex(address user, uint256 index) external view returns (address contract, uint256 tokenId); -} -``` - -`supportsInterface` MUST return true when called with `ERC721EntitlementEnumerable`'s interface ID. - -## Rationale - -[EIP-20](./eip-20.md) and [EIP-1155](./eip-1155.md) are unsupported as partial ownership is much more complex to track than boolean ownership. - -## Backwards Compatibility - -No backward compatibility issues were found. - -## Security Considerations - -The security considerations of [EIP-721](./eip-721.md) apply. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5380.md diff --git a/EIPS/eip-5409.md b/EIPS/eip-5409.md index c27a6b7a891e93..b26426d298c975 100644 --- a/EIPS/eip-5409.md +++ b/EIPS/eip-5409.md @@ -1,61 +1,7 @@ --- eip: 5409 -title: EIP-1155 Non-Fungible Token extension -description: Allow EIP-1155 to represent Non-Fungible Tokens (tokens who have a unique owner) -author: Ronan Sandford (@wighawag) -discussions-to: https://ethereum-magicians.org/t/eip-5409-non-fungible-token-extension-for-eip-1155/10240 -status: Draft -type: Standards Track category: ERC -created: 2022-07-23 -requires: 165, 721, 1155 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-1155](./eip-1155.md). It proposes an additional function, `ownerOf`, which allows EIP-1155 tokens to support Non-Fungibility (unique owners). By implementing this extra function, EIP-1155 tokens can benefit from [EIP-721](./eip-721.md)'s core functionality without implementing the (less efficient) EIP-721 specification in the same contract. - -## Motivation - -Currently, EIP-1155 does not allow an external caller to detect whether a token is truly unique (can have only one owner) or fungible. This is because EIP-1155 do not expose a mechanism to detect whether a token will have its supply remain to be "1". Furthermore, it does not let an external caller retrieve the owner directly on-chain. - -The EIP-1155 specification does mention the use of split id to represent non-fungible tokens, but this requires a pre-established convention that is not part of the standard, and is not as simple as EIP-721's `ownerOf`. - -The ability to get the owner of a token enables novel use-cases, including the ability for the owner to associate data with it. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Contract Interface - -```solidity -interface IERC1155OwnerOf { - - /// @notice Find the owner of an NFT - /// @dev The zero address indicates that there is no owner: either the token does not exist or it is not an NFT (supply potentially bigger than 1) - /// @param tokenId The identifier for an NFT - /// @return The address of the owner of the NFT - function ownerOf(uint256 tokenId) external view returns (address); -} -``` - -The `ownerOf(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `supportsInterface` method MUST return `true` when called with `0x6352211e`. - -## Rationale - -`ownerOf` does not throw when a token does not exist (or does not have an owner). This simplifies the handling of such a case. Since it would be a security risk to assume all EIP-721 implementation would throw, it should not break compatibility with contract handling EIP-721 when dealing with this EIP-1155 extension. - -## Backwards Compatibility - -This EIP is fully backward compatible with EIP-1155. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5409.md diff --git a/EIPS/eip-5437.md b/EIPS/eip-5437.md index 5d1058c94dfd9c..3b3f19a0d0f546 100644 --- a/EIPS/eip-5437.md +++ b/EIPS/eip-5437.md @@ -1,154 +1,7 @@ --- eip: 5437 -title: Security Contact Interface -description: An interface for security notice using asymmetric encryption -author: Zainan Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-interface-for-security-contract/10303 -status: Draft -type: Standards Track category: ERC -created: 2022-08-09 -requires: 165 +status: Moved --- -## Abstract -An interface for security notice using asymmetric encryption. The interface exposes a asymmetric encryption key and a destination of delivery. - -## Motivation -Currently there is no consistent way to specify an official channel for security researchers to report security issues to smart contract maintainers. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -interface IEIP5437 { - - /// REQUIRED - function getSecurityContact(uint8 type, bytes memory data) public view - returns ( - uint8 type, - bytes memory publicKey, - bytes memory extraData - ); - - /// OPTIONAL - // TODO consider remove if not needed before finalized - function setSecurityContact( - uint8 type, - bytes memory publicKey, - bytes memory extraData) public; - event SecurityContactChanged(uint8 type, bytes memory publicKeyForEncryption, bytes memory extraData); - - /// OPTIONAL - function securityNotify(uint8 type, bytes memory data) public payable; - /// OPTIONAL - event OnSecurityNotification(uint8 type, bytes memory sourceData, uint256 value); - - /// OPTIONAL - // TODO consider to make it a separate EIP - function bountyPolicy(uint256 id) public view returns(string, bytes memory extraData); -} -``` - -1. Compliant interfaces MUST implement the `getSecurityContact` method. - -`type` is a one byte data with valid range of `[0x10, 0x7f]`. The ranges of `[0x00, 0x0f]` and `[0x80, 0xff]` are reserved for future extension. - -The `type` indicates the format of the `publicKey` and `extraData` in the following way - ------------------------------------------------------------------------------------------------- -| Type | Encryption scheme | extraData | --------|-------------------------------------|-------------------------------------------------- -| 0x10 | GnuPG - RSA/3072 | Email address(es) encoded in format of RFC 2822 | ------------------------------------------------------------------------------------------------- - -A new version of this table can be proposed by future EIPs by specifying a new `type` number. - -2. The `publicKey` returned from `getSecurityContact` MUST follow the encryption scheme specified -in the table above. - -The following is an example of a `publicKey` using `RSA/3072` generated via GnuPG in an RFC 20 ASCII-encoding of the public key string: - -```text ------BEGIN PGP PUBLIC KEY BLOCK----- - -mQGNBGLzM2YBDADnCxAW/A0idvKNeQ6s/iYUeIIE+2mWmHcBGqLi0zrfz7pKWI+D -m6Hek51sg2c7ZlswPEp8KqANrj/CV1stXHF+KAZtYeFiAqpIZl1wtB6QgKYWGsJf -sXjBU3duLzLut2yvTfbEZsWAvrEaDjlXywdpboorHvfTE2vOvI6iGcjdh7PW7W7g -IGzlL6ukLGG7y9FUO2dSMjCR/tWMLCupnDDLN2cUHnfEnHZ34FMd61NxcHLC7cIk -P8xkFt8GCxURniTjqI5HAB8bGfR34kflVpr2+iKD5e+vQxcWK7vB443nruVf8osn -udDF8Z6mgl7bKBbGyYH58QsVlmZ8g3E4YaMKjpwOzEK3V2R8Yh4ETdr670ZCRrIz -QWVkibGgmQ3J/9RYps5Hfqpj4wV60Bsh1xUIJEIAs3ubMt7Z5JYFeze7VlXGlwot -P+SnAfKzlZT4CDEl2LEEDrbpnpOEdp0x9hYsEaXTxBGSpTDaxP2MyhW3u6pYeehG -oD0UVTLjWgU+6akAEQEAAbQjc29tZXJlYWxuYW1lIDxncGcubG9jYWwuZ2VuQHp6 -bi5pbT6JAdQEEwEIAD4WIQTDk/9jzRZ+lU2cY8rSVJNbud1lrQUCYvMzZgIbAwUJ -EswDAAULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRDSVJNbud1lraulDACqFbQg -e9hfoK17UcPVz/u4ZnwmFd9zFAWSYkGqrK9XMvz0R8pr7Y3Dp5hfvaptqID/lHhA -2oPEZ1ViIYDBcqG9WoWjCOYNoIosEAczrvf8YtUC2MHI+5DdYHtST74jDLuWMw3U -AbBXHds3KcRY5/j01kqqi4uwsMBCYyH3Jl3IwjKgy0KDBbuQakvaHPmNnt81ayvZ -ucdsNB9n/JMDxUWNCcySR+cllW4mk68pdiuK5qw0JMaoUjHFoWsgMTbFSlAV/lre -qu8MnrLSs5iPvvaJ3uDOuYROB2FsbvWxayfAAVS1iZf2vQFBJPnDwDdYoPNYMjLp -s2SfU02MVRGp3wanbtvM52uP42SLLNjBqUvJV03/QwfxCRejgAJOBn+iaOxP9NOe -qfQdKzYPbA9FohdkL9991n21XBZcZzAgF9RyU9IZAPAnwZyex1zfzJsUp/HrjhP8 -Ljs8MIcjIlmpLk66TmJte4dN5eML1bpohmfMX8k0ILESLSUhxEg1JBNYIDK5AY0E -YvMzZgEMALnIkONpqCkV+yaP8Tb8TBjmM+3TioJQROViINUQZh6lZM3/M+DPxAWZ -r0MIh1a3+o+ThlZ70tlS67w3Sjd62sWAFzALzW4F+gTqjBTh6LURDqDV8OXUrggA -SKK222aDP+Fr21h/TtPLeyDvcgm8Xvi4Cy7Jmf5CfT5jDio7a+FyFBNlTFSVqzLM -TgFOkUFBg8kJKvDjWIrS2fcTkELwZ8+IlQ52YbrXwbDar843x1fRmsY+x9nnuGuP -RYn1U4Jbptu2pEkG5q94jzUzTkGZHCzBJY7a8mtvS0mLqIE0Se1p+HFLY76Rma/F -HB6J4JNOTzBZ0/1FVvUOcMkjuZ2dX81qoCZ8NP6eafzKvNYZrGa5NJnjWO1ag5jQ -D8qHuOwxs8Fy9evmkwAVl51evLFNT532I4LK0zHSbF8MccZjpEFMSKwalKJn02Ml -yTd+ljYLf8SKMOLVps8kc4VyMR1lz0PwSpKDFOmkC1LRURpM7UTtCK+/RFg1OLyQ -SKBmdI37KQARAQABiQG8BBgBCAAmFiEEw5P/Y80WfpVNnGPK0lSTW7ndZa0FAmLz -M2YCGwwFCRLMAwAACgkQ0lSTW7ndZa2oFgv8DAxHtRZchTvjxtdLhQEUSHt80JCQ -zgHd7OUI9EU3K+oDj9AKtKZF1fqMlQoOskgBsLy/xpWwyhatv2ONLtHSjYDkZ7qs -jsXshqpuvJ3X00Yn9PXG1Z1jKl7rzy2/0DnQ8aFP+gktfu2Oat4uIu4YSqRsVW/Z -sbdTsW3T4E6Uf0qUKDf49mK3Y2nhTwY0YZqJnuQkSuUvpuM5a/4zSoaIRz+vSNjX -MoXUIK/f8UnWABPm90OCptTMTzXCC1UXEHTNm6iBJThFiq3GeLZH+GnIola5KLO1 -+YbsFEchLfLZ27pWGfIbyppvsuQmrHef+J3g6sXybOWDHVYr3Za1fzxQVIbwoIEe -ndKG0bu7ZAi2b/c8uH/wHT5IvtfzHLeSTjDqG8UyLTnaDxHQZIE9JIzWSQ1DSoNC -YrU7CQtL+/HRpiGFHfClaXln8VWkjnUvp+Fg1ZPtE1t/SKddZ7m29Hd9nzUc0OQW -MOA+HDqgA3a9kWbQKSloORq4unft1eu/FCra -=O6Bf ------END PGP PUBLIC KEY BLOCK----- -``` - -3. IF `setSecurityContact` is implemented and a call to it has succeeded in setting a new security contact, an event `SecurityContactChanged` MUST be emitted with the identical passed-in-parameters of `setSecurityContact` - -4. It's also RECOMMENDED that an on-chain security notify method `securityNotify` -to implemented to receive security notice onchain. If it's implemented and a call -has succeeded, it MUST emit an `OnSecurityNotification` with identical pass-in-parameter data. - -5. Compliant interfaces MUST implement [EIP-165](./eip-165.md). - - - -6. It's recommended to set a bounty policy via `bountyPolicy` method. The `id = 0` is preserved for a full overview, while other digits are used for different individual bounty policies. The returned -string will be URI to content of bounty policies. -No particular format of bounty policy is specified. - -## Rationale -1. For simplicity, this EIP specifies a simple GPG scheme with a given encryption scheme and uses email addresses as a contact method. It's possible that future EIPs will specify new encryption schemes or delivery methods. -2. This EIP adds an optional method, `setSecurityContact`, to set the security contact, because it might change due to circumstances such as the expiration of the cryptographic keys. -3. This EIP explicitly marks `securityNotify` as `payable`, in order to allow implementers to set a staking amount to report a security vulnerability. -4. This EIP allows for future expansion by adding the `bountyPolicy` the `extraData` fields. Additional values of these fields may be added in future EIPs. - -## Backwards Compatibility -Currently, existing solutions such as OpenZeppelin use plaintext in source code - -```solidity -/// @custom:security-contact some-user@some-domain.com -``` - -It's recommend that new versions of smart contracts adopt this EIP in addition to the legacy `@custom:security-contact` approach. - -## Security Considerations - -Implementors should properly follow security practices required by the encryption scheme to ensure the security of the chosen communication channel. Some best practices are as follows: - -1. Keep security contact information up-to-date; -2. Rotate encryption keys in the period recommended by best practice; -3. Regularly monitor the channel to receive notices in a timely manner. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5437.md diff --git a/EIPS/eip-5450.md b/EIPS/eip-5450.md index d419ce19f625cb..9c7c91bf7b9b7a 100644 --- a/EIPS/eip-5450.md +++ b/EIPS/eip-5450.md @@ -26,15 +26,15 @@ and preventing the execution and deployment of any invalid code. The operand stack validation provides several benefits: -- removes run-time stack underflow check for all instructions, -- removes run-time stack overflow check for all instruction except `CALLF`, -- ensures that an execution terminates with one of the terminating instructions, -- prevents the deployment of code with unreachable instructions, which discourages the use of code sections for data storage. +- removes the run-time stack underflow check for all instructions, +- removes the run-time stack overflow check for all instructions except `CALLF` and `JUMPF` (`JUMPF` introduced in a separate EIP) , +- ensures that execution terminates with one of the terminating instructions, +- prevents deployment of code with unreachable instructions, thereby discouraging the use of code sections for data storage. It also has some disadvantages: - adds constraints to the code structure (similar to JVM, CPython bytecode, WebAssembly and others); however, these constraints can be lifted in a backward-compatible manner if they are shown to be user-unfriendly, -- adds second validation pass; however, validation's computational and space complexity remains linear. +- it is natural to implement stack validation as a second validation pass; however, it is not strictly required and validation's computational and space complexity remains linear in any implementation variant. The guarantees created by these validation rules also improve the feasabiliy of Ahead-Of-Time and Just-In-Time compilation of EVM code. Single pass transpilation passes can be safely executed with the code validation and advanced stack/register handling can be applied with the stack height validaitons. While not as impactful to a mainnet validator node that is bound mostly by storage state sizes, these can significantly speed up witness validation and other non-mainnet use cases. @@ -58,50 +58,74 @@ In the second validation phase control-flow analysis is performed on the code. *Terminating instructions* refers to the instructions either: -- ending function execution: `RETF`, or -- ending whole EVM execution: `STOP`, `RETURN`, `REVERT`, `INVALID`. +- ending function execution: `RETF`, `JUMPF`, or +- ending whole EVM execution: `STOP`, `RETURN`, `RETURNCONTRACT`, `REVERT`, `INVALID`. -For each reachable instruction in the code the operand stack height is recorded. -The first instruction has the recorded stack height equal to the number of inputs to the function type matching the code (`type[code_section_index].inputs`). +*note: `JUMPF` and `RETURNCONTRACT` are introduced in separate EIPs.* -The FIFO queue *worklist* is used for tracking "to be inspected" instructions. Initially, it contains the first instruction. +*Forward jump* refers to any of `RJUMP`/`RJUMPI`/`RJUMPV` instruction with relative offset greater than or equal to 0. *Backwards jump* refers to any of `RJUMP`/`RJUMPI`/`RJUMPV` instruction with relative offset less than 0, including jumps to the same jump instruction. -While *worklist* is not empty, dequeue an instruction and: -1. Determine the effect the instruction has on the operand stack: - 1. **Check** if the recorded stack height satisfies the instruction requirements. Specifically: - - for `CALLF` instruction the recorded stack height must be at least the number of inputs of the called function according to its type defined in the type section. - - for `RETF` instruction the recorded stack height must be exactly the number of outputs of the function matching the code. - 2. Compute new stack height after the instruction execution. -2. Determine the list of successor instructions that can follow the current instructions: +Instructions in the code are scanned in a single linear pass over the code. For each instruction the operand stack height bounds are recorded as `stack_height_min` and `stack_height_max`. + +The first instruction's recorded stack height bounds are initialized to be equal to the number of inputs to the function type matching the code (`stack_height_min = stack_height_max = type[code_section_index].inputs`). + +For each instruction: + +1. **Check** if this instruction has recorded stack height bounds. If it does not, it means it was neither referenced by previous forward jump, nor is part of sequential instruction flow, and this code fails validation. + - It is a prerequisite to validation algorithm, and code generators are required to order code basic blocks in a way that no block is referenced only by backwards jump. +2. Determine the effect the instruction has on the operand stack: + 1. **Check** if the recorded stack height bounds satisfy the instruction requirements. Specifically: + - for `CALLF` instruction the recorded stack height lower bound must be at least the number of inputs of the called function according to its type defined in the type section, + - for `RETF` instruction both the recorded lower and upper bound must be equal and must be exactly the number of outputs of the function matching the code, + - for `JUMPF` into returning function both the recorded lower and upper bound must equal exactly `type[current_section_index].outputs + type[target_section_index].inputs - type[target_section_index].outputs`, + - for `JUMPF` into non-returning function the recorded stack height lower bound must be at least the number of inputs of the target function according to its type defined in the type section, + - for any other instruction the recodrded stack height lower bound must be at least the number of inputs required by instruction, + - there is no additional check for terminating instructions other than `RETF` and `JUMPF`, this implies that extra items left on stack at instruction ending EVM execution are allowed. + 2. For `CALLF` and `JUMPF` **check** for possible stack overflow: if recorded stack height upper bound is greater than `1024 - types[target_section_index].max_stack_height + types[target_section_index].inputs`, validation fails. + 3. Compute new stack height bounds after the instruction execution. Upper and lower bound are updated by the same value: + - after `CALLF` stack height bounds are adjusted by adding `types[target_section_index].outputs - types[target_section_index].inputs`, + - after any other non-terminating instruction stack height bounds are adjusted by subtracting the number of instruction inputs and adding the number of instruction outputs, + - terminating instructions do not need to update stack height bounds. +3. Determine the list of successor instructions that can follow the current instructions: 1. The next instruction for all instructions other than terminating instructions and unconditional jump. 2. All targets of a conditional or unconditional jump. -3. For each successor instruction: +4. For each successor instruction: 1. **Check** if the instruction is present in the code (i.e. execution must not "fall off" the code). - 2. If the instruction does not have stack height recorded (visited for the first time): - 1. Record the instruction stack height as the value computed in 1.2. - 2. Add the instruction to the *worklist*. - 3. Otherwise, **check** if the recorded stack height equals the value computed in 1.2. + 2. If the successor is reached via forwards jump or sequential flow from previous instruction: + 1. If the instruction does not have stack height bounds recorded (visited for the first time), record the instruction stack height bound as the value computed in 2.3. + 2. Otherwise instruction was already visited (by previously seen forward jump). Update this instruction's recorded stack height bounds so that they contain the bounds computed in 2.3, i.e. `target_stack_min = min(target_stack_min, current_stack_min)` and `target_stack_max = max(target_stack_max, current_stack_max)`, where `(target_stack_min, target_stack_max)` are successor bounds and `(current_stack_min, current_stack_max)` are bounds computed in 2.3. + 3. If the successor is reached via backwards jump, **check** if the recorded stack height bounds equal the value computed in 2.3. Validation fails if they are not equal, i.e. we see backwards jump to a different stack height. -When *worklist* is empty: +After all instructions are visited, determine the function maximum operand stack height: -1. **Check** if all instruction were reached by the analysis. -2. Determine the function maximum operand stack height: - 1. Compute the maximum stack height as the maximum of all recorded stack heights. - 2. **Check** if the maximum stack height does not exceed the limit of 1023 (`0x3FF`). - 3. **Check** if the maximum stack height matches the corresponding code section's `max_stack_height` within the type section. +1. Compute the maximum stack height as the maximum of all recorded stack height upper bounds. +2. **Check** if the maximum stack height does not exceed the limit of 1023 (`0x3FF`). +3. **Check** if the maximum stack height matches the corresponding code section's `max_stack_height` within the type section. The computational and space complexity of this pass is *O(len(code))*. Each instruction is visited at most once. ### Execution -Given the deploy-time validation guarantees, an EVM implementation is not required anymore to have run-time stack underflow nor overflow checks for each executed instruction. The exception is the `CALLF` performing operand stack overflow check for the entire called function. +Given the deploy-time validation guarantees, an EVM implementation is not required anymore to have run-time stack underflow nor overflow checks for each executed instruction. The exception is the `CALLF` and `JUMPF` performing operand stack overflow check for the entire called function. ## Rationale -### Stack overflow check only in CALLF +### Properties of validated code + +Any code section validated according to operand stack validation has the following properties: -In this EIP, we provide a more efficient variant of the EVM where stack overflow check is performed only in `CALLF` instruction using the called function's `max_stack_height` information. This decreases flexibility of an EVM program because `max_stack_height` corresponds to the worst-case control-flow path in the function. +1. There are no unreachable instructions +2. There are no instructions reachable only via backwards jump +3. Operand stack underflow cannot happen. +4. Operand stack overflow can only happen at `CALLF` or `JUMPF` instruction. +5. Multiple forward jump instructions executing at different stack heights may target the same instruction; the stack of target basic block is validated for all possible heights. +6. Any backwards jump instruction can only target an instruction that is executed with equal stack height; this prevents deployment of the loops with unbounded stack pushing or popping. +7. Final instruction in the code section is either terminating instruction or `RJUMP`. + +### Stack overflow check only in CALLF/JUMPF + +In this EIP, we provide a more efficient variant of the EVM where stack overflow check is performed only in `CALLF` and `JUMPF` instructions using the called function's `max_stack_height` information. This decreases flexibility of an EVM program because `max_stack_height` corresponds to the worst-case control-flow path in the function. ### Unreachable code @@ -114,6 +138,20 @@ Otherwise, the `RETF` semantic would be more complicated. For `n` function outpu However, lifting the requirement and modifying the `RETF` semantic as described above is backward compatible and can be easily introduced in the future. +### More restrictive stack validation + +Originally another variant of stack validation was proposed, where instead of linear scan of the code section, all code paths were examined by following the target(s) of every jump instruction in a breadth-first-search manner, tracking stack height for each visited instruction and checking that for every possible code path to a particular instruction its stack height remains constant. + +The advantage of this variant would be somewhat simpler algorithm (we would not need to track stack height bounds, but only a single stack height value for each instruction) and no extra requirement for ordering of code basic blocks (see below). + +However compiler teams opposed to such restrictive stack height requirements. One prominent pattern used by compilers which wouldn't be possible is jumping to terminating helpers (code blocks ending with `RETURN` or `REVERT`) from different stack heights. This is common for example for a series of `assert` statements, each one compiled to a `RJUMPI` into a shared terminating helper. Enforcing constant stack requirement would mean that before jumping to such helper, extra items on the stack have to be popped, and this noticeably increases code size and consumed gas, and would defeat the purpose of extracting these common terminating sequences into a helper. + +### Ordering of basic blocks + +The prerequisite to stack validation algorithm is ordering of code basic blocks in a way that no block is referenced only by backwards jump. + +This is required to make it possible to examine each instruction in one linear pass over the code section. Forward pass over the code section allows for the algorithm to "expand" each forward jump target's stack height bounds and still keep the complexity linear. Trying to do jump target stack bounds expansion while scanning the code in the breadth-first-search manner would require to re-examine entire code path after its stack height bounds are expanded, which would result in quadratic complexity. + ## Backwards Compatibility This change requires a "network upgrade", since it modifies consensus rules. diff --git a/EIPS/eip-5453.md b/EIPS/eip-5453.md index 322cc3b2ceced4..9ab71ea0f96125 100644 --- a/EIPS/eip-5453.md +++ b/EIPS/eip-5453.md @@ -1,345 +1,7 @@ --- eip: 5453 -title: Endorsement - Permit for Any Functions -description: A general protocol for approving function calls in the same transaction rely on EIP-5750. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-5453-endorsement-standard/10355 -status: Draft -type: Standards Track category: ERC -created: 2022-08-12 -requires: 165, 712, 1271, 5750 +status: Moved --- -## Abstract - -This EIP establish a general protocol for permitting approving function calls in the same transaction rely on [EIP-5750](./eip-5750.md). -Unlike a few prior art ([EIP-2612](./eip-2612.md) for [EIP-20](./eip-20.md), [EIP-4494](./eip-4494.md) for [EIP-721](./eip-721.md) that -usually only permit for a single behavior (`transfer` for EIP-20 and `safeTransferFrom` for EIP-721) and a single approver in two transactions (first a `permit(...)` TX, then a `transfer`-like TX), this EIP provides a way to permit arbitrary behaviors and aggregating multiple approvals from arbitrary number of approvers in the same transaction, allowing for Multi-Sig or Threshold Signing behavior. - - -## Motivation - -1. Support permit(approval) alongside a function call. -2. Support a second approval from another user. -3. Support pay-for-by another user -4. Support multi-sig -5. Support persons acting in concert by endorsements -6. Support accumulated voting -7. Support off-line signatures - - - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -### Interfaces - -The interfaces and structure referenced here are as followed - - - -```solidity -pragma solidity ^0.8.9; - -struct ValidityBound { - bytes32 functionParamStructHash; - uint256 validSince; - uint256 validBy; - uint256 nonce; -} - -struct SingleEndorsementData { - address endorserAddress; // 32 - bytes sig; // dynamic = 65 -} - -struct GeneralExtensionDataStruct { - bytes32 erc5453MagicWord; - uint256 erc5453Type; - uint256 nonce; - uint256 validSince; - uint256 validBy; - bytes endorsementPayload; -} - -interface IERC5453EndorsementCore { - function eip5453Nonce(address endorser) external view returns (uint256); - function isEligibleEndorser(address endorser) external view returns (bool); -} - -interface IERC5453EndorsementDigest { - function computeValidityDigest( - bytes32 _functionParamStructHash, - uint256 _validSince, - uint256 _validBy, - uint256 _nonce - ) external view returns (bytes32); - - function computeFunctionParamHash( - string memory _functionName, - bytes memory _functionParamPacked - ) external view returns (bytes32); -} - -interface IERC5453EndorsementDataTypeA { - function computeExtensionDataTypeA( - uint256 nonce, - uint256 validSince, - uint256 validBy, - address endorserAddress, - bytes calldata sig - ) external view returns (bytes memory); -} - - -interface IERC5453EndorsementDataTypeB { - function computeExtensionDataTypeB( - uint256 nonce, - uint256 validSince, - uint256 validBy, - address[] calldata endorserAddress, - bytes[] calldata sigs - ) external view returns (bytes memory); -} -``` - -See [`IERC5453.sol`](../assets/eip-5453/IERC5453.sol). - -### Behavior specification - -As specified in [EIP-5750 General Extensibility for Method Behaviors](./eip-5750.md), any compliant method that has an `bytes extraData` as its -last method designated for extending behaviors can conform to [EIP-5453](./eip-5453.md) as the way to indicate a permit from certain user. - -1. Any compliant method of this EIP MUST be a [EIP-5750](./eip-5750.md) compliant method. -2. Caller MUST pass in the last parameter `bytes extraData` conforming a solidity memory encoded layout bytes of `GeneralExtensonDataStruct` specified in _Section Interfaces_. The following descriptions are based on when decoding `bytes extraData` into a `GeneralExtensonDataStruct` -3. In the `GeneralExtensonDataStruct`-decoded `extraData`, caller MUST set the value of `GeneralExtensonDataStruct.erc5453MagicWord` to be the `keccak256("ERC5453-ENDORSEMENT")`. -4. Caller MUST set the value of `GeneralExtensonDataStruct.erc5453Type` to be one of the supported values. - -```solidity -uint256 constant ERC5453_TYPE_A = 1; -uint256 constant ERC5453_TYPE_B = 2; -``` - -5. When the value of `GeneralExtensonDataStruct.erc5453Type` is set to be `ERC5453_TYPE_A`, `GeneralExtensonDataStruct.endorsementPayload` MUST be abi encoded bytes of a `SingleEndorsementData`. -6. When the value of `GeneralExtensonDataStruct.erc5453Type` is set to be `ERC5453_TYPE_B`, `GeneralExtensonDataStruct.endorsementPayload` MUST be abi encoded bytes of `SingleEndorsementData[]` (a dynamic array). - -7. Each `SingleEndorsementData` MUST have a `address endorserAddress;` and a 65-bytes `bytes sig` signature. - -8. Each `bytes sig` MUST be an ECDSA (secp256k1) signature using private key of signer whose corresponding address is `endorserAddress` signing `validityDigest` which is the a hashTypeDataV4 of [EIP-712](./eip-712.md) of hashStruct of `ValidityBound` data structure as followed: - -```solidity -bytes32 validityDigest = - eip712HashTypedDataV4( - keccak256( - abi.encode( - keccak256( - "ValidityBound(bytes32 functionParamStructHash,uint256 validSince,uint256 validBy,uint256 nonce)" - ), - functionParamStructHash, - _validSince, - _validBy, - _nonce - ) - ) - ); -``` - - -9. The `functionParamStructHash` MUST be computed as followed - -```solidity - bytes32 functionParamStructHash = keccak256( - abi.encodePacked( - keccak256(bytes(_functionStructure)), - _functionParamPacked - ) - ); - return functionParamStructHash; -``` - -whereas - -- `_functionStructure` MUST be computed as `function methodName(type1 param1, type2 param2, ...)`. -- `_functionParamPacked` MUST be computed as `enc(param1) || enco(param2) ...` - -10. Upon validating that `endorserAddress == ecrecover(validityDigest, signature)` or `EIP1271(endorserAddress).isValidSignature(validityDigest, signature) == ERC1271.MAGICVALUE`, the single endorsement MUST be deemed valid. -11. Compliant method MAY choose to impose a threshold for a number of endorsements needs to be valid in the same `ERC5453_TYPE_B` kind of `endorsementPayload`. - -12. The `validSince` and `validBy` are both inclusive. Implementer MAY choose to use blocknumber or timestamp. Implementor SHOULD find away to indicate whether `validSince` and `validBy` is blocknumber or timestamp. - -## Rationale - -1. We chose to have both `ERC5453_TYPE_A`(single-endorsement) and `ERC5453_TYPE_B`(multiple-endorsements, same nonce for entire contract) so we -could balance a wider range of use cases. E.g. the same use cases of EIP-2612 and EIP-4494 can be supported by `ERC5453_TYPE_A`. And threshold approvals can be done via `ERC5453_TYPE_B`. More complicated approval types can also be extended by defining new `ERC5453_TYPE_?` - -2. We chose to include both `validSince` and `validBy` to allow maximum flexibility in expiration. This can be also be supported by EVM natively at if adopted [EIP-5081](./eip-5081.md) but EIP-5081 will not be adopted anytime soon, we choose to add these two numbers in our protocol to allow -smart contract level support. - -## Backwards Compatibility - -The design assumes a `bytes calldata extraData` to maximize the flexibility of future extensions. This assumption is compatible with [EIP-721](eip-721.md), [EIP-1155](eip-1155.md) and many other ERC-track EIPs. Those that aren't, such as [EIP-20](./eip-20.md), can also be updated to support it, such as using a wrapper contract or proxy upgrade. - -## Reference Implementation - -In addition to the specified algorithm for validating endorser signatures, we also present the following reference implementations. - -```solidity -pragma solidity ^0.8.9; - -import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; -import "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; - -import "./IERC5453.sol"; - -abstract contract AERC5453Endorsible is EIP712, - IERC5453EndorsementCore, IERC5453EndorsementDigest, IERC5453EndorsementDataTypeA, IERC5453EndorsementDataTypeB { - // ... - - function _validate( - bytes32 msgDigest, - SingleEndorsementData memory endersement - ) internal virtual { - require( - endersement.sig.length == 65, - "AERC5453Endorsible: wrong signature length" - ); - require( - SignatureChecker.isValidSignatureNow( - endersement.endorserAddress, - msgDigest, - endersement.sig - ), - "AERC5453Endorsible: invalid signature" - ); - } - // ... - - modifier onlyEndorsed( - bytes32 _functionParamStructHash, - bytes calldata _extensionData - ) { - require(_isEndorsed(_functionParamStructHash, _extensionData)); - _; - } - - function computeExtensionDataTypeB( - uint256 nonce, - uint256 validSince, - uint256 validBy, - address[] calldata endorserAddress, - bytes[] calldata sigs - ) external pure override returns (bytes memory) { - require(endorserAddress.length == sigs.length); - SingleEndorsementData[] - memory endorsements = new SingleEndorsementData[]( - endorserAddress.length - ); - for (uint256 i = 0; i < endorserAddress.length; ++i) { - endorsements[i] = SingleEndorsementData( - endorserAddress[i], - sigs[i] - ); - } - return - abi.encode( - GeneralExtensionDataStruct( - MAGIC_WORLD, - ERC5453_TYPE_B, - nonce, - validSince, - validBy, - abi.encode(endorsements) - ) - ); - } -} - -``` - -See [`AERC5453.sol`](../assets/eip-5453/AERC5453.sol) - -### Reference Implementation of `EndorsableERC721` - -Here is a reference implementation of `EndorsableERC721` that achieves similar behavior of [EIP-4494](./eip-4494.md). - -```solidity -pragma solidity ^0.8.9; - -contract EndorsableERC721 is ERC721, AERC5453Endorsible { - //... - - function mint( - address _to, - uint256 _tokenId, - bytes calldata _extraData - ) - external - onlyEndorsed( - _computeFunctionParamHash( - "function mint(address _to,uint256 _tokenId)", - abi.encode(_to, _tokenId) - ), - _extraData - ) - { - _mint(_to, _tokenId); - } -} -``` - -See [`EndorsableERC721.sol`](../assets/eip-5453/EndorsableERC721.sol) - -### Reference Implementation of `ThresholdMultiSigForwarder` - -Here is a reference implementation of ThresholdMultiSigForwarder that achieves similar behavior of multi-sig threshold approval -remote contract call like a Gnosis-Safe wallet. - -```solidity -pragma solidity ^0.8.9; - -contract ThresholdMultiSigForwarder is AERC5453Endorsible { - //... - function forward( - address _dest, - uint256 _value, - uint256 _gasLimit, - bytes calldata _calldata, - bytes calldata _extraData - ) - external - onlyEndorsed( - _computeFunctionParamHash( - "function forward(address _dest,uint256 _value,uint256 _gasLimit,bytes calldata _calldata)", - abi.encode(_dest, _value, _gasLimit, keccak256(_calldata)) - ), - _extraData - ) - { - string memory errorMessage = "Fail to call remote contract"; - (bool success, bytes memory returndata) = _dest.call{value: _value}( - _calldata - ); - Address.verifyCallResult(success, returndata, errorMessage); - } - -} - -``` - -See [`ThresholdMultiSigForwarder.sol`](../assets/eip-5453/ThresholdMultiSigForwarder.sol) - -## Security Considerations - -### Replay Attacks - -A replay attack is a type of attack on cryptography authentication. In a narrow sense, it usually refers to a type of attack that circumvents the cryptographically signature verification by reusing an existing signature for a message being signed again. Any implementations relying on this EIP must realize that all smart endorsements described here are cryptographic signatures that are _public_ and can be obtained by anyone. They must foresee the possibility of a replay of the transactions not only at the exact deployment of the same smart contract, but also other deployments of similar smart contracts, or of a version of the same contract on another `chainId`, or any other similar attack surfaces. The `nonce`, `validSince`, and `validBy` fields are meant to restrict the surface of attack but might not fully eliminate the risk of all such attacks, e.g. see the [Phishing](#phishing) section. - -### Phishing - -It's worth pointing out a special form of replay attack by phishing. An adversary can design another smart contract in a way that the user be tricked into signing a smart endorsement for a seemingly legitimate purpose, but the data-to-designed matches the target application - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5453.md diff --git a/EIPS/eip-5478.md b/EIPS/eip-5478.md index dc22e61f9aa14f..e190681c676a47 100644 --- a/EIPS/eip-5478.md +++ b/EIPS/eip-5478.md @@ -4,7 +4,7 @@ title: CREATE2COPY Opcode description: Reducing the gas cost of contract creation with existing code author: Qi Zhou (@qizhou) discussions-to: https://ethereum-magicians.org/t/eip-5478-reducing-the-gas-cost-of-contract-creation-with-existing-code/10419 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-08-17 diff --git a/EIPS/eip-5484.md b/EIPS/eip-5484.md index a885f529885651..f199d2724ddde5 100644 --- a/EIPS/eip-5484.md +++ b/EIPS/eip-5484.md @@ -1,116 +1,7 @@ --- eip: 5484 -title: Consensual Soulbound Tokens -description: Interface for special NFTs with immutable ownership and pre-determined immutable burn authorization -author: Buzz Cai (@buzzcai) -discussions-to: https://ethereum-magicians.org/t/eip-5484-consensual-soulbound-tokens/10424 -status: Final -type: Standards Track category: ERC -created: 2022-08-17 -requires: 165, 721 +status: Moved --- - -## Abstract - -This EIP defines an interface extending [EIP-721](./eip-721.md) to create soulbound tokens. Before issuance, both parties (the issuer and the receiver), have to agree on who has the authorization to burn this token. Burn authorization is immutable after declaration. After its issuance, a soulbound token can't be transferred, but can be burned based on a predetermined immutable burn authorization. - -## Motivation - -The idea of soulbound tokens has gathered significant attention since its publishing. Without a standard interface, however, soulbound tokens are incompatible. It is hard to develop universal services targeting at soulbound tokens without minimal consensus on the implementation of the tokens. - -This EIP envisions soulbound tokens as specialized NFTs that will play the roles of credentials, credit records, loan histories, memberships, and many more. In order to provide the flexibility in these scenarios, soulbound tokens must have an application-specific burn authorization and a way to distinguish themselves from regular EIP-721 tokens. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -- The token MUST implement the following interfaces: - - 1. [EIP-165](./eip-165.md)’s `ERC165` (`0x01ffc9a7`) - 1. [EIP-721](./eip-721.md)’s `ERC721` (`0x80ac58cd`) - -- `burnAuth` SHALL be presented to receiver before issuance. -- `burnAuth` SHALL be Immutable after issuance. -- `burnAuth` SHALL be the sole factor that determines which party has the rights to burn token. -- The issuer SHALL present token metadata to the receiver and acquire receiver's signature before issuance. -- The issuer SHALL NOT change metadata after issuance. - -/// Note: the EIP-165 identifier for this interface is 0x0489b56f - -### Contract Interface - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface IERC5484 { - /// A guideline to standardlize burn-authorization's number coding - enum BurnAuth { - IssuerOnly, - OwnerOnly, - Both, - Neither - } - - /// @notice Emitted when a soulbound token is issued. - /// @dev This emit is an add-on to nft's transfer emit in order to distinguish sbt - /// from vanilla nft while providing backward compatibility. - /// @param from The issuer - /// @param to The receiver - /// @param tokenId The id of the issued token - event Issued ( - address indexed from, - address indexed to, - uint256 indexed tokenId, - BurnAuth burnAuth - ); - - /// @notice provides burn authorization of the token id. - /// @dev unassigned tokenIds are invalid, and queries do throw - /// @param tokenId The identifier for a token. - function burnAuth(uint256 tokenId) external view returns (BurnAuth); -} -``` - -## Rationale - -### Soulbound Token (SBTs) as an extension to EIP-721 - -We believe that soulbound token serves as a specialized subset of the existing EIP-721 tokens. The advantage of such design is seamless compatibility of soulbound token with existing NFT services. Service providers can treat SBTs like NFTs and do not need to make drastic changes to their existing codebase. - -### Non-Transferable - -One problem with current soulbound token implementations that extend from [EIP-721](./eip-721.md) is that all transfer implementations throw errors. A much cleaner approach would be for transfer functions to still throw, but also enable third parties to check beforehand if the contract implements the soulbound interface to avoid calling transfer. - -### Burn Authorization - -We want maximum freedom when it comes to interface usage. A flexible and predetermined rule to burn is crucial. Here are some sample scenarios for different burn authorizations: - -- `IssuerOnly`: Loan record -- `ReceiverOnly`: Paid membership -- `Both`: Credentials -- `Neither`: Credit history - -Burn authorization is tied to specific tokens and immutable after issuance. It is therefore important to inform the receiver and gain receiver's consent before the token is issued. - -### Issued Event - -On issuing, an `Issued` event will be emitted alongside [EIP-721](./eip-721.md)'s `Transfer` event. This design keeps backward compatibility while giving clear signals to thrid-parties that this is a soulBound token issuance event. - -### Key Rotations - -A concern Ethereum users have is that soulbound tokens having immutable ownership discourage key rotations. This is a valid concern. Having a burnable soulbound token, however, makes key rotations achievable. The owner of the soulbound token, when in need of key rotations, can inform the issuer of the token. Then the party with burn authorization can burn the token while the issuer can issue a replica to the new address. - -## Backwards Compatibility - -This proposal is fully backward compatible with [EIP-721](./eip-721.md) - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5484.md diff --git a/EIPS/eip-5485.md b/EIPS/eip-5485.md index 85064a50d6046a..1511dbb63a03b5 100644 --- a/EIPS/eip-5485.md +++ b/EIPS/eip-5485.md @@ -1,88 +1,7 @@ --- eip: 5485 -title: Legitimacy, Jurisdiction and Sovereignty -description: An interface for identifying the legitimacy, jurisdiction and sovereignty. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-5485-interface-for-legitimacy-jurisdiction-and-sovereignty/10425 -status: Draft -type: Standards Track category: ERC -created: 2022-08-17 -requires: 165, 5247 +status: Moved --- -## Abstract -Provide a way for compliant smart contracts to declare their legitimacy lineage, jurisdiction they observe, and sovereignty if they choose to not fall onto any jurisdiction. - -## Motivation -Today, smart contracts have no standard way to specify their legitimacy lineage, jurisdiction, or sovereignty relationship. The introduction of such a standard, supports better integration with today's legal and regulative scenarios: - -1. it supports a regulative body to allow or deny interoperability with smart contracts. -2. it also allows DAOs to clearly declare "self-sovereignty" by announcing via this interface by saying they do not assert legitimacy from any source other than themselves. - -A real-world example is that ContractA represents an **A company registered in a country**, ContractB represents a **The Secretary of State of the country**, and ContractC represents the **Supreme Court of the Country**. - -Another real example is a contract that declares "self-sovereignty" that doesn't follow any jurisdiction. - -This interface supports both cases, providing a way to allow smart contracts to determine if they want to allow/prohibit interaction based on sovereignty. - -For example, a country might want to require any digital money service's all smart contracts to observe their [EIP-5485](./eip-5485.md) jurisdiction before they are allowed to operate money in their (real world) legal jurisdiction. - -Another real world use-case is that in some jurisdiction e.g. in United States, if an token issuer choose to issue a token, -they can try to petition SEC to recognize their token as registered security, if approved, will gain legitimacy from SEC. -Should they choose to petition Commodity Futures Trading Commission (CFTC) to recognize them as a commodity, if approved, will -gain legitimacy from CFTC. - -On the other hand, a DAO with a strong decentralized ideology might choose to only inter-operate with EOA or "self-sovereign" smart contracts to avoid being affected by any country. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -1. Compliant contract MUSTS implement the following interface. - -```solidity -interface IERC5485 { - /// A function that returns the source of legitimacy in an address - /// - /// @returns address of EOA or contract that grants legitimacy status to this contract. - /// See Specification #2 and #3 for more details. - function sourceOfLegitimacy() public view returns (address); - - /// A function that returns the sovereign jurisdiction in an address - /// - /// @returns address of EOA or contract that *ultimately* grants legitimacy status (root of legitimacy lineage). - /// See Specification #4 and #4 for more details. - function jurisdiction() public view returns (address); -} -``` - -2. Suppose a compliant `ContractA` is deployed at address `0x` and gains its legitimacy from another contract or External Owned Account (EOA) at `0x`. In this case, it MUST return the `0x` when being queried for `sourceOfLegitimacy()`. For example. If `ContractA` gains legitimacy from `ContractB`, `ContractB` gains legitimacy from `ContractC` but `ContractC` doesn't gain legitimacy from anyone, ContractC is considered the "jurisdiction" that both `ContractB` and `ContractA` observe. Both `ContractA` and `ContractB` MUST return the address of `ContractC` as the result of jurisdiction. - -3. A contract that matches ANY of the following cases is considered a "sovereign contract": - -- Case 1: it does not implement this EIP -- Case 2: it implements this EIP but return its *own address*. -- Case 3: it implements this EIP but return a ZERO address. - -4. Any compliant contract MUST return its legitimacy sources chain up to the sovereign contract when queried by `jurisdiction()`. - -5. If ContractA gains legitimacy from ContractB, ContractA MUST observe the ContractB's order to ANY of the following -- Order Type 1: execute a `selfdestruct` of ContractA - -6. If ContractA observes jurisdiction of ContractC (a sovereignty), ContractA MUST observe ContractC's order to ANY the following -- Order Type 1: execute a `selfdestruct` of ContractA -- Order Type 2: execute ANY smart contract executable proposals as specified in [EIP-5247](./eip-5247.md) - -TODO determine whether to address "add/remove legitimacy" in this EIP or leave it as a future EIP - -## Rationale -Needs discussion. - -## Backwards Compatibility -Needs discussion. - -## Security Considerations -Needs discussion. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5485.md diff --git a/EIPS/eip-5489.md b/EIPS/eip-5489.md index aec096b66bc551..dc67574085a2bc 100644 --- a/EIPS/eip-5489.md +++ b/EIPS/eip-5489.md @@ -1,172 +1,7 @@ --- eip: 5489 -title: NFT Hyperlink Extension -description: NFT Hyperlink Extension embeds hyperlinks onto NFTs, allowing users to click any hNFT and be transported to any url set by the owner. -author: IronMan_CH (@coderfengyun) -discussions-to: https://ethereum-magicians.org/t/eip-5489-nft-hyperlink-extension/10431 -status: Final -type: Standards Track category: ERC -created: 2022-08-16 -requires: 165, 721 +status: Moved --- -## Abstract - -This EIP proposes a new extension for NFTs (non-fungible token, aka [EIP-721](./eip-721.md)): nft-hyperlink-extention (hNFT), embedding NFTs with hyperlinks, referred to as “hNFTs”. As owners of hNFTs, users may authorize a URL slot to a specific address which can be either an externally-owned account (EOA) or a contract address and hNFT owners are entitled to revoke that authorization at any time. The address which has slot authorization can manage the URL of that slot. - - -## Motivation - -As NFTs attract more attention, they have the potential to become the primary medium of Web3. Currently, end users can’t attach rich texts, videos, or images to NFTs, and there’s no way to render these rich-content attachments. Many industries eagerly look forward to this kind of rich-content attachment ability. Attaching, editing, and displaying highly customized information can usefully be standardized. - -This EIP uses hyperlinks as the aforementioned form of “highly customized attachment on NFT”, and also specifies how to attach, edit, and display these attachments on NFTs. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Interface - -#### `IERC5489` - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface IERC5489 { - /** - * @dev this event emits when the slot on `tokenId` is authorzized to `slotManagerAddr` - */ - event SlotAuthorizationCreated(uint256 indexed tokenId, address indexed slotManagerAddr); - - /** - * @dev this event emits when the authorization on slot `slotManagerAddr` of token `tokenId` is revoked. - * So, the corresponding DApp can handle this to stop on-going incentives or rights - */ - event SlotAuthorizationRevoked(uint256 indexed tokenId, address indexed slotManagerAddr); - - /** - * @dev this event emits when the uri on slot `slotManagerAddr` of token `tokenId` has been updated to `uri`. - */ - event SlotUriUpdated(uint256 indexed tokenId, address indexed slotManagerAddr, string uri); - - /** - * @dev - * Authorize a hyperlink slot on `tokenId` to address `slotManagerAddr`. - * Indeed slot is an entry in a map whose key is address `slotManagerAddr`. - * Only the address `slotManagerAddr` can manage the specific slot. - * This method will emit SlotAuthorizationCreated event - */ - function authorizeSlotTo(uint256 tokenId, address slotManagerAddr) external; - - /** - * @dev - * Revoke the authorization of the slot indicated by `slotManagerAddr` on token `tokenId` - * This method will emit SlotAuthorizationRevoked event - */ - function revokeAuthorization(uint256 tokenId, address slotManagerAddr) external; - - /** - * @dev - * Revoke all authorizations of slot on token `tokenId` - * This method will emit SlotAuthorizationRevoked event for each slot - */ - function revokeAllAuthorizations(uint256 tokenId) external; - - /** - * @dev - * Set uri for a slot on a token, which is indicated by `tokenId` and `slotManagerAddr` - * Only the address with authorization through {authorizeSlotTo} can manipulate this slot. - * This method will emit SlotUriUpdated event - */ - function setSlotUri( - uint256 tokenId, - string calldata newUri - ) external; - - /** - * @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC 3986. - * The URI MUST point to a JSON file that conforms to the "EIP5489 Metadata JSON schema". - * - * returns the latest uri of an slot on a token, which is indicated by `tokenId`, `slotManagerAddr` - */ - function getSlotUri(uint256 tokenId, address slotManagerAddr) - external - view - returns (string memory); -} -``` - -The `authorizeSlotTo(uint256 tokenId, address slotManagerAddr)` function MAY be implemented as public or external. - -The `revokeAuthorization(uint256 tokenId, address slotManagerAddr)` function MAY be implemented as public or external. - -The `revokeAllAuthorizations(uint256 tokenId)` function MAY be implemented as public or external. - -The `setSlotUri(uint256 tokenId, string calldata newUri)` function MAY be implemented as public or external. - -The `getSlotUri(uint256 tokenId, address slotManagerAddr)` function MAY be implemented as pure or view. - -The `SlotAuthorizationCreated` event MUST be emitted when a slot is authorized to an address. - -The `SlotAuthorizationRevoked` event MUST be emitted when a slot authorization is revoked. - -The `SlotUriUpdated` event MUSt be emitted when a slot's URI is changed. - -The `supportInterface` method MUST return true when called with `0x8f65987b`. - -### Authentication - -The `authorizeSlotTo`, `revokeAuthorization`, and `revokeAllAuthorizations` functions are authenticated if and only if the message sender is the owner of the token. - -### Metadata JSON schema - -```json -{ - "title": "AD Metadata", - "type": "object", - "properties": { - "icon": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the slot's occupier. Consider making any images at a width between 48 and 1080 pixels and aspect ration between 1.91:1 and 4:5 inclusive. Suggest to show this as an thumbnail of the target resource" - }, - "description": { - "type": "string", - "description": "A paragraph which briefly introduce what is the target resource" - }, - "target": { - "type": "string", - "description": "A URI pointing to target resource, sugguest to follow 30X status code to support more redirections, the mime type and content rely on user's setting" - } - } -} -``` - -## Rationale - -### Extends NFT with hyperlinks - -URIs are used to represent the value of slots to ensure enough flexibility to deal with different use cases. - -### Authorize slot to address - -We use addresses to represent the key of slots to ensure enough flexibility to deal with all use cases. - -## Backwards Compatibility - -As mentioned in the specifications section, this standard can be fully EIP-721 compatible by adding an extension function set. - -In addition, new functions introduced in this standard have many similarities with the existing functions in EIP-721. This allows developers to easily adopt the standard quickly. - -## Reference Implementation - -You can find an implementation of this standard in [`ERC5489.sol`](../assets/eip-5489/contracts/ERC5489.sol). - -## Security Considerations - -No security considerations were found. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5489.md diff --git a/EIPS/eip-5496.md b/EIPS/eip-5496.md index ea436746269521..7b198b74d28fa5 100644 --- a/EIPS/eip-5496.md +++ b/EIPS/eip-5496.md @@ -1,254 +1,7 @@ --- eip: 5496 -title: Multi-privilege Management NFT Extension -description: Create shareable multi-privilege NFTs for EIP-721 -author: Jeremy Z (@wnft) -discussions-to: https://ethereum-magicians.org/t/eip-5496-multi-privilege-management-extension-for-erc-721/10427 -status: Last Call -last-call-deadline: 2022-11-29 -type: Standards Track category: ERC -created: 2022-07-30 -requires: 721 +status: Moved --- - -## Abstract - -This EIP defines an interface extending [EIP-721](./eip-721.md) to provide shareable multi-privileges for NFTs. Privileges may be on-chain (voting rights, permission to claim an airdrop) or off-chain (a coupon for an online store, a discount at a local restaurant, access to VIP lounges in airports). Each NFT may contain many privileges, and the holder of a privilege can verifiably transfer that privilege to others. Privileges may be non-shareable or shareable. Shareable privileges can be cloned, with the provider able to adjust the details according to the spreading path. Expiration periods can also be set for each privilege. - -## Motivation - -This standard aims to efficiently manage privileges attached to NFTs in real-time. Many NFTs have functions other than just being used as profile pictures or art collections, they may have real utilities in different scenarios. For example, a fashion store may give a discount for its own NFT holders; a DAO member NFT holder can vote for the proposal of how to use their treasury; a dApp may create an airdrop event to attract a certain group of people like some blue chip NFT holders to claim; the grocery store can issue its membership card on chain (as an NFT) and give certain privileges when the members shop at grocery stores, etc. There are cases when people who own NFTs do not necessarily want to use their privileges. By providing additional data recording different privileges a NFT collection has and interfaces to manage them, users can transfer or sell privileges without losing their ownership of the NFT. - -[EIP-721](./eip-721.md) only records the ownership and its transfer, the privileges of an NFT are not recorded on-chain. This extension would allow merchants/projects to give out a certain privilege to a specified group of people, and owners of the privileges can manage each one of the privileges independently. This facilitates a great possibility for NFTs to have real usefulness. - -For example, an airline company issues a series of [EIP-721](./eip-721.md)/[EIP-1155](./eip-1155.md) tokens to Crypto Punk holders to give them privileges, in order to attract them to join their club. However, since these tokens are not bound to the original NFT, if the original NFT is transferred, these privileges remain in the hands of the original holders, and the new holders cannot enjoy the privileges automatically. -So, we propose a set of interfaces that can bind the privileges to the underlying NFT, while allowing users to manage the privileges independently. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Every contract complying with this standard MUST implement the `IERC5496` interface. The **shareable multi-privilege extension** is OPTIONAL for EIP-721 contracts. - -```solidity -/// @title multi-privilege extension for EIP-721 -/// Note: the EIP-165 identifier for this interface is 0x076e1bbb -interface IERC5496{ - /// @notice Emitted when `owner` changes the `privilege holder` of a NFT. - event PrivilegeAssigned(uint256 tokenId, uint256 privilegeId, address user, uint256 expires); - /// @notice Emitted when `contract owner` changes the `total privilege` of the collection - event PrivilegeTotalChanged(uint256 newTotal, uint256 oldTotal); - - /// @notice set the privilege holder of a NFT. - /// @dev expires should be less than 30 days - /// Throws if `msg.sender` is not approved or owner of the tokenId. - /// @param tokenId The NFT to set privilege for - /// @param privilegeId The privilege to set - /// @param user The privilege holder to set - /// @param expires For how long the privilege holder can have - function setPrivilege(uint256 tokenId, uint256 privilegeId, address user, uint256 expires) external; - - /// @notice Return the expiry timestamp of a privilege - /// @param tokenId The identifier of the queried NFT - /// @param privilegeId The identifier of the queried privilege - /// @return Whether a user has a certain privilege - function privilegeExpires(uint256 tokenId, uint256 privilegeId) external view returns(uint256); - - /// @notice Check if a user has a certain privilege - /// @param tokenId The identifier of the queried NFT - /// @param privilegeId The identifier of the queried privilege - /// @param user The address of the queried user - /// @return Whether a user has a certain privilege - function hasPrivilege(uint256 tokenId, uint256 privilegeId, address user) external view returns(bool); -} -``` - -Every contract implementing this standard SHOULD set a maximum privilege number before setting any privilege, the `privilegeId` MUST NOT be greater than the maximum privilege number. - -The `PrivilegeAssigned` event MUST be emitted when `setPrivilege` is called. - -The `PrivilegeTotalChanged` event MUST be emitted when the `total privilege` of the collection is changed. - -The `supportsInterface` method MUST return `true` when called with `0x076e1bbb`. - -```solidity -/// @title Cloneable extension - Optional for EIP-721 -interface IERC721Cloneable { - /// @notice Emitted when set the `privilege ` of a NFT cloneable. - event PrivilegeCloned(uint tokenId, uint privId, address from, address to); - - /// @notice set a certain privilege cloneable - /// @param tokenId The identifier of the queried NFT - /// @param privilegeId The identifier of the queried privilege - /// @param referrer The address of the referrer - /// @return Whether the operation is successful or not - function clonePrivilege(uint tokenId, uint privId, address referrer) external returns (bool); -} -``` - -The `PrivilegeCloned` event MUST be emitted when `clonePrivilege` is called. - -For Compliant contract, it is RECOMMENDED to use [EIP-1271](./eip-1271.md) to validate the signatures. - -## Rationale - -### Shareable Privileges - -The number of privilege holders is limited by the number of NFTs if privileges are non-shareable. A shareable privilege means the original privilege holder can copy the privilege and give it to others, not transferring his/her own privilege to them. This mechanism greatly enhances the spread of privileges as well as the adoption of NFTs. - -### Expire Date Type - -The expiry timestamp of a privilege is a timestamp and stored in `uint256` typed variables. - -### Beneficiary of Referrer - -For example, a local pizza shop offers a 30% off Coupon and the owner of the shop encourages their consumers to share the coupon with friends, then the friends can get the coupon. Let's say Tom gets 30% off Coupon from the shop and he shares the coupon with Alice. Alice gets the coupon too and Alice's referrer is Tom. For some certain cases, Tom may get more rewards from the shop. This will help the merchants in spreading the promotion among consumers. - -### Proposal: NFT Transfer - -If the owner of the NFT transfers ownership to another user, there is no impact on "privileges". But errors may occur if the owner tries to withdraw the original [EIP-721](./eip-721.md) token from the wrapped NFT through `unwrap()` if any available privileges are still ongoing. We protect the rights of holders of the privileges to check the last expiration date of the privilege. - -```solidity -function unwrap(uint256 tokenId, address to) external { - require(getBlockTimestamp() >= privilegeBook[tokenId].lastExpiresAt, "privilege not yet expired"); - - require(ownerOf(tokenId) == msg.sender, "not owner"); - - _burn(tokenId); - - IERC721(nft).transferFrom(address(this), to, tokenId); - - emit Unwrap(nft, tokenId, msg.sender, to); -} -``` - -## Backwards Compatibility - -This EIP is compatible with any kind of NFTs that follow the EIP-721 standard. It only adds more functions and data structures without interfering with the original [EIP-721](./eip-721.md) standard. - -## Test Cases - -Test cases are implemented with the reference implementation. - -### Test Code - -[test.js](../assets/eip-5496/test/test.js) - -Run in terminal: - -```shell -truffle test ./test/test.js -``` - -[testCloneable.js](../assets/eip-5496/test/testCloneable.js) - -Run in terminal: - -```shell -truffle test ./test/testCloneable.js -``` - -## Reference Implementation - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; -import "./IERC5496.sol"; - -contract ERC5496 is ERC721, IERC5496 { - struct PrivilegeRecord { - address user; - uint256 expiresAt; - } - struct PrivilegeStorage { - uint lastExpiresAt; - // privId => PrivilegeRecord - mapping(uint => PrivilegeRecord) privilegeEntry; - } - - uint public privilegeTotal; - // tokenId => PrivilegeStorage - mapping(uint => PrivilegeStorage) public privilegeBook; - mapping(address => mapping(address => bool)) private privilegeDelegator; - - constructor(string memory name_, string memory symbol_) - ERC721(name_,symbol_) - { - - } - - function setPrivilege( - uint tokenId, - uint privId, - address user, - uint64 expires - ) external virtual { - require((hasPrivilege(tokenId, privId, ownerOf(tokenId)) && _isApprovedOrOwner(msg.sender, tokenId)) || _isDelegatorOrHolder(msg.sender, tokenId, privId), "ERC721: transfer caller is not owner nor approved"); - require(expires < block.timestamp + 30 days, "expire time invalid"); - require(privId < privilegeTotal, "invalid privilege id"); - privilegeBook[tokenId].privilegeEntry[privId].user = user; - if (_isApprovedOrOwner(msg.sender, tokenId)) { - privilegeBook[tokenId].privilegeEntry[privId].expiresAt = expires; - if (privilegeBook[tokenId].lastExpiresAt < expires) { - privilegeBook[tokenId].lastExpiresAt = expires; - } - } - emit PrivilegeAssigned(tokenId, privId, user, uint64(privilegeBook[tokenId].privilegeEntry[privId].expiresAt)); - } - - function hasPrivilege( - uint256 tokenId, - uint256 privId, - address user - ) public virtual view returns(bool) { - if (privilegeBook[tokenId].privilegeEntry[privId].expiresAt >= block.timestamp){ - return privilegeBook[tokenId].privilegeEntry[privId].user == user; - } - return ownerOf(tokenId) == user; - } - - function privilegeExpires( - uint256 tokenId, - uint256 privId - ) public virtual view returns(uint256){ - return privilegeBook[tokenId].privilegeEntry[privId].expiresAt; - } - - function _setPrivilegeTotal( - uint total - ) internal { - emit PrivilegeTotalChanged(total, privilegeTotal); - privilegeTotal = total; - } - - function getPrivilegeInfo(uint tokenId, uint privId) external view returns(address user, uint256 expiresAt) { - return (privilegeBook[tokenId].privilegeEntry[privId].user, privilegeBook[tokenId].privilegeEntry[privId].expiresAt); - } - - function setDelegator(address delegator, bool enabled) external { - privilegeDelegator[msg.sender][delegator] = enabled; - } - - function _isDelegatorOrHolder(address delegator, uint256 tokenId, uint privId) internal virtual view returns (bool) { - address holder = privilegeBook[tokenId].privilegeEntry[privId].user; - return (delegator == holder || isApprovedForAll(holder, delegator) || privilegeDelegator[holder][delegator]); - } - - function supportsInterface(bytes4 interfaceId) public override virtual view returns (bool) { - return interfaceId == type(IERC5496).interfaceId || super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations - -Implementations must thoroughly consider who has the permission to set or clone privileges. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5496.md diff --git a/EIPS/eip-55.md b/EIPS/eip-55.md index 325a70f9683ef0..f7016be98d9850 100644 --- a/EIPS/eip-55.md +++ b/EIPS/eip-55.md @@ -1,119 +1,7 @@ --- eip: 55 -title: Mixed-case checksum address encoding -author: Vitalik Buterin , Alex Van de Sande -discussions-to: https://github.com/ethereum/eips/issues/55 -type: Standards Track category: ERC -status: Final -created: 2016-01-14 +status: Moved --- -# Specification - -Code: - -``` python -import eth_utils - - -def checksum_encode(addr): # Takes a 20-byte binary address as input - hex_addr = addr.hex() - checksummed_buffer = "" - - # Treat the hex address as ascii/utf-8 for keccak256 hashing - hashed_address = eth_utils.keccak(text=hex_addr).hex() - - # Iterate over each character in the hex address - for nibble_index, character in enumerate(hex_addr): - - if character in "0123456789": - # We can't upper-case the decimal digits - checksummed_buffer += character - elif character in "abcdef": - # Check if the corresponding hex digit (nibble) in the hash is 8 or higher - hashed_address_nibble = int(hashed_address[nibble_index], 16) - if hashed_address_nibble > 7: - checksummed_buffer += character.upper() - else: - checksummed_buffer += character - else: - raise eth_utils.ValidationError( - f"Unrecognized hex character {character!r} at position {nibble_index}" - ) - - return "0x" + checksummed_buffer - - -def test(addr_str): - addr_bytes = eth_utils.to_bytes(hexstr=addr_str) - checksum_encoded = checksum_encode(addr_bytes) - assert checksum_encoded == addr_str, f"{checksum_encoded} != expected {addr_str}" - - -test("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed") -test("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359") -test("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB") -test("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb") - -``` - -In English, convert the address to hex, but if the `i`th digit is a letter (ie. it's one of `abcdef`) print it in uppercase if the `4*i`th bit of the hash of the lowercase hexadecimal address is 1 otherwise print it in lowercase. - -# Rationale - -Benefits: -- Backwards compatible with many hex parsers that accept mixed case, allowing it to be easily introduced over time -- Keeps the length at 40 characters -- On average there will be 15 check bits per address, and the net probability that a randomly generated address if mistyped will accidentally pass a check is 0.0247%. This is a ~50x improvement over ICAP, but not as good as a 4-byte check code. - -# Implementation - -In javascript: - -```js -const createKeccakHash = require('keccak') - -function toChecksumAddress (address) { - address = address.toLowerCase().replace('0x', '') - var hash = createKeccakHash('keccak256').update(address).digest('hex') - var ret = '0x' - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase() - } else { - ret += address[i] - } - } - - return ret -} -``` - -``` -> toChecksumAddress('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359') -'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359' -``` - -Note that the input to the Keccak256 hash is the lowercase hexadecimal string (i.e. the hex address encoded as ASCII): - -``` - var hash = createKeccakHash('keccak256').update(Buffer.from(address.toLowerCase(), 'ascii')).digest() -``` - -# Test Cases - -``` -# All caps -0x52908400098527886E0F7030069857D2E4169EE7 -0x8617E340B3D01FA5F11F306F4090FD50E238070D -# All Lower -0xde709f2102306220921060314715629080e2fb77 -0x27b1fdb04752bbc536007a920d24acb045561c26 -# Normal -0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed -0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359 -0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB -0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb -``` +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-55.md diff --git a/EIPS/eip-5501.md b/EIPS/eip-5501.md index 3d34905e9e40c2..5da15b925fb07a 100644 --- a/EIPS/eip-5501.md +++ b/EIPS/eip-5501.md @@ -1,251 +1,7 @@ --- eip: 5501 -title: Rental & Delegation NFT - EIP-721 Extension -description: Adds a conditional time-limited user role to EIP-721. This role can be delegated or borrowed. -author: Jan Smrža (@smrza), David Rábel (@rabeles11), Tomáš Janča , Jan Bureš (@JohnyX89), DOBBYLABS (@DOBBYLABS) -discussions-to: https://ethereum-magicians.org/t/eip-tbd-rental-delegation-nft-erc-721-extension/10441 -status: Draft -type: Standards Track category: ERC -created: 2022-08-18 -requires: 165, 721, 4400, 4907 +status: Moved --- -## Abstract -The following standard proposes an additional `user` role for [EIP-721](./eip-721.md). This role grants the permission to use the NFT with no ability to transfer or set users. It has an expiry and a flag if the token is borrowed or not. `Owner` can delegate the NFT for usage to hot wallets or lend the NFT. If the token is borrowed, not even the owner can change the user until the status expires or both parties agree to terminate. This way, it is possible to keep both roles active at the same time. - -## Motivation -Collectibles, gaming assets, metaverse, event tickets, music, video, domains, real item representation are several among many NFT use cases. With [EIP-721](./eip-721.md) only the owner can reap the benefits. However, with most of the utilities it would be beneficial to distinguish between the token owner and its user. For instance music or movies could be rented. Metaverse lands could be delegated for usage. - -The two reasons why to set the user are: - -* **delegation** - Assign user to your hot wallet to interact with applications securely. In this case, the owner can change the user at any time. -* **renting** - This use case comes with additional requirements. It is needed to terminate the loan once the established lending period is over. This is provided by `expires` of the user. It is also necessary to protect the borrower against resetting their status by the owner. Thus, `isBorrowed` check must be implemented to disable the option to set the user before the contract expires. - -The most common use cases for having an additional user role are: - -* **delegation** - For security reasons. -* **gaming** - Would you like to try a game (or particular gaming assets) but are you unsure whether or not you will like it? Rent assets first. -* **guilds** - Keep the owner of the NFTs as the multisig wallet and set the user to a hot wallet with shared private keys among your guild members. -* **events** - Distinguish between `ownerOf` and `userOf`. Each role has a different access. -* **social** - Differentiate between roles for different rooms. For example owner has read + write access while userOf has read access only. - -This proposal is a follow up on [EIP-4400](./eip-4400.md) and [EIP-4907](./eip-4907.md) and introduces additional upgrades for lending and borrowing which include: - -* **NFT stays in owner's wallet during rental period** -* **Listing and sale of NFT without termination of the rent** -* **Claiming owner benefits during rental period** - -Building the standard with additional isBorrowed check now allows to create rental marketplaces which can set the user of NFT without the necessary staking mechanism. With current standards if a token is not staked during the rental period, the owner can simply terminate the loan by setting the user repeatedly. This is taken care of by disabling the function if the token is borrowed which in turn is providing the owner additional benefits. They can keep the token tied to their wallet, meaning they can still receive airdrops, claim free mints based on token ownership or otherwise use the NFT provided by third-party services for owners. They can also keep the NFT listed for sale. Receiving airdrops or free mints was previously possible but the owner was completely reliant on the implementation of rental marketplaces and their discretion. - -Decentralized applications can now differentiate between ownerOf and userOf while both statuses can coexist. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -**Every compliant contract MUST implement the `IERC5501` interface. This extension is OPTIONAL for [EIP-721](./eip-721.md) contracts.** - -```solidity -/** - * @title IERC5501: Rental & Delegation NFT - EIP-721 Extension - * @notice the EIP-165 identifier for this interface is 0xf808ec37. - */ -interface IERC5501 /* is IERC721 */ { - /** - * @dev Emitted when the user of an NFT is modified. - */ - event UpdateUser(uint256 indexed _tokenId, address indexed _user, uint64 _expires, bool _isBorrowed); - - /** - * @notice Set the user info of an NFT. - * @dev User address cannot be zero address. - * Only approved operator or NFT owner can set the user. - * If NFT is borrowed, the user info cannot be changed until user status expires. - * @param _tokenId uint256 ID of the token to set user info for - * @param _user address of the new user - * @param _expires Unix timestamp when user info expires - * @param _isBorrowed flag whether or not the NFT is borrowed - */ - function setUser(uint256 _tokenId, address _user, uint64 _expires, bool _isBorrowed) external; - - /** - * @notice Get the user address of an NFT. - * @dev Reverts if user is not set. - * @param _tokenId uint256 ID of the token to get the user address for - * @return address user address for this NFT - */ - function userOf(uint256 _tokenId) external view returns (address); - - /** - * @notice Get the user expires of an NFT. - * @param _tokenId uint256 ID of the token to get the user expires for - * @return uint64 user expires for this NFT - */ - function userExpires(uint256 _tokenId) external view returns (uint64); - - /** - * @notice Get the user isBorrowed of an NFT. - * @param _tokenId uint256 ID of the token to get the user isBorrowed for - * @return bool user isBorrowed for this NFT - */ - function userIsBorrowed(uint256 _tokenId) external view returns (bool); -} -``` - -Every contract implementing the `IERC5501` interface is free to define the permissions of a `user`. However, user MUST NOT be considered an `owner`. They MUST NOT be able to execute transfers and approvals. Furthermore, `setUser` MUST be blocked from executing if `userIsBorrowed` returns `true` and `userExpires` is larger than or equal to `block.timestamp`. - -The `UpdateUser` event MUST be emitted when a `user` is changed. -The `setUser(uint256 _tokenId, address _user, uint64 _expires, bool _isBorrowed)` function SHOULD `revert` unless the `msg.sender` is the `owner` or an approved operator. It MUST revert if a token is borrowed and status has not expired yet. It MAY be `public` or `external`. -The `userOf(uint256 _tokenId)` function SHOULD revert if `user` is not set or expired. -The `userExpires(uint256 _tokenId)` function returns a timestamp when user status expires. -The `userIsBorrowed(uint256 _tokenId)` function returns whether NFT is borrowed or not. -The `supportsInterface` function MUST return `true` when called with `0xf808ec37`. -On every `transfer`, the `user` MUST be reset if the token is not borrowed. If the token is borrowed the `user` MUST stay the same. - -**The Balance extension is OPTIONAL. This gives the option to query the number of tokens a `user` has.** - -```solidity -/** - * @title IERC5501Balance - * Extension for ERC5501 which adds userBalanceOf to query how many tokens address is userOf. - * @notice the EIP-165 identifier for this interface is 0x0cb22289. - */ -interface IERC5501Balance /* is IERC5501 */{ - /** - * @notice Count of all NFTs assigned to a user. - * @dev Reverts if user is zero address. - * @param _user an address for which to query the balance - * @return uint256 the number of NFTs the user has - */ - function userBalanceOf(address _user) external view returns (uint256); -} -``` - -The `userBalanceOf(address _user)` function SHOULD `revert` for zero address. - -**The Enumerable extension is OPTIONAL. This allows to iterate over user balance.** - -```solidity -/** - * @title IERC5501Enumerable - * This extension for ERC5501 adds the option to iterate over user tokens. - * @notice the EIP-165 identifier for this interface is 0x1d350ef8. - */ -interface IERC5501Enumerable /* is IERC5501Balance, IERC5501 */ { - /** - * @notice Enumerate NFTs assigned to a user. - * @dev Reverts if user is zero address or _index >= userBalanceOf(_owner). - * @param _user an address to iterate over its tokens - * @return uint256 the token ID for given index assigned to _user - */ - function tokenOfUserByIndex(address _user, uint256 _index) external view returns (uint256); -} -``` - -The `tokenOfUserByIndex(address _user, uint256 _index)` function SHOULD `revert` for zero address and `throw` if the index is larger than or equal to `user` balance. - -**The Terminable extension is OPTIONAL. This allows terminating the rent early if both parties agree.** - -```solidity -/** - * @title IERC5501Terminable - * This extension for ERC5501 adds the option to terminate borrowing if both parties agree. - * @notice the EIP-165 identifier for this interface is 0x6a26417e. - */ -interface IERC5501Terminable /* is IERC5501 */ { - /** - * @dev Emitted when one party from borrowing contract approves termination of agreement. - * @param _isLender true for lender, false for borrower - */ - event AgreeToTerminateBorrow(uint256 indexed _tokenId, address indexed _party, bool _isLender); - - /** - * @dev Emitted when agreements to terminate borrow are reset. - */ - event ResetTerminationAgreements(uint256 indexed _tokenId); - - /** - * @dev Emitted when borrow of token ID is terminated. - */ - event TerminateBorrow(uint256 indexed _tokenId, address indexed _lender, address indexed _borrower, address _caller); - - /** - * @notice Agree to terminate a borrowing. - * @dev Lender must be ownerOf token ID. Borrower must be userOf token ID. - * If lender and borrower are the same, set termination agreement for both at once. - * @param _tokenId uint256 ID of the token to set termination info for - */ - function setBorrowTermination(uint256 _tokenId) external; - - /** - * @notice Get if it is possible to terminate a borrow agreement. - * @param _tokenId uint256 ID of the token to get termination info for - * @return bool, bool first indicates lender agrees, second indicates borrower agrees - */ - function getBorrowTermination(uint256 _tokenId) external view returns (bool, bool); - - /** - * @notice Terminate a borrow if both parties agreed. - * @dev Both parties must have agreed, otherwise revert. - * @param _tokenId uint256 ID of the token to terminate borrow of - */ - function terminateBorrow(uint256 _tokenId) external; -} -``` - -The `AgreeToTerminateBorrow` event MUST be emitted when either the lender or borrower agrees to terminate the rent. -The `ResetTerminationAgreements` event MUST be emitted when a token is borrowed and transferred or `setUser` and `terminateBorrow` functions are called. -The `TerminateBorrow` event MUST be emitted when the rent is terminated. -The `setBorrowTermination(uint256 _tokenId)`. It MUST set an agreement from either party whichever calls the function. If the lender and borrower are the same address, it MUST assign an agreement for both parties at once. -The `getBorrowTermination(uint256 _tokenId)` returns if agreements from both parties are `true` or `false`. -The `terminateBorrow(uint256 _tokenId)` function MAY be called by anyone. It MUST `revert` if both agreements to terminate are not `true`. This function SHOULD change the `isBorrowed` flag from `true` to `false`. -On every `transfer`, the termination agreements from either party MUST be reset if the token is borrowed. - -## Rationale -The main factors influencing this standard are: - -* **[EIP-4400](./eip-4400.md) and [EIP-4907](./eip-4907.md)** -* **Allow lending and borrowing without the necessary stake or overcollateralization while owner retains ownership** -* **Leave the delegation option available** -* **Keep the number of functions in the interfaces to a minimum while achieving desired functionality** -* **Modularize additional extensions to let developers choose what they need for their project** - -### Name -The name for the additional role has been chosen to fit the purpose and to keep compatibility with EIP-4907. - -### Ownership retention -Many collections offer their owners airdrops or free minting of various tokens. This is essentially broken if the owner is lending a token by staking it into a contract (unless the contract is implementing a way to claim at least airdropped tokens). Applications can also provide different access and benefits to owner and user roles in their ecosystem. - -### Balance and Enumerable extensions -These have been chosen as OPTIONAL extensions due to the complexity of implementation based on the fact that balance is less once user status expires and there is no immediate on-chain transaction to evaluate that. In both `userBalanceOf` and `tokenOfUserByIndex` functions there must be a way to determine whether or not user status has expired. - -### Terminable extension -If the owner mistakenly sets a user with borrow status and expires to a large value they would essentially be blocked from setting the user ever again. The problem is addressed by this extension if both parties agree to terminate the user status. - -### Security -Once applications adopt the user role, it is possible to delegate ownership to hot wallet and interact with them with no fear of connecting to malicious websites. - -## Backwards Compatibility -This standard is compatible with current [EIP-721](./eip-721.md) by adding an extension function set. The new functions introduced are similar to existing functions in EIP-721 which guarantees easy adoption by developers and applications. This standard also shares similarities to [EIP-4907](./eip-4907.md) considering user role and its expiry which means applications will be able to determine the user if either of the standards is used. - -## Test Cases -Test cases can be found in the reference implementation: -* [Main contract](../assets/eip-5501/test/ERC5501Test.ts) -* [Balance extension](../assets/eip-5501/test/ERC5501BalanceTest.ts) -* [Enumerable extension](../assets/eip-5501/test/ERC5501EnumerableTest.ts) -* [Terminable extension](../assets/eip-5501/test/ERC5501TerminableTest.ts) -* [Scenario combined of all extensions](../assets/eip-5501/test/ERC5501CombinedTest.ts) - -## Reference Implementation -The reference implementation is available here: -* [Main contract](../assets/eip-5501/contracts/ERC5501.sol) -* [Balance extension](../assets/eip-5501/contracts/ERC5501Balance.sol) -* [Enumerable extension](../assets/eip-5501/contracts/ERC5501Enumerable.sol) -* [Terminable extension](../assets/eip-5501/contracts/ERC5501Terminable.sol) -* [Solution combined of all extensions](../assets/eip-5501/contracts/ERC5501Combined.sol) - -## Security Considerations -Developers implementing this standard and applications must consider all the permissions they give to users and owners. Since owner and user are both active roles at the same time, double-spending problem must be avoided. Balance extension must be implemented in such a way which will not cause any gas problems. Marketplaces should let users know if a token listed for sale is borrowed or not. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5501.md diff --git a/EIPS/eip-5505.md b/EIPS/eip-5505.md index c6fd939e9f8df1..b37bfe663046e2 100644 --- a/EIPS/eip-5505.md +++ b/EIPS/eip-5505.md @@ -1,77 +1,7 @@ --- eip: 5505 -title: EIP-1155 asset backed NFT extension -description: Extends EIP-1155 to support crucial operations for asset-backed NFTs -author: liszechung (@liszechung) -discussions-to: https://ethereum-magicians.org/t/eip-draft-erc1155-asset-backed-nft-extension/10437 -status: Draft -type: Standards Track category: ERC -created: 2022-08-18 -requires: 1155 +status: Moved --- -## Abstract -To propose an extension of smart contract interfaces for asset-backed, fractionalized projects using the [EIP-1155](./eip-1155.md) standard such that total acquisition will become possible. This proposal focuses on physical asset, where total acquisition should be able to happen. - -## Motivation -Fractionalized, asset backed NFTs face difficulty when someone wants to acquire the whole asset. For example, if someone wants to bring home a fractionalized asset, he needs to buy all NFT pieces so he will become the 100% owner. However he could not do so as it is publicly visible that someone is trying to perform a total acquisition in an open environment like Ethereum. Sellers will take advantage to set unreasonable high prices which hinders the acquisition. Or in other cases, NFTs are owned by wallets with lost keys, such that the ownership will never be a complete one. We need a way to enable potential total acquisition. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -[EIP-1155](./eip-1155.md) compliant contracts MAY implement this EIP for adding functionalities to support total acquisition. - -```solidity -//set the percentage required for any acquirer to trigger a forced sale -//set also the payment token to settle for the acquisition - -function setForcedSaleRequirement( - uint128 requiredBP, - address erc20Token -) public onlyOwner - -//set the unit price to acquire the remaining NFTs (100% - requiredBP) -//suggest to use a Time Weighted Average Price for a certain period before reaching the requiredBP -//emit ForcedSaleSet - -function setForcedSaleTWAP( - uint256 amount -) public onlyOwner - -//acquirer deposit remainingQTY*TWAP -//emit ForcedSaleFinished -//after this point, the acquirer is the new owner of the whole asset - -function execForcedSale ( - uint256 amount -) public external payable - -//burn ALL NFTs and collect funds -//emit ForcedSaleClaimed - -function claimForcedSale() -public - -event ForcedSaleSet( - bool isSet -) -event ForceSaleClaimed( - uint256 qtyBurned, - uint256 amountClaimed, - address claimer -) -``` - - -## Rationale -Native ETH is supported by via Wrapped Ether [EIP-20](./eip-20.md). -After forcedSale is set, the remaining NFTs metadata should be updated to reflect the NFTs are at most valued at the previously set TWAP price. - -## Security Considerations -The major security risks considered include -- The execution of the forcedSale is only executed by the contract owner, after a governance proposal. If there is any governance attack, the forcedSale TWAP price might be manipulated on a specific timing. The governance structure for using this extension should consider adding a **council** to safeguard the fairness of the forcedSale. -- Payment tokens are deposited into the contract account when forcedSale is executed. These tokens will then await the minority holders to withdraw on burning the NFT. There might be a potential security risk. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5505.md diff --git a/EIPS/eip-5507.md b/EIPS/eip-5507.md index 683cc10c034325..2fc8ba328eda85 100644 --- a/EIPS/eip-5507.md +++ b/EIPS/eip-5507.md @@ -1,164 +1,7 @@ --- eip: 5507 -title: Refundable Tokens -description: Adds refund functionality to EIP-20, EIP-721, and EIP-1155 tokens -author: elie222 (@elie222), Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/eip-5507-refundable-nfts/10451 -status: Review -type: Standards Track category: ERC -created: 2022-08-19 -requires: 20, 165, 721, 1155 +status: Moved --- -## Abstract - -This EIP adds refund functionality for initial token offerings to [EIP-20](./eip-20.md), [EIP-721](./eip-721.md), and [EIP-1155](./eip-1155.md). Funds are held in escrow until a predetermined time before they are claimable. Until that predetermined time passes, users can receive a refund for tokens they have purchased. - -## Motivation - -The NFT and token spaces lack accountability. For the health of the ecosystem as a whole, better mechanisms to prevent rugpulls from happening are needed. Offering refunds provides greater protection for buyers and increases legitimacy for creators. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### EIP-20 Refund Extension - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.17; - -import "ERC20.sol"; -import "ERC165.sol"; - -/// @notice Refundable EIP-20 tokens -/// @dev The EIP-165 identifier of this interface is `0xf0ca2917` -interface ERC20Refund is ERC20, ERC165 { - /// @notice Emitted when a token is refunded - /// @dev Emitted by `refund` - /// @param _sender The person that requested a refund - /// @param _amount The amount of token (in terms of the smallest divisible unit) that was refunded - event Refund( - address indexed _sender, - uint256 indexed _amount - ); - - /// @notice As long as the refund is active, refunds the user - /// @dev Make sure to check that the user has the token, and be aware of potential re-entrancy vectors - /// @param amount The `amount` to refund - function refund(uint256 amount) external; - - /// @notice Gets the refund price - /// @return _wei The amount of ether (in wei) that would be refunded for a single token unit (10**decimals smallest divisible units) - function refundOf() external view returns (uint256 _wei); - - /// @notice Gets the first block for which the refund is not active - /// @return block The first block where the token cannot be refunded - function refundDeadlineOf() external view returns (uint256 block); -} -``` - -### EIP-721 Refund Extension - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.17; - -import "ERC721.sol"; -import "ERC165.sol"; - -/// @notice Refundable EIP-721 tokens -/// @dev The EIP-165 identifier of this interface is `0xe97f3c83` -interface ERC721Refund is ERC721 /* , ERC165 */ { - /// @notice Emitted when a token is refunded - /// @dev Emitted by `refund` - /// @param _sender The person that requested a refund - /// @param _tokenId The `tokenId` that was refunded - event Refund( - address indexed _sender, - uint256 indexed _tokenId - ); - - /// @notice As long as the refund is active for the given `tokenId`, refunds the user - /// @dev Make sure to check that the user has the token, and be aware of potential re-entrancy vectors - /// @param tokenId The `tokenId` to refund - function refund(uint256 tokenId) external; - - /// @notice Gets the refund price of the specific `tokenId` - /// @param tokenId The `tokenId` to query - /// @return _wei The amount of ether (in wei) that would be refunded - function refundOf(uint256 tokenId) external view returns (uint256 _wei); - - /// @notice Gets the first block for which the refund is not active for a given `tokenId` - /// @param tokenId The `tokenId` to query - /// @return block The first block where token cannot be refunded - function refundDeadlineOf(uint256 tokenId) external view returns (uint256 block); -} -``` - -### EIP-1155 Refund Extension - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.17; - -import "ERC1155.sol"; -import "ERC165.sol"; - -/// @notice Refundable EIP-1155 tokens -/// @dev The EIP-165 identifier of this interface is `0x94029f5c` -interface ERC1155Refund is ERC1155 /* , ERC165 */ { - /// @notice Emitted when a token is refunded - /// @dev Emitted by `refund` - /// @param _sender The person that requested a refund - /// @param _tokenId The `tokenId` that was refunded - /// @param _amount The amount of `tokenId` that was refunded - event Refund( - address indexed _sender, - uint256 indexed _tokenId, - uint256 _amount - ); - - /// @notice As long as the refund is active for the given `tokenId`, refunds the user - /// @dev Make sure to check that the user has enough tokens, and be aware of potential re-entrancy vectors - /// @param tokenId The `tokenId` to refund - /// @param amount The amount of `tokenId` to refund - function refund(uint256 tokenId, uint256 amount) external; - - /// @notice Gets the refund price of the specific `tokenId` - /// @param tokenId The `tokenId` to query - /// @return _wei The amount of ether (in wei) that would be refunded for a single token - function refundOf(uint256 tokenId) external view returns (uint256 _wei); - - /// @notice Gets the first block for which the refund is not active for a given `tokenId` - /// @param tokenId The `tokenId` to query - /// @return block The first block where the token cannot be refunded - function refundDeadlineOf(uint256 tokenId) external view returns (uint256 block); -} -``` - -## Rationale - -`refundDeadlineOf` uses blocks instead of timestamps, as timestamps are less reliable than block numbers. - -The function names of `refund`, `refundOf`, and `refundDeadlineOf` were chosen to fit the naming style of EIP-20, EIP-721, and EIP-1155. - -[EIP-165](./eip-165.md) is required as introspection by DApps would be made significantly harder if it weren't. - -Custom EIP-20 tokens are not supported, as it needlessly increases complexity. - -## Backwards Compatibility - -No backward compatibility issues were found. - -## Security Considerations - -There is a potential re-entrancy risk with the `refund` function. Make sure to perform the ether transfer **after** the tokens are destroyed (i.e. obey the checks, effects, interactions pattern). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5507.md diff --git a/EIPS/eip-5516.md b/EIPS/eip-5516.md index bc9c8e7d6955a6..3306e79fcae3c4 100644 --- a/EIPS/eip-5516.md +++ b/EIPS/eip-5516.md @@ -1,186 +1,7 @@ --- eip: 5516 -title: Soulbound Multi-owner Tokens -description: An interface for non-transferable, Multi-owner NFTs binding to Ethereum accounts -author: Lucas Martín Grasso Ramos (@LucasGrasso), Matias Arazi (@MatiArazi) -discussions-to: https://ethereum-magicians.org/t/EIP-5516-soulbound-multi-token-standard/10485 -status: Review -type: Standards Track category: ERC -created: 2022-08-19 -requires: 165, 1155 +status: Moved --- -## Abstract -This EIP proposes a standard interface for non-fungible double signature Soulbound multi-tokens. Previous account-bound token standards face the issue of users losing their account keys or having them rotated, thereby losing their tokens in the process. This EIP provides a solution to this issue that allows for the recycling of SBTs. - -## Motivation -This EIP was inspired by the main characteristics of the [EIP-1155](./eip-1155.md) token and by articles in which benefits and potential use cases of Soulbound/Accountbound Tokens (SBTs) were presented. -This design also allows for batch token transfers, saving on transaction costs. Trading of multiple tokens can be built on top of this standard and it removes the need to approve individual token contracts separately. It is also easy to describe and mix multiple fungible or non-fungible token types in a single contract. - -### Characteristics -- The NFT will be non-transferable after the initial transfer -- Partially compatible with [EIP-1155](./eip-1155.md) -- Double Signature -- Multi-Token -- Multi-Owner -- Semi-Fungible - -### Applications -- Academic Degrees -- Code audits -- POAPs (Proof of Attendance Protocol NFTs) - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -**Smart contracts implementing this EIP MUST implement all of the functions in the `EIP-5516` interface.** - -**Smart contracts implementing this EIP MUST implement the [EIP-165](./eip-165.md) `supportsInterface` function and and MUST return the constant value `true` if `0x8314f22b` is passed through the `interfaceID` argument. They also MUST implement the [EIP-1155](./eip-1155.md) Interface and MUST return the constant value `true` if `0xd9b67a26` is passed through the `interfaceID` argument. Furthermore, they MUST implement the [EIP-1155](./eip-1155.md) Metadata interface, and MUST return the constant value `true` if `0x0e89341c` is passed through the `interfaceID` argument.** - -_See [EIP-1155](./eip-1155.md#specification)_ - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity ^0.8.4; - -/** - @title Soulbound, Multi-Token standard. - @notice Interface of the EIP-5516 - Note: The ERC-165 identifier for this interface is 0x8314f22b. - */ - -interface IERC5516 { - /** - * @dev Emitted when `account` claims or rejects pending tokens under `ids[]`. - */ - event TokenClaimed( - address indexed operator, - address indexed account, - bool[] actions, - uint256[] ids - ); - - /** - * @dev Emitted when `from` transfers token under `id` to every address at `to[]`. - */ - event TransferMulti( - address indexed operator, - address indexed from, - address[] to, - uint256 amount, - uint256 id - ); - - /** - * @dev Get tokens owned by a given address. - */ - function tokensFrom(address from) external view returns (uint256[] memory); - - /** - * @dev Get tokens awaiting to be claimed by a given address. - */ - function pendingFrom(address from) external view returns (uint256[] memory); - - /** - * @dev Claims or Reject pending `id`. - * - * Requirements: - * - `account` must have a pending token under `id` at the moment of call. - * - `account` must not own a token under `id` at the moment of call. - * - * Emits a {TokenClaimed} event. - * - */ - function claimOrReject( - address account, - uint256 id, - bool action - ) external; - - /** - * @dev Claims or Reject pending tokens under `ids[]`. - * - * Requirements for each `id` `action` pair: - * - `account` must have a pending token under `id` at the moment of call. - * - `account` must not own a token under `id` at the moment of call. - * - * Emits a {TokenClaimed} event. - * - */ - function claimOrRejectBatch( - address account, - uint256[] memory ids, - bool[] memory actions - ) external; - - /** - * @dev Transfers `id` token from `from` to every address at `to[]`. - * - * Requirements: - * - * - `from` MUST be the creator(minter) of `id`. - * - All addresses in `to[]` MUST be non-zero. - * - All addresses in `to[]` MUST have the token `id` under `_pendings`. - * - All addresses in `to[]` MUST not own a token type under `id`. - * - * Emits a {TransfersMulti} event. - * - */ - function batchTransfer( - address from, - address[] memory to, - uint256 id, - uint256 amount, - bytes memory data - ) external; - -} - -``` - -## Rationale - -### SBT as an extension of EIP-1155 -We believe that Soulbound Tokens serve as a specialized subset of existing [EIP-1155](./eip-1155.md) tokens. The advantage of such a design is the seamless compatibility of SBTs with existing NFT services. Service providers can treat SBTs like NFTs and do not need to make drastic changes to their existing codebase. - -Making the standard mostly compatible with [EIP-1155](./eip-1155.md) also allows for SBTs to bind to multiple addresses and to Smart Contracts. - -### Double-Signature -The Double-Signature functionality was implemented to prevent the receipt of unwanted tokens. It symbolizes a handshake between the token receiver and sender, implying that **both** parties agree on the token transfer. - -### Metadata. -The [EIP-1155](./eip-1155.md#metadata) Metadata Interface was implemented for further compatibility with [EIP-1155](./eip-1155.md). - -### Guaranteed log trace -> As the Ethereum ecosystem continues to grow, many DApps are relying on traditional databases and explorer API services to retrieve and categorize data. The EIP-1155 standard guarantees that event logs emitted by the smart contract will provide enough data to create an accurate record of all current token balances. A database or explorer may listen to events and be able to provide indexed and categorized searches of every EIP-1155 token in the contract. - -_Quoted from [EIP-1155](./eip-1155.md#guaranteed-log-trace)_ - -This EIP extends this concept to the Double Signature functionality: The `{TokenClaimed}` event logs all the necessary information of a `ClaimOrReject(...)` or `ClaimOrRejectBatch(...)` function call, storing relevant information about the actions performed by the user. This also applies to the `batchTransfer(...)` function: It emits the `{TransferMulti}` event and logs necessary data. - -### Exception handling -Given the non-transferability property of SBTs, if a user's keys to an account get compromised or rotated, such user may lose the ability to associate themselves with the token. - -**Given the multi-owner characteristic of [EIP-1155](./eip-1155.md) compliant interfaces and contracts, SBTs will be able to bind to multiple accounts, providing a potential solution to the issue.** - -Multi-owner SBTs can also be issued to a contract account that implements a multi-signature functionality (As recommended in [EIP-4973](./eip-4973.md#exception-handling)); this can be achieved via the [EIP-1155](./eip-1155.md#erc-1155-token-receiver) Token Receiver interface. - -### Multi-token -The multi-token functionality permits the implementation of multiple token types in the same contract. Furthermore, all emitted tokens are stored in the same contract, preventing redundant bytecode from being deployed to the blockchain. It also facilitates transfer to token issuers, since all issued tokens are stored and can be accessed under the same contract address. - -### The `batchTransfer` function -This EIP supports transfers to multiple recipients. This eases token transfer to a large number of addresses, making it more gas-efficient and user-friendly. - -## Backwards Compatibility -This proposal is only partially compatible with EIP-1155, because it makes tokens non-transferable after the first transfer. - -## Reference Implementation -You can find an implementation of this standard in [../assets/EIP-5516](../assets/eip-5516/ERC5516.sol). - -## Security Considerations -Needs discussion. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5516.md diff --git a/EIPS/eip-5521.md b/EIPS/eip-5521.md index e1506aa66807f2..7abf4e216bf64c 100644 --- a/EIPS/eip-5521.md +++ b/EIPS/eip-5521.md @@ -1,195 +1,7 @@ --- eip: 5521 -title: Referable NFT -description: An EIP-721 extension to construct reference relationships among NFTs -author: Saber Yu (@OniReimu), Qin Wang , Shange Fu , Shiping Chen , Sherry Xu , Jiangshan Yu -discussions-to: https://ethereum-magicians.org/t/eip-x-erc-721-referable-nft/10310 -status: Draft -type: Standards Track category: ERC -created: 2022-08-10 -requires: 165, 721 +status: Moved --- -## Abstract -This standard is an extension of [EIP-721](./eip-721.md). It proposes two referrable indicators, referring and referred, and a time-based indicator `createdTimestamp`. The relationship between each NFT forms a Directed acyclic graph (DAG). The standard allows users to query, track and analyze their relationships. - -## Motivation -Many scenarios require inheritance, reference, and extension of NFTs. For instance, an artist may develop his NFT work based on a previous NFT, or a DJ may remix his record by referring to two pop songs, etc. Proposing a referable solution for existing NFTs and enabling efficient queries on cross-references make much sense. - -By adding the `referring` indicator, users can mint new NFTs (e.g., C, D, E) by referring to existing NFTs (e.g., A, B), while `referred` enables the referred NFTs (A, B) to be aware that who has quoted it (e.g., A ← D; C ← E; B ← E, and A ← E). The `createdTimestamp` is an indicator used to show the creation time of NFTs (A, B, C, D, E). - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -`Relationship`: a structure that contains `referring`, `referred`, `createdTimestamp`, and other customized attributes such as `mapping (uint256 => address) privityOfAgreement` recording the ownerships of referred NFTs at the time the rNFTs were being created. -`referring`: an out-degree indicator, used to show the users this NFT refers to; -`referred`: an in-degree indicator, used to show the users who have refereed this NFT; -`createdTimestamp`: a time-based indicator, used to compare the timestamp of mint. - -`safeMint`: mint a new rNFT; -`setNode`: set the referring list of an rNFT and update the referred list of each one in the referring list; -`setNodeReferring`: set the referring list of an rNFT; -`setNodeReferred`: set the referred list of the given rNFTs; -`referringOf`: Get the referring list of an rNFT; -`referredOf`: Get the referred list of an rNFT. - -## Rationale -This standard is intended to establish the referable DAG for queries on cross-relationship and accordingly provide the simplest functions. It provides advantages as follows. - -*Clear ownership inheritance*: This standard extends the static NFT into a virtually extensible NFT network. Artists do not have to create work isolated from others. The ownership inheritance avoids reinventing the same wheel. - -*Incentive Compatibility*: This standard clarifies the referable relationship across different NFTs, helping to integrate multiple up-layer incentive models for both original NFT owners and new creators. - -*Easy Integration*: This standard makes it easier for the existing token standards or third-party protocols. For instance, the rNFT can be collaborating with the Top-down composible NFT (cf. [EIP-998](./eip-998.md) to build a finer-grained reference relationship, where the `Relationship` structure and the interface `IERC_rNFT` can be seamlessly stored and updated when invoking the `mint` function). Another example is that the rNFT can be applied to rentable scenarios (cf. [EIP-5006](./eip-5006.md) to build a hierarchical rental market, where multiple users can rent the same NFT during the same time or one user can rent multiple NFTs during the same duration). - -## Backwards Compatibility -This standard can be fully [EIP-721](./eip-721.md) compatible by adding an extension function set. - -## Test Cases -Truffle and Openzeppelin are required to run the following in a test network. -```node -truffle develop -rNFT = await ERC_rNFT.new("ERC_rNFT","ERC_rNFT") -rNFT.safeMint(1,[]) -rNFT.referredOf(1) -rNFT.referringOf(1) - -rNFT.safeMint(2,[1]) -rNFT.referredOf(2) -rNFT.referringOf(2) - -rNFT.safeMint(3,[1,2]) -rNFT.referredOf(2) -rNFT.referredOf(3) -rNFT.referringOf(3) - -``` - -## Reference Implementation -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.4; - -interface IERC_rNFT { - - // Logged when a node in the rNFT gets referred and changed - /// @notice Emitted when the `node` (i.e., an rNFT) is changed - event UpdateNode(uint256 indexed tokenId, address indexed owner, uint256[] _referringList, uint256[] _referredList); - - /// @notice Set the referred and referring relationship of an rNFT - /// Throws if `tokenId` is not valid rNFT - /// @param _tokenIds The list of the rNFTs that `tokenId` refers to - function setNode(uint256 tokenId, uint256[] memory _tokenIds) external; - - /// @notice Get the list of the rNFTs that `tokenId` refers to - /// Throws if `tokenId` is not valid rNFT - /// @param tokenId The rNFT of the referring list - function referringOf(uint256 tokenId) external view returns(uint256[] memory); - - /// @notice Get the list of the rNFT that refers to `tokenId` - /// Throws if `tokenId` is not valid rNFT - /// @param tokenId The rNFT of the referred list - function referredOf(uint256 tokenId) external view returns(uint256[] memory); -} -``` - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.4; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./IERC_rNFT.sol"; - -contract ERC_rNFT is ERC721, IERC_rNFT { - - struct Relationship { - uint256[] referring; // referring list - uint256[] referred; // referred list - uint256 createdTimestamp; // unix timestamp when the rNFT is being created - - // Customized attributes - // The distribution of profits complies to the aggreement when the NFT was being created regardless of the change of ownership unless specified in the agreement - // token owner address> - // mapping (uint256 => address) privityOfAgreement - } - - mapping (uint256 => Relationship) internal _relationship; - address contractOwner = address(0); - - constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) { - contractOwner = msg.sender; - } - - function safeMint(uint256 tokenId, uint256[] memory _tokenIds) public { - _safeMint(msg.sender, tokenId); - setNode(tokenId, _tokenIds); - } - - /// @notice set the referring list of an rNFT - /// Throws if `tokenId` is not a valid rNFT - /// @param _tokenIds array of rNFTs - function setNodeReferring(uint256 tokenId, uint256[] memory _tokenIds) private { - require(_isApprovedOrOwner(msg.sender, tokenId), "ERC_rNFT: transfer caller is not owner nor approved"); - if (contractOwner != msg.sender && _tokenIds.length == 0) { revert("ERC_rNFT: the referring list cannot be empty"); } - - Relationship storage relationship = _relationship[tokenId]; - relationship.referring = _tokenIds; - relationship.createdTimestamp = block.timestamp; - emit UpdateNode(tokenId, msg.sender, relationship.referring, relationship.referred); - } - - /// @notice set the referred list of an rNFT - /// Throws if `tokenId` is not a valid rNFT - /// @param _tokenIds array of rNFTs - function setNodeReferred(uint256 tokenId, uint256[] memory _tokenIds) private { - for (uint i = 0; i < _tokenIds.length; i++) { - Relationship storage relationship = _relationship[_tokenIds[i]]; - - if (relationship.createdTimestamp >= block.timestamp) { revert("ERC_rNFT: the referred rNFT needs to be a predecessor"); } // Make sure the reference complies with the timing sequence - - relationship.referred.push(tokenId); - emit UpdateNode(_tokenIds[i], ownerOf(_tokenIds[i]), relationship.referring, relationship.referred); - } - } - - /// @notice set the referred list of an rNFT and update the referring list of each one in the referred list - /// Throws if `tokenId` is not a valid rNFT - /// @param _tokenIds array of rNFTs - function setNode(uint256 tokenId, uint256[] memory _tokenIds) public virtual override { - setNodeReferring(tokenId, _tokenIds); - setNodeReferred(tokenId, _tokenIds); - } - - /// @notice Get the referring list of an rNFT - /// @param tokenId The considered rNFT - /// @return The referring list of an rNFT - function referringOf(uint256 tokenId) external view virtual override returns(uint256[] memory) { - require(_exists(tokenId), "ERC_rNFT: token ID not existed"); - return _relationship[tokenId].referring; - } - - /// @notice Get the referred list of an rNFT - /// @param tokenId The considered rNFT - /// @return The referred list of an rNFT - function referredOf(uint256 tokenId) external view virtual override returns(uint256[] memory) { - require(_exists(tokenId), "ERC_rNFT: token ID not existed"); - return _relationship[tokenId].referred; - } - - /// @dev See {IERC165-supportsInterface}. - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC_rNFT).interfaceId || super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations -The `createdTimestamp` only covers the block-level timestamp (based on block headers), which does not support fine-grained comparisons such as transaction-level. - -The change of ownership has nothing to do with the reference relationship. Normally, the distribution of profits complies to the aggreement when the NFT was being created regardless of the change of ownership unless specified in the agreement. - -In the context of collaborating with [EIP-998](./eip-998.md), referring a token will not refer its descendants by default. In the case that only a specific child token gets referred, it means the privity of contract will involve nobody other than the owner of this specific child token. Alternatively, a chain-of-reference all the way from the root token to a specific very bottom child token (from root to leaf) can be constructured and recorded in the `referring` to explicitly define the distribution of profits. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5521.md diff --git a/EIPS/eip-5528.md b/EIPS/eip-5528.md index cb822cc106a584..2573c467d35ce3 100644 --- a/EIPS/eip-5528.md +++ b/EIPS/eip-5528.md @@ -1,266 +1,7 @@ --- eip: 5528 -title: Refundable Fungible Token -description: Allows refunds for EIP-20 tokens by escrow smart contract -author: StartfundInc (@StartfundInc) -discussions-to: https://ethereum-magicians.org/t/eip-5528-refundable-token-standard/10494 -status: Final -type: Standards Track category: ERC -created: 2022-08-16 -requires: 20 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-20](./eip-20.md). This specification defines a type of escrow service with the following flow: - -- The seller issues tokens. -- The seller creates an escrow smart contract with detailed escrow information like contract addresses, lock period, exchange rate, additional escrow success conditions, etc. -- The seller funds seller tokens to the *Escrow Contract*. -- Buyers fund buyer tokens which are pre-defined in the *Escrow Contract*. -- When the escrow status meets success, the seller can withdraw buyer tokens, and buyers can withdraw seller tokens based on exchange rates. -- Buyers can withdraw (or refund) their funded token if the escrow process is failed or is in the middle of the escrow process. - -## Motivation - -Because of the pseudonymous nature of cryptocurrencies, there is no automatic recourse to recover funds that have already been paid. - -In traditional finance, trusted escrow services solve this problem. In the world of decentralized cryptocurrency, however, it is possible to implement an escrow service without a third-party arbitrator. This standard defines an interface for smart contracts to act as an escrow service with a function where tokens are sent back to the original wallet if the escrow is not completed. - -## Specification - -There are two types of contract for the escrow process: - -- *Payable Contract*: The sellers and buyers use this token to fund the *Escrow Contract*. This contract MUST override [EIP-20](./eip-20.md) interfaces. -- *Escrow Contract*: Defines the escrow policies and holds *Payable Contract*'s token for a certain period. This contract does not requires override [EIP-20](./eip-20.md) interfaces. - -### Methods - -#### `constructor` - -The *Escrow Contract* demonstrates details of escrow policies as none-mutable matter in constructor implementation. - -The *Escrow Contract* MUST define the following policies: - -- Seller token contract address -- Buyer token contract address - -The *Escrow Contract* MAY define the following policies: - -- Escrow period -- Maximum (or minimum) number of investors -- Maximum (or minimum) number of tokens to fund -- Exchange rates of seller/buyer token -- KYC verification of users - -#### `escrowFund` - -Funds `_value` amount of tokens to address `_to`. - -In the case of *Escrow Contract*: - - - `_to` MUST be the user address. - - `msg.sender` MUST be the *Payable Contract* address. - - MUST check policy validations. - -In the case of *Payable Contract*: - - - The address `_to` MUST be the *Escrow Contract* address. - - MUST call the same function of the *Escrow Contract* interface. The parameter `_to` MUST be `msg.sender` to recognize the user address in the *Escrow Contract*. - -```solidity -function escrowFund(address _to, uint256 _value) public returns (bool) -``` - -#### `escrowRefund` - -Refunds `_value` amount of tokens from address `_from`. - -In the case of *Escrow Contract*: - - - `_from` MUST be the user address. - - `msg.sender` MUST be the *Payable Contract* address. - - MUST check policy validations. - -In the case of *Payable Contract*: - - - The address `_from` MUST be the *Escrow Contract* address. - - MUST call the same function of the *Escrow Contract* interface. The parameter `_from` MUST be `msg.sender` to recognize the user address in the *Escrow Contract*. - -```solidity -function escrowRefund(address _from, uint256 _value) public returns (bool) -``` - -#### `escrowWithdraw` - -Withdraws funds from the escrow account. - -In the case of *Escrow Contract*: - - - MUST check the escrow process is completed. - - MUST send the remaining balance of seller and buyer tokens to `msg.sender`'s seller and buyer contract wallets. - -In the case of *Payable Contract*, it is optional. - -```solidity -function escrowWithdraw() public returns (bool) -``` - -### Example of interface - -This example demonstrates simple exchange of one seller and one buyer in one-to-one exchange rates. - -```solidity -pragma solidity ^0.4.20; - -interface IERC5528 { - - function escrowFund(address _to, uint256 _value) public returns (bool); - - function escrowRefund(address _from, uint256 _value) public returns (bool); - - function escrowWithdraw() public returns (bool); - -} - -contract PayableContract is IERC5528, IERC20 { - /* - General ERC20 implementations - */ - - function _transfer(address from, address to, uint256 amount) internal { - uint256 fromBalance = _balances[from]; - require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); - _balances[from] = fromBalance - amount; - _balances[to] += amount; - } - - function transfer(address to, uint256 amount) public returns (bool) { - address owner = msg.sender; - _transfer(owner, to, amount); - return true; - } - - function escrowFund(address _to, uint256 _value) public returns (bool){ - bool res = IERC5528(to).escrowFund(msg.sender, amount); - require(res, "Fund Failed"); - _transfer(msg.sender, to, amount); - return true; - } - - function escrowRefund(address _from, uint256 _value) public returns (bool){ - bool res = IERC5528(_from).escrowRefund(msg.sender, _value); - require(res, "Refund Failed"); - _transfer(_from, msg.sender, _value); - return true; - } -} - -contract EscrowContract is IERC5528 { - - enum State { Inited, Running, Success, Closed } - struct BalanceData { - address addr; - uint256 amount; - } - - address _addrSeller; - address _addrBuyer; - BalanceData _fundSeller; - BalanceData _fundBuyer; - EscrowStatus _status; - - constructor(address sellerContract, address buyerContract){ - _addrSeller = sellerContract; - _addrBuyer = buyerContract; - _status = State.Inited; - } - - function escrowFund(address _to, uint256 _value) public returns (bool){ - if(msg.sender == _addrSeller){ - require(_status.state == State.Running, "must be running state"); - _fundSeller.addr = _to; - _fundSeller.amount = _value; - _status = State.Success; - }else if(msg.sender == _addrBuyer){ - require(_status.state == State.Inited, "must be init state"); - _fundBuyer.addr = _to; - _fundBuyer.amount = _value; - _status = State.Running; - }else{ - require(false, "Invalid to address"); - } - return true; - } - - function escrowRefund(address _from, uint256 amount) public returns (bool){ - require(_status.state == State.Running, "refund is only available on running state"); - require(msg.sender == _addrBuyer, "invalid caller for refund"); - require(_fundBuyer.addr == _from, "only buyer can refund"); - require(_fundBuyer.amount >= amount, "buyer fund is not enough to refund"); - _fundBuyer.amount = _fundBuyer.amount - amount - return true; - } - - function escrowWithdraw() public returns (bool){ - require(_status.state == State.Success, "withdraw is only available on success state"); - uint256 common = MIN(_fundBuyer.amount, _fundSeller.amount); - - if(common > 0){ - _fundBuyer.amount = _fundBuyer.amount - common; - _fundSeller.amount = _fundSeller.amount - common; - - // Exchange - IERC5528(_addrSeller).transfer(_fundBuyer.addr, common); - IERC5528(_addrBuyer).transfer(_fundSeller.addr, common); - - // send back the remaining balances - if(_fundBuyer.amount > 0){ - IERC5528(_addrBuyer).transfer(_fundBuyer.addr, _fundBuyer.amount); - } - if(_fundSeller.amount > 0){ - IERC5528(_addrSeller).transfer(_fundSeller.addr, _fundSeller.amount); - } - } - - _status = State.Closed; - } - -} - -``` - -## Rationale - -The interfaces cover the escrow operation's refundable issue. - -The suggested 3 functions (`escrowFund`, `escrowRefund` and `escrowWithdraw`) are based on `transfer` function in EIP-20. - -`escrowFund` send tokens to the *Escrow Contract*. The *Escrow Contract* can hold the contract in the escrow process or reject tokens if the policy does not meet. - -`escrowRefund` can be invoked in the middle of the escrow process or when the escrow process fails. - -`escrowWithdraw` allows users (sellers and buyers) to transfer tokens from the escrow account. When the escrow process completes, the seller can get the buyer's token, and the buyers can get the seller's token. - -## Backwards Compatibility - -The *Payable Contract* which implements this EIP is fully backward compatible with the [EIP-20](./eip-20.md) specification. - -## Test Cases - -[Unit test example by truffle](../assets/eip-5528/truffule-test.js). - -This test case demonstrates the following conditions for exchanging seller/buyer tokens. - -- The exchange rate is one-to-one. -- If the number of buyers reaches 2, the escrow process will be terminated(success). -- Otherwise (not meeting success condition yet), buyers can refund (or withdraw) their funded tokens. - -## Security Considerations - -Since the *Escrow Contract* controls seller and buyer rights, flaws within the *Escrow Contract* will directly lead to unexpected behavior and potential loss of funds. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5528.md diff --git a/EIPS/eip-5539.md b/EIPS/eip-5539.md index eb3e50cac35977..8b1d1b8823dbb4 100644 --- a/EIPS/eip-5539.md +++ b/EIPS/eip-5539.md @@ -1,252 +1,7 @@ --- eip: 5539 -title: Revocation List Registry -description: Registry of revocation lists for revoking arbitrary data. -author: Philipp Bolte (@strumswell), Lauritz Leifermann (@lleifermann), Dennis von der Bey (@DennisVonDerBey) -discussions-to: https://ethereum-magicians.org/t/eip-5539-revocation-list-registry/10573 -status: Draft -type: Standards Track category: ERC -created: 2022-08-26 -requires: 712 +status: Moved --- -## Abstract -This EIP proposes a set of methods and standards for a role-based registry of indicators aimed for usage in revocations. - -## Motivation -Revocation is a universally needed construct both in the traditional centralized and decentralized credential attestation. This EIP aims to provide an interface to standardize a decentralized approach to managing and resolving revocation states in a contract registry. - -The largest problem with traditional revocation lists is the centralized aspect of them. Most of the world's CRLs rely on HTTP servers as well as caching and are therefore vulnerable to known attack vectors in the traditional web space. This aspect severely weakens the underlying strong asymmetric key architecture in current PKI systems. - -In addition, issuers in existing CRL approaches are required to host an own instance of their public revocation list, as shared or centralized instances run the risk of misusage by the controlling entity. -This incentivizes issuers to shift this responsibility to a third party, imposing the risk of even more centralization of the ecosystem (see Cloudflare, AWS). -Ideally, issuers should be able to focus on their area of expertise, including ownership of their revocable material, instead of worrying about infrastructure. - -We see value in a future of the Internet where anyone can be an issuer of verifiable information. This proposal lays the groundwork for anyone to also own the lifecycle of this information to build trust in ecosystems. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -This EIP specifies a contract called `EthereumRevocationRegistry` that is deployed once and may then be commonly used by everyone. By default, an Ethereum address **MAY** own and manage a multitude of revocation lists in a namespace that **MUST** contain the revocation states for a set of revocation keys. - -An owner of a namespace **MAY** allow delegates to manage one or more of its revocation lists. Delegates **MUST** be removable by the respective list's owner. In certain situations, an owner **MAY** also want to transfer a revocation list in a namespace and its management rights to a new owner. - -### Definitions -- `namespace`: A namespace is a representation of an Ethereum address inside the registry that corresponds to its owners address. All revocation lists within a namespace are initially owned by the namespace's owner address. -- `revocation list`: A namespace can contain a number of revocation lists. Each revocation list is identified by a unique key of the type bytes32 that can be used to address it in combination with the namespace address. -- `revocation key`: A revocation list can contain a number of revocation keys of the type bytes32. In combination with the namespace address and the revocation list key, it resolves to a boolean value that indicates whether the revocation key is revoked or not. -- `owner`: An Ethereum address that has modifying rights to revocation lists within its own and possibly foreign namespaces. An owner can give up modifying rights of revocation lists within its namespace by transferring ownership to another address. -- `delegate`: An Ethereum address that received temporary access to a revocation list in a namespace. It has to be granted by the current owner of the revocation list in question. - -### Revocation Management - -#### isRevoked -**MUST** implement a function that returns the revocation status of a particular revocation key in a namespace's revocation list. It **MAY** also respect the revocation lists revocation status. -```solidity -function isRevoked(address namespace, bytes32 list, bytes32 key) public view returns (bool); -``` - -#### changeStatus -**MUST** implement a function to change the revocation status of a particular revocation key in a namespace's revocation list -```solidity -function changeStatus(bool revoked, address namespace, bytes32 revocationList, bytes32 revocationKey) public; -``` - -#### changeStatusSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to change the revocation status of a particular revocation key in a namespace's revocation list with a raw signature. -```solidity -function changeStatusSigned(bool revoked, address namespace, bytes32 revocationList, bytes32 revocationKey, address signer, bytes calldata signature) public; -``` - -#### changeStatusDelegated -**OPTIONAL** implements a function to change the revocation status of a particular revocation key in a namespace's revocation list by a revocation list's delegate. -```solidity -function changeStatusDelegated(bool revoked, address namespace, bytes32 revocationList, bytes32 revocationKey) public; -``` - -#### changeStatusDelegatedSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to change the revocation status of a particular revocation key in a namespace's revocation list with a raw signature. -```solidity -function changeStatusDelegatedSigned(bool revoked, address namespace, bytes32 revocationList, bytes32 revocationKey, address signer, bytes calldata signature) public; -``` - -#### changeStatusesInList -**OPTIONAL** implements a function to change multiple revocation statuses in a namespace's revocation list at once. -```solidity -function changeStatusesInList(bool[] memory revoked, address namespace, bytes32 revocationList, bytes32[] memory revocationKeys) public; -``` - -#### changeStatusesInListSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to change multiple revocation statuses in a namespace's revocation list at once with a raw signature. -```solidity -function changeStatusesInListSigned(bool[] memory revoked, address namespace, bytes32 revocationList, bytes32[] memory revocationKeys, address signer, bytes calldata signature) public; -``` - -#### changeStatusesInListDelegated -**OPTIONAL** implements a function to change multiple revocation statuses in a namespace's revocation list at once by a revocation list's delegate. -```solidity -function changeStatusesInListDelegated(bool[] memory revoked, address namespace, bytes32 revocationList, bytes32[] memory revocationKeys) public; -``` - -#### changeStatusesInListDelegatedSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to change multiple revocation statuses in a namespace's revocation list at once with a raw signature generated by a revocation list's delegate. -```solidity -function changeStatusesInListDelegatedSigned(bool[] memory revoked, address namespace, bytes32 revocationList, bytes32[] memory revocationKeys, address signer, bytes calldata signature) public; -``` - -### Revocation List Management - -#### -**OPTIONAL** implements a function that returns the revocation status of a particular revocation list in a namespace. -```solidity -function listIsRevoked(address namespace, bytes32 revocationList) view public returns (bool); -``` - -#### changeListStatus -**OPTIONAL** implements a function to change the revocation of a revocation list itself. If a revocation list is revoked, all its keys are considered revoked as well. -```solidity -function changeListStatus(bool revoked, address namespace, bytes32 revocationList) public; -``` - -#### changeListStatusSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to change the revocation of a revocation list itself with a raw signature. If a revocation list is revoked, all its keys are considered revoked as well. -```solidity -function changeListStatusSigned(bool revoked, address namespace, bytes32 revocationList, address signer, bytes calldata signature) public; -``` - -### Owner management - -#### changeListOwner -**OPTIONAL** implement a function to change the revocation status of a revocation list. If a revocation list is revoked, all keys in it are considered revoked. -```solidity -function changeListOwner(address newOwner, address namespace, bytes32 revocationList) public; -``` - -#### changeListOwnerSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implement a function to change the revocation status of a revocation list with a raw signature. If a revocation list is revoked, all keys in it are considered revoked. -```solidity -function changeListOwnerSigned(address newOwner, address namespace, bytes32 revocationList, address signer, bytes calldata signature) public; -``` - -### Delegation management - -#### addListDelegate -**OPTIONAL** implements a function to add a delegate to an owner's revocation list in a namespace. -```solidity -function addListDelegate(address delegate, address namespace, bytes32 revocationList) public; -``` - -#### addListDelegateSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to add a delegate to an owner's revocation list in a namespace with a raw signature. -```solidity -function addListDelegateSigned(address delegate, address namespace, bytes32 revocationList, address signer, bytes calldata signature) public; -``` - -#### removeListDelegate -**OPTIONAL** implements a function to remove a delegate from an owner's revocation list in a namespace. -```solidity -function removeListDelegate(address delegate, address owner, bytes32 revocationList) public; -``` - -#### removeListDelegateSigned ([see Meta Transactions](#MetaTransactions)) -**OPTIONAL** implements a function to remove a delegate from an owner's revocation list in a namespace with a raw signature. -```solidity -function removeListDelegateSigned(address delegate, address namespace, bytes32 revocationList, address signer, bytes calldata signature) public; -``` - -### Events - -#### RevocationStatusChanged -**MUST** be emitted when `changeStatus`, `changeStatusSigned`, `changeStatusDelegated`, `changeStatusDelegatedSigned`, `changeStatusesInList`, `changeStatusesInListSigned`, `changeStatusesInListDelegated`, or `changeStatusesInListDelegatedSigned` was successfully executed. - -```solidity -event RevocationStatusChanged( - address indexed namespace, - bytes32 indexed revocationList, - bytes32 indexed revocationKey, - bool revoked -); -``` - -#### RevocationListOwnerChanged -**MUST** be emitted when `changeListOwner` or `changeListOwnerSigned` was successfully executed. - -```solidity -event RevocationListOwnerChanged( - address indexed namespace, - bytes32 indexed revocationList, - address indexed newOwner -); -``` - -#### RevocationListDelegateAdded -**MUST** be emitted when `addListDelegate` or `addListDelegateSigned` was successfully executed. - -```solidity -event RevocationListDelegateAdded( - address indexed namespace, - bytes32 indexed revocationList, - address indexed delegate -); -``` - -#### RevocationListDelegateRemoved -**MUST** be emitted when `removeListDelegate` or `removeListDelegateSigned` was successfully executed. - -```solidity -event RevocationListDelegateRemoved( - address indexed namespace, - bytes32 indexed revocationList, - address indexed delegate -); -``` - -#### RevocationListStatusChanged -**MUST** be emitted when `changeListStatus` or `changeListStatusSigned` was successfully executed. - -```solidity -event RevocationListStatusChanged( - address indexed namespace, - bytes32 indexed revocationlist, - bool revoked -); -``` - -### Meta Transactions - -This section uses the following terms: -- **`transaction signer`**: An Ethereum address that signs arbitrary data for the contract to execute **BUT** does not commit the transaction. -- **`transaction sender`**: An Ethereum address that takes signed data from a **transaction signer** and commits it wrapped with its own signature to the smart contract. - -An address (**transaction signer**) **MAY** be able to deliver a signed payload off-band to another address (**transaction sender**) that initiates the Ethereum interaction with the smart contract. The signed payload **MUST** be limited to be used only once ([Signed Hash](#SignedHash) + [nonces](#Nonce)). - -#### Signed Hash - -The signature of the **transaction signer** **MUST** conform [EIP-712](./eip-712.md). This helps users understand what the payload they're signing consists of & it improves the protection against replay attacks. - -#### Nonce - -This EIP **RECOMMENDS** the use of a **dedicated nonce mapping** for meta transactions. If the signature of the **transaction sender** and its meta contents are verified, the contract increases a nonce for this **transaction signer**. This effectively removes the possibility for any other sender to execute the same transaction again with another wallet. - -## Rationale - -### Why the concept of namespaces? -This provides every Ethereum address a reserved space, without the need to actively claim it in the contract. Initially addresses only have owner access in their own namespace. - -### Why does a namespace always represent the initial owner address? -The change of an owner of a list shouldn't break the link to a revocation key in it, as already existing off-chain data may depend on it. - -## Backwards Compatibility -No backward compatibility issues were found. - -## Security Considerations - -### Meta Transactions -The signature of signed transactions could potentially be replayed on different chains or deployed versions of the registry implementing this ERC. This security consideration is addressed by the usage of [EIP-712](./eip-712.md) - -### Rights Management -The different roles and their inherent permissions are meant to prevent changes from unauthorized entities. The revocation list owner should always be in complete control over its revocation list and who has writing access to it. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5539.md diff --git a/EIPS/eip-5553.md b/EIPS/eip-5553.md index b131e89e021991..65712704a35970 100644 --- a/EIPS/eip-5553.md +++ b/EIPS/eip-5553.md @@ -1,256 +1,7 @@ --- eip: 5553 -title: Representing IP and its Royalty Structure -description: A way of representing intellectual property and its respective royalty structure on chain -author: Roy Osherove (@royosherove) -discussions-to: https://ethereum-magicians.org/t/eip-5553-representing-intellectual-property-on-chain-with-royalty-rights/10551 -status: Review -type: Standards Track category: ERC -created: 2022-08-17 -requires: 20, 721 +status: Moved --- -## Abstract -This proposal introduces a generic way to represent intellectual property on chain, along with a refined royalty representation mechanism and associated metadata link. This standard is not associated with a specific type of IP and could represent many types of IP, such as musical IP, videos, books, images, and more. -The standard is kept very generic to allow the industry to evolve new ecosystems that can all rely on the same basic standard at their core. - -This standard allows market participants to: -1) Observe the canonical on-chain representation of an intellectual property -2) Discover its attached metadata -3) Discover its related royalty structure -4) This will enable building registration, licensing, and payout mechanisms for intellectual property assets in the future. - -## Motivation - -There is no accepted standard mechanism to license intellectual property or to represent it, except using traditional NFTs. However, regular NFTs only represent a collectible item use case and cannot easily represent more complicated use cases of licensing IP for different types of uses. -We can enable such licensing mechanisms if we can: - -1) Declare that IP exists, SEPARATELY from its purchase ability -2) Declare possibly multiple interested parties to be paid for such IP - -For 1, no standard exists today. - -For 2, traditional split standards exist based on NFT purchases or through mechanisms like 0xsplits. While these solve the main problem, they do not contain the ability to name multiple types of collaboration participants. - - - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**contracts that want to represent IP on chain MUST implement [EIP-721](./eip-721.md) AND this Proposal** - -This standard extends [EIP-721](./eip-721.md) with the following `IIPRepresentation` (IPR for short) interface. -Implementers of this standard **MUST** have all of the following functions: - -### royaltyPortionTokens() function -This function MUST return an array of addresses related to [EIP-20](./eip-20.md) tokens that MUST represent royalty portions to different types of interested parties. These royalty portion tokens represent a more granular and streamlined way to declare royalty splits for multiple collaboration participants for the creation of the IP. - -For example, for a musical IP, we might have two tokens representing the composition/writing/publishing royalty portion side and the recording/master side. These royalty portion tokens are distributed to the collaboration participants and can later be queried by the various holders to distribute royalties. I.e., if one holds 10% of a royalty portion token, that holder will get 10% of the financial distribution related to that type of royalty. - -### metadataURI() function -This function MUST return the URI to a metadata file containing any required metadata for the IP or an empty string. Each IP type MAY implement its metadata standard, defined separately. The file MUST be hosted in IPFS, Arweave, or other decentralized content-addressable systems in which the file's contents are not changeable without changing the URI. - -### changeMetadataURI() function -This function allows changing the metadata URI to point to a new version of the metadata file. Calling this function MUST trigger the event `MetadataChanged` in case of success. - -### ledger() function -This function MUST return the registry or registrar contract address or an EOA account that initialized the IP and associated royalty tokens. An IP representation MAY be registered in multiple places by different actors for different purposes. This function enables market participants to discover which registry mechanism is the parent of the IP and might have special access rights to manage the IP. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.9; -import '@openzeppelin/contracts/interfaces/IERC165.sol'; - - -/// -/// @dev Interface for Intellectual Property Representation -/// -interface IIPRepresentation is IERC165 { - - /// @notice Called with the new URI to an updated metadata file - /// @param _newUri - the URI pointing to a metadata file (file standard is up to the implementer) - /// @param _newFileHash - The hash of the new metadata file for future reference and verification - function changeMetadataURI(string memory _newUri, string memory _newFileHash) external ; - - /// @return array of addresses of ERC20 tokens representing royalty portion in the IP - /// @dev i.e implementing ERC5501 (IRoyaltyInterestToken interface) - function royaltyPortionTokens() external view returns (address[] memory) ; - - /// @return the address of the contract or EOA that initialized the IP registration - /// @dev i.e., a registry or registrar, to be implemented in the future - function ledger() external view returns (address) ; - - /// @return the URI of the current metadata file for the II P - function metadataURI() external view returns (string memory) ; - - /// @dev event to be triggered whenever metadata URI is changed - /// @param byAddress the addresses that triggered this operation - /// @param oldURI the URI to the old metadata file before the change - /// @param oldFileHash the hash of the old metadata file before the change - /// @param newURI the URI to the new metadata file - /// @param newFileHash the hash of the new metadata file - event MetadaDataChanged(address byAddress, string oldURI, string oldFileHash, string newURI, string newFileHash); -} -``` - - -## Rationale - -### Returning an array of EIP-20 tokens presents a more robust royalty portions structure/ - -Current royalty implementations deal only with a single type of royalty payment: NFT sales. They also only allow a single type of royalty - i.e., Music NFTs cannot pay different people in different scenarios. -In other words, currently, a royalty split works the same way no matter what type of purchase or license deal has happened for all parties involved. - -With this proposal, multiple **types** of royalty scenarios are allowed. A classic case is the music industry, in which we have writing/composition royalties and recording/master royalties. Different licensing types will pay different percentages to different parties based on context. - -In the case of a song cover, a license payment formula can be created so that that -a) Original IP's writers get paid for using the lyrics or composition of the song -b) recording artists of the original song do not get paid since their recording is not used -c) recording artists of the new IP will get paid -d) there are no writing royalties for the creators of the cover. - -Moreover, this EIP has a single structure that connects to all types of royalty types and allows finding them more easily. -Lastly, moving EIP-20 tokens around is much easier than managing an 0xsplits contract. - -### Separating the IP contract from the collectible and licensing NFTs enables scaling licensing types -By separating the canonical version of the IP from its various licensed uses (NFT purchase, streaming, usage of art and more.), this EIP introduces a path for an ecosystem of various license types and payment distributions to evolve. -In other words, when people use this scheme, they will not start by creating a music NFT or art NFT; they start by creating the IP Representation and then create types of licenses or collectibles for it, each as its own sellable NFT. - -### A single pointer to the IP's metadata -The IPR points to metadata housed in IPFS or Arweave and allows changing it and keeping track of the changes in a simple and standard way. Today the only metadata standard is NFT metadata extension, but it is impossible to know to which standard the document adheres. With different IP types, different metadata standards for different IP types can be formulated and have a simple, easy place to discover attached metadata. - -## Reference Implementation - -#### Implementing a Musical IP Representation (MIPR for short) based on IIPRepresentation -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.9; -import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; -import "./interfaces/IIPRepresentation.sol"; -import "./interfaces/Structs.sol"; - - -contract MusicalIP is ERC721, IIPRepresentation { - address public songLedger; - address public compToken; - address public recToken; - string public metadataURI; - string public fileHash; - uint256 public tokenId; - bool public activated =false; - - function supportsInterface(bytes4 interfaceId) public view virtual override( ERC721, IERC165) returns (bool) { - return - interfaceId == type(IIPRepresentation).interfaceId || - super.supportsInterface(interfaceId); - } - - function getInterfaceId() public pure returns (bytes4){ - return type(IIPRepresentation).interfaceId; - } - - constructor ( - uint256 _tokenId, - address _songLedger, - SongMintingParams memory _params, - address _compAddress, - address _recAddress - ) - ERC721(_params.shortName, _params.symbol){ - - songLedger = _songLedger; - compToken = _compAddress; - recToken = _recAddress; - metadataURI = _params.metadataUri; - fileHash = _params.fileHash; - tokenId = _tokenId; - - _safeMint(_songLedger, _tokenId); - emit Minted(_params.shortName,_songLedger,_compAddress,_recAddress,_msgSender(),tokenId,_params.metadataUri); - } - - function changeMetadataURI(string memory _newURI,string memory _newFileHash) public - { - string memory oldURI = metadataURI; - string memory oldHash = fileHash; - metadataURI = _newURI; - fileHash = _newFileHash; - - emit MetadataChanged(oldURI, oldHash,_newURI,_newFileHash); - } - - function royaltyPortionTokens() external view returns (address[] memory) { - address[] memory items = new address[](2); - items[0] = compToken; - items[1] = recToken; - return items; - } - function ledger() external view returns (address) { - return songLedger; - } - - event MetadataChanged( - string oldUri, string oldFileHash, - string newUri, string newFileHash - ); - event Minted( - string abbvName, - address ledger, - address compToken, - address recToken, - address creator, - uint256 tokenId, - string metadataUri - ); -} - - - -``` - -#### Deploying a new Musical IP using a simple song registry contract - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.9; -import "@openzeppelin/contracts/utils/Counters.sol"; -import "./MusicalIP.sol"; -import "./CompositionRoyaltyToken.sol"; -import "./RecordingRoyaltyToken.sol"; - - -contract SimpleSongLedger is IERC721Receiver { - using Counters for Counters.Counter; - Counters.Counter private mipIds; - function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) { - return IERC721Receiver.onERC721Received.selector; - } - - function mintSong(SongMintingParams memory _params) public { - CompositionRoyaltyToken comp = new CompositionRoyaltyToken(address(this),"SONGCOMP","COMP"); - RecordingRoyaltyToken rec = new RecordingRoyaltyToken(address(this),"SONGREC","REC"); - mipIds.increment(); - - MusicalIP mip = new MusicalIP( - mipIds.current(), - address(this), - _params, - address(comp), - address(rec) - ); - } -} - - -``` -## Security Considerations - -There might be potential security challenges of attackers persuading holders of royalty portion tokens to send them those tokens and gaining royalty portion in various IPRs. However, these are not specific to royalties and are a common issue with EIP-20 tokens. - -In the case of the IP registration ownership, it will be recommended that registry contracts own the IP registration, which will be non-transferrable (account bound to the registry that created it). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5553.md diff --git a/EIPS/eip-5554.md b/EIPS/eip-5554.md index eb70c862e37b8c..15be8c459edd63 100644 --- a/EIPS/eip-5554.md +++ b/EIPS/eip-5554.md @@ -1,213 +1,7 @@ --- eip: 5554 -title: NFT Legal Use, Repurposing, and Remixing -description: An interface for describing and enforcing the legal use and remix of an NFT. On-chain registry of rights, attribution and derivative links. -author: Isaac Patka (@ipatka), COALA Licensing Taskforce -discussions-to: https://ethereum-magicians.org/t/eip-5999-legal-use-sharing-repurposing-and-remixing-standard-compatible-with-creative-commons/10553 -status: Draft -type: Standards Track category: ERC -created: 2022-07-07 -requires: 5218 +status: Moved --- -## Abstract - -This EIP extends any other token standard to provide: - -* Explicit rights for the token holder related to commercial exploitation, derivative works, and reproduction; -* [EIP-5218](./eip-5218.md) interface for creating, viewing, and checking the status of licenses -* Standard format for extended license information in the token metadata; -* Standard events to track off chain creation of derivative works, commercial exploitation, and reproduction; -* On chain tracking of derivative works and reproductions -* Additional required fields in the smart contract to reference the copyright owner -* Function calls for commercial exploitation, derivative works and reproduction. - -## Motivation -NFTs still face legal uncertainty, and many now realize that the rights associated with an NFT are just as important as the NFT itself. Our goal is to help the ecosystem reach clear consensus and broad understanding of what purchasers of NFTs are acquiring in terms of copyright or other rights. - -Today, purchasing the NFT of a digital work is not the same as purchasing the copyright in that work. In most cases, the NFT does not even incorporate the digital work; it only references it via a hash. Hence, the NFT holder owns a unique digital copy of the work, but does not necessarily enjoy the right to reproduce, redistribute, or otherwise exploit that work—unless explicitly provided for by the copyright owner. It typically only includes the right to privately enjoy the work and display it publicly on social media or in virtual galleries. - -We aim to create a new set of licenses with modular terms and conditions—à la Creative Commons—in order to enable artists to increase the value of their NFT by associating additional rights to them (e.g. the right to create derivative works, or to allow for the commercial usage of the underlying works). Our solution will allow for any licensed rights to be granted, only and exclusively, to the current holders of an NFT, and to be transferred automatically to the new token holders every time the NFT is being transferred. - -An on chain registry of copyrighted material will help in discovery of the rights associated with the NFTs that have been created with this protocol. - -Our current work is drafting the legalese and technical specifications. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Every contract compliant with this EIP must implement the `IERC5554` interface: - -```solidity -pragma solidity ^0.8.0; - -interface IERC5554 is IERC5218 { - - event CommercialExploitation(uint256 _tokenId, uint256 _licenseId, string _externalUri); - event ReproductionCreated(uint256 _tokenId, uint256 _licenseId, uint256 _reproductionId, address _reproduction, uint256 _reproductionTokenId); - event DerivativeCreated(uint256 _tokenId, uint256 _licenseId, uint256 _derivativeId, address _derivative, uint256 _derivativeTokenId); - - /// @notice Retrieve the copyright owner address - /// @dev Throws unless the token exists - /// @param tokenId The identifier for the queried token - /// @return address of the copyright owner - function getCopyrightOwner(uint256 tokenId) - external - virtual - returns (address); - - /// @notice Requests to log an execution of a license - /// @dev Throws unless the token issuance conditions are met - /// @param tokenId The identifier for the queried token - /// @return uint256 tracking reproduction ID - function logReproduction(uint256 tokenId, address reproduction, uint256 reproductionTokenId) - external - virtual - returns (uint256); - - /// @notice Requests to log an executions of a license - /// @dev Throws unless the token issuance conditions are met - /// @param tokenId The identifier for the queried token - /// @return uint256 tracking derivative ID - function logDerivative(uint256 tokenId, address derivative, uint256 derivativeTokenId) - external - virtual - returns (uint256); - - /// @notice Requests to log an execution of a license - /// @dev Throws unless the commercial exploitation conditions are met - /// @param tokenId The identifier for the queried token - function logCommercialExploitation(uint256 tokenId, string calldata uri) - external; - - /// @notice Retrieve the token associated with a reproduction - /// @dev Throws unless the reproduction exists - /// @param _reproductionId The identifier for the reproduction - /// @return uint256 The identifier for the token used to generate the reproduction - function getReproductionTokenId(uint256 _reproductionId) - external - view - returns (uint256); - - /// @notice Retrieve the token associated with a reproduction - /// @dev Throws unless the reproduction exists - /// @param _reproductionId The identifier for the reproduction - /// @return uint256 The identifier for the license used to generate the reproduction - function getReproductionLicenseId(uint256 _reproductionId) - external - view - returns (uint256); - - /// @notice Retrieve the token associated with a reproduction - /// @dev Throws unless the reproduction exists - /// @param _reproductionId The identifier for the derivative work - /// @return address The address of the reproduction collection - function getReproductionCollection(uint256 _reproductionId) - external - view - returns (address); - - /// @notice Retrieve the token associated with a derivative - /// @dev Throws unless the derivative exists - /// @param _derivativeId The identifier for the derivative work - /// @return uint256 The identifier for the token used to generate the derivative work - function getDerivativeTokenId(uint256 _derivativeId) - external - view - returns (uint256); - - /// @notice Retrieve the token associated with a derivative - /// @dev Throws unless the derivative exists - /// @param _derivativeId The identifier for the derivative work - /// @return uint256 The identifier for the license used to generate the derivative work - function getDerivativeLicenseId(uint256 _derivativeId) - external - view - returns (uint256); - - /// @notice Retrieve the token associated with a derivative - /// @dev Throws unless the derivative exists - /// @param _derivativeId The identifier for the derivative work - /// @return address The address of the derivative collection - function getDerivativeCollection(uint256 _derivativeId) - external - view - returns (address); - -} -``` - - - -### Token based Attribution/ Remix -On chain derivative works and reproductions -* Reproductions and derivative works are tracked in the contract. - - -### Event based attribution -For commercial exploitation or other off-chain uses of a creative work, this EIP defines events to be emitted to track the use of the work. - -```solidity -event CommercialExploitation(uint256 tokenID, string uri) - -function logCommercialExploitation(uint256 tokenId, string calldata uri) external returns bool; -``` - -#### Example: -When a token holder uses an NFT for off-chain merchandise, log a reference to the off-chain work in the event uri - -### Required fields - -```solifity -function copyrightOwner(uint256 tokenId) external returns address; -``` - -Copyright owner per tokenID. Could just be the tokenID owner in a simple use case, or something else if desired by the creator. - -## Rationale -We expand here upon the Motivation section to justify every decision made with regard to the specs of the standard: - -The `getLicenseId()` function takes a tokenID as a parameter, making it possible for different tokenID to be associated with different licensing terms. - -LicenseURI links to a content-addressed file that stipulates the terms and conditions of the license in actual legal language, so that the license can be read and understood by those who want to understand which rights are associated with the work of authorship, and which additional rights are granted through the acquisition of the NFT. - -When the license allows for the reproduction and/or for the creation of a derivative work only to the token holders, there needs to be a way to verify that the new NFT or the derivative NFT was created legitimately. The standard ensures this by enabling the current token holder to call a function, e.g. logDerivative which checks that the caller has a valid license to execute - -For commercial exploitation or other off-chain uses of a creative work, the standard implements the `logCommercialExploitation()` that makes it possible to keep track of which commercial exploitations have been made, and when. This makes it possible to verify that all commercial exploitation were legitimately done. - -The standard introduces a new field, `copyrightOwner`, which indicates the address of the current holder of the copyright in the work. If multiple copyright owners exist, a multisig address (or DAO) can be used. - -The artist address is not registered as an on-chain variable, but rather as part of the metadata, because it is an immutable field. - -If any, the parents of the work (i.e. the works that it is derived upon) must be part of the metadata information, so that people can verify that the NFT has obtained a DerivativeWork for each one of its parents. - -This licensing framework is intended to create a system to facilitate the licensing of rights that “follow the token” through a public licensing framework. This is not meant to be used for cases in which an exclusive right is licensed through a personal license to a specific actor (e.g. the copyright owner providing a third-party with the right to commercially exploit the work, regardless of whether they hold the token). This also is not designed to account for the sub-licensing case (e.g. licensing the right to one party to license third parties to engage in commercial exploitation), since this should rather be done via a personal copyright licensing scheme. - - -### Examples - -#### Bored Koalas merchandising - -Vigdís creates a PFP collection of Bored Koalas, which is subject to standard copyright restrictions: no one has the right to reproduce, distribute, communicate, commercialize or remix these works. However, she wants to give specific permissions to those who hold a NFT from the collection. She mints the collection with this EIP, introducing a conditional license that allows for the current token holder to display the Bored Koala associated with each NFT and commercialize it for the purpose of merchandising only. - -Neža has purchased one of these Bored Koalas. She wants to produce merchandising to be distributed at his blockchain conference. She goes to a print shop and asks them to make t-shirts with the Bored Koala image of the NFT she has purchased. The print shop can verify that she has the right to commercially exploit the work by verifying that they are the holder of the Bored Koala NFT, and verifying the terms of the license associated with it. (NB: this does not require a sub-license to be granted to the print shop, because the commercial exploitation implies the right to commission third parties to engage in such commercial exploitation). Neža brings the t-shirts to her conference and puts them for sale. When doing so, she calls the `logCommercialExploitation()` function from the NFT smart contract in order to track that the commercial exploitation was done at a time while she was the token holder. - -#### Musical Remix - -Matti is an up and coming songwriter in the emerging web3 music ecosystem. For the upcoming crypto conference, he creates a hit song called “Degens in the Night”. Instead of listing the song on a web2 platform, Matti mints the song as an NFT using this EIP, with a dual licensing scheme: a general public licenses that allows for the free reproduction and redistribution of the work, given proper attribution (e.g. Creative Commons BY-NC-ND) and a conditional license which allows for the token holder to remix the song, in exchange of a particular lump sum (e.g. 1ETH) and under the condition that the derivative work is released under the same licensing terms as the original work Lyyli wants to create a cover of that song, which she calls “Degens in the Parisian Night”. She purchases the NFT and mints a new derivative NFT under a new smart contract using this EIP standard. She then calls the `requestDerivativeToken()` function and send 1ETH to the original NFT smart contract, in order to request that a DerivativeToken be assigned to the new smart contract she has created. The smart contract automatically approves the request to assign a Derivative Token to the new smart contract of Lyyli. This can be used as a proof that the derivative work is indeed a legitimate work, which has been approved by the copyright owner of the original work. During the conference hundreds of other web3 music creators host a side event with Degens in the Night remixes playing until 4am. - -#### Royalties Remix - -Alice created a 3D model of a motorcycle, which she wants everyone to remix, under the condition that she gets royalty from the commercial exploitation of all derivative works. She release her work as an NFT with this EIP, with a dual licensing scheme: a general public licenses that allows for the free reproduction and redistribution of the work, given proper attribution (e.g. Creative Commons BY-NC-ND) and a conditional license which allows for the token holder to remix the song, under the condition that the derivative work is released under the same licensing terms as the original work, and that there is a split of the royalties between himself and the remixer. - -Jane wants to create a derivative work of the motorcycle. She purchases the NFT and mints a new derivative NFT under a new smart contract that uses this EIP, which includes a royalty split for Alice. She then calls the `requestDerivativeToken()` function from the original NFT smart contract in order to request that a DerivativeToken be assigned to the new smart contract she has created. Alice decided that the smart contract shall not automate the approval or rejection of the request, but rather wait for her to validate or invalidate the request, after she has verified that the design and provisions of the new smart contract, namely that it does indeed replicate the same terms and conditions as the original work and that it incorporates the proper amount of royalties. She approves the request to assign a Derivative Token to the new smart contract of Jane. When people purchase Jane’s NFT, the royalties are split to ensure the proper redistribution of the generated profit to Alice. - -## Backwards Compatibility -The interface defined in this standard is backward compatible with most NFT standards used in the Ethereum ecosystem as of this writing. - -## Security Considerations -Needs discussion. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5554.md diff --git a/EIPS/eip-5559.md b/EIPS/eip-5559.md index 868ea2a0234312..8935eaa426be98 100644 --- a/EIPS/eip-5559.md +++ b/EIPS/eip-5559.md @@ -1,471 +1,7 @@ --- eip: 5559 -title: "Cross Chain Write Deferral Protocol" -description: The cross chain write deferral protocol provides a mechanism to defer the storage & resolution of mutations to off-chain handlers -author: Paul Gauvreau (@0xpaulio), Nick Johnson (@arachnid) -discussions-to: https://ethereum-magicians.org/t/eip-cross-chain-write-deferral-protocol/10576 -status: Draft -type: Standards Track category: ERC -created: 2022-06-23 -requires: 712 +status: Moved --- -## Abstract -The following standard provides a mechanism in which smart contracts can request various tasks to be resolved by an external handler. This provides a mechanism in which protocols can reduce the gas fees associated with storing data on mainnet by deferring the handling of it to another system/network. These external handlers act as an extension to the core L1 contract. - -This standard outlines a set of handler types that can be used for managing the execution and storage of mutations (tasks), as well as their corresponding tradeoffs. Each handler type has associated operational costs, finality guarantees, and levels of decentralization. By further specifying the type of handler that the mutation is deferred to, the protocol can better define how to permission and secure their system. - -This standard can be implemented in conjunction with [EIP-3668](./eip-3668) to provide a mechanism in which protocols can reside on and be interfaced through an L1 contract on mainnet, while being able to resolve and mutate data stored in external systems. - -## Motivation -[EIP-3668](./eip-3668) provides a mechanism by which off-chain lookups can be defined inside smart contracts in a transparent manner. In addition, it provides a scheme in which the resolved data can be verified on-chain. However, there lacks a standard by which mutations can be requested through the native contract, to be performed on the off-chain data. Furthermore, with the increase in L2 solutions, smart contract engineers have additional tools that can be used to reduce the storage and transaction costs of performing mutations on the Ethereum mainnet. - -A specification that allows smart contracts to defer the storage and resolution of data to external handlers facilitates writing clients agnostic to the storage solution being used, enabling new applications that can operate without knowledge of the underlying handlers associated with the contracts they interact with. - -Examples of this include: - - Allowing the management of ENS domains externally resolved on an L2 solution or off-chain database as if they were native L1 tokens. - - Allowing the management of digital identities stored on external handlers as if they were in the stored in the native L1 smart contract. - -## Specification -### Overview -There are two main handler classifications: L2 Contract and Off-Chain Database. These are determined based off of where the handler is deployed. The handler classifications are used to better define the different security guarantees and requirements associated with its deployment. - -From a high level: -- Handlers hosted on an L2 solution are EVM compatible and can use attributes native to the Ethereum ecosystem (such as address) to permission access. -- Handlers hosted on an Off-Chain Database require additional parameters and signatures to correctly enforce the authenticity and check the validity of a request. - -A deferred mutation can be handled in as little as two steps. However, in some cases the mutation might be deferred multiple times. - -1. Querying or sending a transaction to the contract -2. Querying or sending a transaction to the handler using the parameters provided in step 1 - -In step 1, a standard blockchain call operation is made to the contract. The contract either performs the operation as intended or reverts with an error that specifies the type of handler that the mutation is being deferred to and the corresponding parameters required to perform the subsequent mutation. There are two types of errors that the contract can revert with, but more may be defined in other EIPs: - -- `StorageHandledByL2(chainId, contractAddress)` -- `StorageHandledByOffChainDatabase(sender, url, data)` - -In step 2, the client builds and performs a new request based off of the type of error received in (1). These handshakes are outlined in the sections below: - -- [StorageHandledByL2](#data-stored-in-an-l2) -- [StorageHandledByOffChainDatabase](#data-stored-in-an-off-chain-database) - -In some cases, the mutation may be deferred multiple times -- [Storage Deferred Twice L1 > L2 > Off-Chain](#data-stored-in-an-l2--an-off-chain-database) - -### Data Stored in an L1 -``` -┌──────┐ ┌───────────┐ -│Client│ │L1 Contract│ -└──┬───┘ └─────┬─────┘ - │ │ - │ somefunc(...) │ - ├─────────────────────────►│ - │ │ - │ response │ - │◄─────────────────────────┤ - │ │ -``` - -In the case in which no reversion occurs, data is stored in the L1 contract when the transaction is executed. - -### Data Stored in an L2 - -``` -┌──────┐ ┌───────────┐ ┌─────────────┐ -│Client│ │L1 Contract│ │ L2 Contract │ -└──┬───┘ └─────┬─────┘ └──────┬──────┘ - │ │ │ - │ somefunc(...) │ │ - ├────────────────────────────────────────────────────►│ │ - │ │ │ - │ revert StorageHandledByL2(chainId, contractAddress) │ │ - │◄────────────────────────────────────────────────────┤ │ - │ │ │ - │ Execute Tx [chainId] [contractAddress] [callData] │ │ - ├─────────────────────────────────────────────────────┼──────────────►│ - │ │ │ - │ response │ │ - │◄────────────────────────────────────────────────────┼───────────────┤ - │ │ │ -``` - -The call or transaction to the L1 contract reverts with the `StorageHandledByL2(chainId, contractAddress)` error. - -In this case, the client builds a new transaction for `contractAddress` with the original `callData` and sends it to a RPC of their choice for the corresponding `chainId`. The `chainId` parameter corresponds to an L2 Solution that is EVM compatible. - -#### Example - -Suppose a contract has the following method: - -```solidity -function setAddr(bytes32 node, address a) external; -``` - -Data for this mutations is stored and tracked on an EVM compatible L2. The contract author wants to reduce the gas fees associated with the contract, while maintaining the interoperability and decentralization of the protocol. Therefore, the mutation is deferred to a off-chain handler by reverting with the `StorageHandledByL2(chainId, contractAddress)` error. - -One example of a valid implementation of `setAddr` would be: - -```solidity -function setAddr(bytes32 node, address a) external { - revert StorageHandledByL2( - 10, - _l2HandlerContractAddress - ); -} -``` - -For example, if a contract returns the following data in an `StorageHandledByL2`: - -```text -chainId = 10 -contractAddress = 0x0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff -``` - -The user, receiving this error, creates a new transaction for the corresponding `chainId`, and builds a transaction with the original `callData` to send to `contractAddress`. The user will have to choose an RPC of their choice to send the transaction to for the corresponding `chainId`. - -### Data Stored in an Off-Chain Database -``` -┌──────┐ ┌───────────┐ ┌────────────────────┐ -│Client│ │L1 Contract│ │ Off-Chain Database │ -└──┬───┘ └─────┬─────┘ └──────────┬─────────┘ - │ │ │ - │ somefunc(...) │ │ - ├────────────────────────────────────────────────────►│ │ - │ │ │ - │ revert StorageHandledByOffChainDatabase(sender, | │ - │ urls, requestParams) │ │ - │◄────────────────────────────────────────────────────┤ │ - │ │ │ - │ HTTP Request [requestParams, signature] │ │ - ├─────────────────────────────────────────────────────┼──────────────────►│ - │ │ │ - │ response │ │ - │◄────────────────────────────────────────────────────┼───────────────────┤ - │ │ │ -``` - -The call or transaction to the L1 contract reverts with the `StorageHandledByOffChainDatabase(sender, url, data)` error. - -In this case, the client performs a HTTP POST request to the gateway service. The gateway service is defined by `url`. The body attached to the request is a JSON object that includes `sender`, `data`, and a signed copy of `data` denoted `signature`. The signature is generated according to a [EIP-712](./eip-712), in which a typed data signature is generated using domain definition, `sender`, and the message context, `data`. - -`sender` ia an ABI-encoded struct defined as: - -```solidity -/** -* @notice Struct used to define the domain of the typed data signature, defined in EIP-712. -* @param name The user friendly name of the contract that the signature corresponds to. -* @param version The version of domain object being used. -* @param chainId The ID of the chain that the signature corresponds to (ie Ethereum mainnet: 1, Goerli testnet: 5, ...). -* @param verifyingContract The address of the contract that the signature pertains to. -*/ -struct domainData { - string name; - string version; - uint64 chainId; - address verifyingContract; -} -``` - -`data` ia an abi encoded struct defined as: - -```solidity -/** -* @notice Struct used to define the message context used to construct a typed data signature, defined in EIP-712, -* to authorize and define the deferred mutation being performed. -* @param functionSelector The function selector of the corresponding mutation. -* @param sender The address of the user performing the mutation (msg.sender). -* @param parameter[] A list of pairs defining the inputs used to perform the deferred mutation. -*/ -struct messageData { - bytes4 functionSelector; - address sender; - parameter[] parameters; - uint256 expirationTimestamp; -} - -/** -* @notice Struct used to define a parameter for Off-Chain Database Handler deferral. -* @param name The variable name of the parameter. -* @param value The string encoded value representation of the parameter. -*/ -struct parameter { - string name; - string value; -} -``` - -`signature` is generated by using the `sender` & `data` parameters to construct an [EIP-712](./eip-712) typed data signature. - -The body used in the HTTP POST request is defined as: - -```json -{ - "sender": "", - "data": "", - "signature": "" -} -``` - -#### Example - -Suppose a contract has the following method: - -```solidity -function setAddr(bytes32 node, address a) external; -``` - -Data for this mutations is stored and tracked in some kind of off-chain database. The contract author wants the user to be able to authorize and make modifications to their `Addr` without having to pay a gas fee. Therefore, the mutation is deferred to a off-chain handler by reverting with the `StorageHandledByOffChainDatabase(sender, url, data)` error. - -One example of a valid implementation of `setAddr` would be: - -```solidity -function setAddr(bytes32 node, address a) external { - IWriteDeferral.parameter[] memory params = new IWriteDeferral.parameter[](3); - - params[0].name = "node"; - params[0].value = BytesToString.bytes32ToString(node); - - params[1].name = "coin_type"; - params[1].value = Strings.toString(coinType); - - params[2].name = "address"; - params[2].value = BytesToString.bytesToString(a); - - revert StorageHandledByOffChainDatabase( - IWriteDeferral.domainData( - { - name: WRITE_DEFERRAL_DOMAIN_NAME, - version: WRITE_DEFERRAL_DOMAIN_VERSION, - chainId: 1, - verifyingContract: address(this) - } - ), - _offChainDatabaseUrl, - IWriteDeferral.messageData( - { - functionSelector: msg.sig, - sender: msg.sender, - parameters: params, - expirationTimestamp: block.timestamp + _offChainDatabaseTimeoutDuration - } - ) - ); -} -``` - -For example, if a contract reverts with the following: - -```text -StorageHandledByOffChainDatabase( - ( - "CoinbaseResolver", - "1", - 1, - 0x32f94e75cde5fa48b6469323742e6004d701409b - ), - "https://example.com/r/{sender}", - ( - 0xd5fa2b00, - 0x727f366727d3c9cc87f05d549ee2068f254b267c, - [ - ("node", "0x418ae76a9d04818c7a8001095ad01a78b9cd173ee66fe33af2d289b5dc5f4cba"), - ("coin_type", "60"), - ("address", "0x727f366727d3c9cc87f05d549ee2068f254b267c") - ], - 181 - ) -) -``` - -The user, receiving this error, constructs the typed data signature, signs it, and performs that request via a HTTP POST to `url`. - -Example HTTP POST request body including `requestParams` and `signature`: - -```json -{ - "sender": "", - "data": "", - "signature": "" -} -``` - -Note that the message could be altered could be altered in any way, shape, or form prior to signature and request. It is the backend's responsibility to correctly permission and process these mutations. From a security standpoint, this is no different then a user being able to call a smart contract with any params they want, as it is the smart contract's responsibility to permission and handle those requests. - - -### Data Stored in an L2 & an Off-Chain Database - -```text -┌──────┐ ┌───────────┐ ┌─────────────┐ ┌────────────────────┐ -│Client│ │L1 Contract│ │ L2 Contract │ │ Off-Chain Database │ -└──┬───┘ └─────┬─────┘ └──────┬──────┘ └──────────┬─────────┘ - │ │ │ │ - │ somefunc(...) │ │ │ - ├────────────────────────────────────────────────────►│ │ │ - │ │ │ │ - │ revert StorageHandledByL2(chainId, contractAddress) │ │ │ - │◄────────────────────────────────────────────────────┤ │ │ - │ │ │ │ - │ Execute Tx [chainId] [contractAddress] [callData] │ │ │ - ├─────────────────────────────────────────────────────┼──────────────►│ │ - │ │ │ │ - │ revert StorageHandledByOffChainDatabase(sender, url, data) │ │ - │◄────────────────────────────────────────────────────┼───────────────┤ │ - │ │ │ │ - │ HTTP Request {requestParams, signature} │ │ │ - ├─────────────────────────────────────────────────────┼───────────────┼───────────────────►│ - │ │ │ │ - │ response │ │ │ - │◄────────────────────────────────────────────────────┼───────────────┼────────────────────┤ - │ │ │ │ -``` - -The call or transaction to the L1 contract reverts with the `StorageHandledByL2(chainId, contractAddress)` error. - -In this case, the client builds a new transaction for `contractAddress` with the original `callData` and sends it to a RPC of their choice for the corresponding `chainId`. - -That call or transaction to the L2 contract then reverts with the `StorageHandledByOffChainDatabase(sender, url, data)` error. - -In this case, the client then performs a HTTP POST request against the gateway service. The gateway service is defined by `url`. The body attached to the request is a JSON object that includes `sender`, `data`, and `signature` -- a typed data signature corresponding to [EIP-712](./eip-712). - -### Events - -When making changes to core variables of the handler, the corresponding event MUST be emitted. This increases the transparency associated with different managerial actions. Core variables include `chainId` and `contractAddress` for L2 solutions and `url` for Off-Chain Database solutions. The events are outlined below in the WriteDeferral Interface. - -### Write Deferral Interface - -Below is a basic interface that defines and describes all of the reversion types and their corresponding parameters. - -```solidity -pragma solidity ^0.8.13; - -interface IWriteDeferral { - /*////////////////////////////////////////////////////////////// - EVENTS - //////////////////////////////////////////////////////////////*/ - - /// @notice Event raised when the default chainId is changed for the corresponding L2 handler. - event L2HandlerDefaultChainIdChanged(uint256 indexed previousChainId, uint256 indexed newChainId); - /// @notice Event raised when the contractAddress is changed for the L2 handler corresponding to chainId. - event L2HandlerContractAddressChanged(uint256 indexed chainId, address indexed previousContractAddress, address indexed newContractAddress); - - /// @notice Event raised when the url is changed for the corresponding Off-Chain Database handler. - event OffChainDatabaseHandlerURLChanged(string indexed previousUrl, string indexed newUrl); - - /*////////////////////////////////////////////////////////////// - STRUCTS - //////////////////////////////////////////////////////////////*/ - - /** - * @notice Struct used to define the domain of the typed data signature, defined in EIP-712. - * @param name The user friendly name of the contract that the signature corresponds to. - * @param version The version of domain object being used. - * @param chainId The ID of the chain that the signature corresponds to (ie Ethereum mainnet: 1, Goerli testnet: 5, ...). - * @param verifyingContract The address of the contract that the signature pertains to. - */ - struct domainData { - string name; - string version; - uint64 chainId; - address verifyingContract; - } - - /** - * @notice Struct used to define the message context used to construct a typed data signature, defined in EIP-712, - * to authorize and define the deferred mutation being performed. - * @param functionSelector The function selector of the corresponding mutation. - * @param sender The address of the user performing the mutation (msg.sender). - * @param parameter[] A list of pairs defining the inputs used to perform the deferred mutation. - */ - struct messageData { - bytes4 functionSelector; - address sender; - parameter[] parameters; - uint256 expirationTimestamp; - } - - /** - * @notice Struct used to define a parameter for off-chain Database Handler deferral. - * @param name The variable name of the parameter. - * @param value The string encoded value representation of the parameter. - */ - struct parameter { - string name; - string value; - } - - - /*////////////////////////////////////////////////////////////// - ERRORS - //////////////////////////////////////////////////////////////*/ - - /** - * @dev Error to raise when mutations are being deferred to an L2. - * @param chainId Chain ID to perform the deferred mutation to. - * @param contractAddress Contract Address at which the deferred mutation should transact with. - */ - error StorageHandledByL2( - uint256 chainId, - address contractAddress - ); - - /** - * @dev Error to raise when mutations are being deferred to an Off-Chain Database. - * @param sender the EIP-712 domain definition of the corresponding contract performing the off-chain database, write - * deferral reversion. - * @param url URL to request to perform the off-chain mutation. - * @param data the EIP-712 message signing data context used to authorize and instruct the mutation deferred to the - * off-chain database handler. - * In order to authorize the deferred mutation to be performed, the user must use the domain definition (sender) and message data - * (data) to construct a type data signature request defined in EIP-712. This signature, message data (data), and domainData (sender) - * are then included in the HTTP POST request, denoted sender, data, and signature. - * - * Example HTTP POST request: - * { - * "sender": , - * "data": , - * "signature": - * } - * - */ - error StorageHandledByOffChainDatabase( - domainData sender, - string url, - messageData data - ); -} -``` - -### Use of transactions with storage-deferral reversions -In some cases the contract might conditionally defer and handle mutations, in which case a transaction may be required. It is simple to use this method for sending transactions that may result in deferral reversions, as a client should receive the corresponding reversion while `preflighting` the transaction. - -This functionality is ideal for applications that want to allow their users to define the security guarantees and costs associated with their actions. For example, in the case of a decentralized identity profile, a user might not care if their data is decentralized and chooses to defer the handling of their records to the off-chain handler to reduce gas fees and on-chain transactions. - -## Rationale -### Use of `revert` to convey call information -[EIP-3668](./eip-3668) adopted the idea of using a `revert` to convey call information. It was proposed as a simple mechanism in which any pre-existing interface or function signature could be satisfied while maintain a mechanism to instruct and trigger an off-chain lookup. - -This is very similar for the write deferral protocol, defined in this EIP; without any modifications to the ABI or underlying EVM, `revert` provides a clean mechanism in which we can "return" a typed instruction - and the corresponding elements to complete that action - without modifying the signature of the corresponding function. This makes it easy to comply with pre-existing interfaces and infrastructure. - -### Use of multiple reversion & handler types to better define security guarantees -By further defining the class of the handler, it gives the developer increased granularity to define the characteristics and different guarantees associated storing the data off-chain. In addition, different handlers require different parameters and verification mechanisms. This is very important for the transparency of the protocol, as they store data outside of the native ethereum ecosystem. Common implementations of this protocol could include storing non-operational data in L2 solutions and off-chain databases to reduce gas fees, while maintaining open interoperability. - - -## Backwards Compatibility -Existing contracts that do not wish to use this specification are unaffected. Clients can add support for Cross Chain Write Deferrals to all contract calls without introducing any new overhead or incompatibilities. - -Contracts that require Cross Chain Write Deferrals will not function in conjunction with clients that do not implement this specification. Attempts to call these contracts from non-compliant clients will result in the contract throwing an exception that is propagated to the user. - -## Security Considerations -Deferred mutations should never resolve to mainnet ethereum. Such attempts to defer the mutation back to ETH could include hijacking attempts in which the contract developer is trying to get the user to sign and send a malicious transaction. Furthermore, when a transaction is deferred to an L2 system, it must use the original `calldata`, this prevents against potentially malicious contextual changes in the transaction. - -### Fingerprinting attacks -As all deferred mutations will include the `msg.sender` parameter in `data`, it is possible that `StorageHandledByOffChainDatabase` reversions could fingerprint wallet addresses and the corresponding IP address used to make the HTTP request. The impact of this is application-specific and something the user should understand is a risk associated with off-chain handlers. To minimize the security impact of this, we make the following recommendations: - -1. Smart contract developers should provide users with the option to resolve data directly on the network. Allowing them to enable on-chain storage provides the user with a simple cost-benefit analysis of where they would like their data to resolve and different guarantees / risks associated with the resolution location. -2. Client libraries should provide clients with a hook to override Cross Chain Write Deferral `StorageHandledByOffChainDatabase` calls - either by rewriting them to use a proxy service, or by denying them entirely. This mechanism or another should be written so as to easily facilitate adding domains to allowlists or blocklists. - -We encourage applications to be as transparent as possible with their setup and different precautions put in place. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5559.md diff --git a/EIPS/eip-5560.md b/EIPS/eip-5560.md index 668796d0f0211b..0c3abc9dc3ec23 100644 --- a/EIPS/eip-5560.md +++ b/EIPS/eip-5560.md @@ -1,125 +1,7 @@ --- eip: 5560 -title: Redeemable NFTs -description: Makes an NFT redeemable for a physical object -author: Olivier Fernandez (@fernandezOli), Frédéric Le Coidic (@FredLC29), Julien Béranger (@julienbrg) -discussions-to: https://ethereum-magicians.org/t/eip-redeemable-nft-extension/10589 -status: Draft -type: Standards Track category: ERC -created: 2022-08-30 -requires: 165, 721 +status: Moved --- -## Abstract - -The EIP is a Redeemable NFT extension which adds a `redeem` function to [EIP-721](./eip-721.md). It can be implemented when an NFT issuer wants his/her NFT to be redeemed for a physical object. - -## Motivation - -An increasing amount of NFT issuers such as artists, fine art galeries, auction houses, brands and others want to offer a physical object to the holder of a given NFT. This standard allows EIP-721 NFTs to signal reedemability. - -## Specification - -_The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119._ - -`EIP-721` compliant contracts MAY implement this EIP to provide a standard method of receiving information on redeemability. - -The NFT issuer **MUST** decide who is allowed to redeem the NFT, and restrict access to the `redeem()` function accordingly. - -Anyone **MAY** access the `isRedeemable()` function to check the redeemability status: it returns `true` when the NFT redeemable, and `false` when already redeemed. - -Third-party services that support this standard **MAY** use the `Redeem` event to listen to changes on the redeemable status of the NFT. - -Implementers of this standard **MUST** have all of the following functions: - -```solidity -import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; - -/** - * @dev Implementation of Redeemable for ERC-721s - * - */ - -interface IRedeemable is ERC165 { - /* - * ERC165 bytes to add to interface array - set in parent contract implementing this standard - * - * bytes4 private constant _INTERFACE_ID_ERC721REDEEM = 0x2f8ca953; - */ - - /// @dev This event emits when a token is redeemed. - event Redeem(address indexed from, uint256 indexed tokenId); - - /// @notice Returns the redeem status of a token - /// @param tokenId Identifier of the token. - function isRedeemable(uint256 _tokenId) external view returns (bool); - - /// @notice Redeeem a token - /// @param tokenId Identifier of the token to redeeem - function redeem(uint256 _tokenId) external; -} -``` - -The `Redeem` event is emitted when the `redeem()` function is called. - -The `supportsInterface` method **MUST** return `true` when called with `0x2f8ca953`. - -## Rationale - -When the NFT contract is deployed, the `isRedeemable()` function returns `true` by default. - -By default, the `redeem()` function visibility is public, so anyone can trigger it. It is **RECOMMENDED** to add a `require` to restrict the access: - -```solidity -require(ownerOf(tokenId) == msg.sender, "ERC721Redeemable: You are not the owner of this token"); -``` - -After the `redeem()` function is triggered, `isRedeemable()` function returns `false`. - -### `Redeem` event - -When the `redeem()` function is triggered, the following event **MUST** be emitted: - -```solidity -event Redeem(address indexed from, uint256 indexed tokenId); -``` - -## Backwards Compatibility - -This standard is compatible with EIP-721. - -## Reference Implementation - -Here's an example of an EIP-721 that includes the Redeemable extension: - -```solidity -contract ERC721Redeemable is ERC721, Redeemable { - - constructor(string memory name, string memory symbol) ERC721(name, symbol) { - } - - function isRedeemable(uint256 tokenId) public view virtual override returns (bool) { - require(_exists(tokenId), "ERC721Redeemable: Redeem query for nonexistent token"); - return super.isRedeemable(tokenId); - } - - function redeem(uint256 tokenId) public virtual override { - require(_exists(tokenId), "ERC721Redeemable: Redeem query for nonexistent token"); - require(ownerOf(tokenId) == msg.sender, "ERC721Redeemable: You are not the owner of this token"); - super.redeem(tokenId); - } - - function supportsInterface(bytes4 interfaceId) public view override(ERC721, Redeemable) returns (bool) { - return super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5560.md diff --git a/EIPS/eip-5564.md b/EIPS/eip-5564.md index c66ebf67a36f83..7be889c69831b2 100644 --- a/EIPS/eip-5564.md +++ b/EIPS/eip-5564.md @@ -1,294 +1,7 @@ --- eip: 5564 -title: Non-Interactive Stealth Address Generation -description: Stealth addresses for private transfers -author: Toni Wahrstätter (@nerolation), Matt Solomon (@mds1), Ben DiFrancesco (@apbendi), Vitalik Buterin -discussions-to: https://ethereum-magicians.org/t/eip-5566-stealth-addresses-for-smart-contract-wallets/10614 -status: Draft -type: Standards Track category: ERC -created: 2022-08-13 +status: Moved --- - -## Abstract - -This specification defines a standardized way of creating stealth addresses. This EIP enables senders of transactions/transfers to non-interactively generate private stealth addresses for their recipients that only the recipients can unlock. - -## Motivation - -The standardization of non-interactive stealth address generation holds the potential to greatly enhance the privacy capabilities of Ethereum by enabling the recipient of a transfer to remain anonymous when receiving an asset. This is achieved through the generation of a stealth address by the sender, using a shared secret between the sender and recipient. Only the recipient is able to unlock the funds at the stealth address, as they are the only ones with access to the private key required for this purpose. As a result, observers are unable to link the recipient's stealth address to their identity, preserving the privacy of the recipient and leaving only the sender with this information. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -The follow contracts are part of this specification: - -- `IERC5564Registry` stores the stealth public keys for users. This MUST be a singleton contract, with one instance per chain. - -- `IERC5565Generator` contracts are used to compute stealth addresses for a user based on a given curve. There can be many of these per chain, and for a given curve there SHOULD be one implementation per chain. Generator contracts are intended to primarily serve as reference implementations for off-chain libraries, as calling a method over HTTPS to generate a stealth address may compromise the user's privacy depending on who runs the node. - -- `IERC5564Messenger` emits events to announce when something is sent to a stealth address. This MUST be a singleton contract, with one instance per chain. - -The interface for each is specified as follows: - -### `IERC5564Registry` - -```solidity -/// @notice Registry to map an address to its stealth key information. -interface IERC5564Registry { - /// @notice Returns the stealth public keys for the given `registrant` to compute a stealth - /// address accessible only to that `registrant` using the provided `generator` contract. - /// @dev MUST return zero if a registrant has not registered keys for the given generator. - function stealthKeys(address registrant, address generator) - external - view - returns (bytes memory spendingPubKey, bytes memory viewingPubKey); - - /// @notice Sets the caller's stealth public keys for the `generator` contract. - function registerKeys(address generator, bytes memory spendingPubKey, bytes memory viewingPubKey) - external; - - /// @notice Sets the `registrant`s stealth public keys for the `generator` contract using their - /// `signature`. - /// @dev MUST support both EOA signatures and EIP-1271 signatures. - function registerKeysOnBehalf( - address registrant, - address generator, - bytes memory signature, - bytes memory spendingPubKey, - bytes memory viewingPubKey - ) external; - - /// @dev Emitted when a registrant updates their registered stealth keys. - event StealthKeyChanged( - address indexed registrant, address indexed generator, bytes spendingPubKey, bytes viewingPubKey - ); -} -``` - -### `IERC5564Generator` - -```solidity -/// @notice Interface for generating stealth addresses for keys from a given stealth address scheme. -/// @dev The Generator contract MUST have a method called `stealthKeys` that returns the recipient's -/// public keys as the correct types. The return types will vary for each generator, so a sample -/// is shown below. -interface IERC5564Generator { - /// @notice Given a `registrant`, returns all relevant data to compute a stealth address. - /// @dev MUST return all zeroes if the registrant has not registered keys for this generator. - /// @dev The returned `viewTag` MUST be the hash of the `sharedSecret`. THe hashing function used - /// is specified by the generator. - /// @dev `ephemeralPubKey` represents the ephemeral public key used by the sender. - /// @dev Intended to be used off-chain only to prevent exposing secrets on-chain. - /// @dev Consider running this against a local node, or using an off-chain library with the same - /// logic, instead of via an `eth_call` to a public RPC provider to avoid leaking secrets. - function generateStealthAddress(address registrant) - external - view - returns ( - address stealthAddress, - bytes memory ephemeralPubKey, - bytes memory sharedSecret, - bytes32 viewTag - ); - - /// @notice Returns the stealth public keys for the given `registrant`, in the types that best - /// represent the curve. - /// @dev The below is an example for the secp256k1 curve. - function stealthKeys(address registrant) - external - view - returns ( - uint256 spendingPubKeyX, - uint256 spendingPubKeyY, - uint256 viewingPubKeyX, - uint256 viewingPubKeyY - ); -} -``` - -### `IERC5564Messenger` - -```solidity -/// @notice Interface for announcing that something was sent to a stealth address. -interface IERC5564Messenger { - /// @dev Emitted when sending something to a stealth address. - /// @dev See `announce` for documentation on the parameters. - event Announcement( - bytes ephemeralPubKey, bytes32 indexed stealthRecipientAndViewTag, bytes32 metadata - ); - - /// @dev Called by integrators to emit an `Announcement` event. - /// @dev `ephemeralPubKey` represents the ephemeral public key used by the sender. - /// @dev `stealthRecipientAndViewTag` contains the stealth address (20 bytes) and the view tag (12 - /// bytes). - /// @dev `metadata` is an arbitrary field that the sender can use however they like, but the below - /// guidelines are recommended: - /// - When sending ERC-20 tokens, the metadata SHOULD include the token address as the first 20 - /// bytes, and the amount being sent as the following 32 bytes. - /// - When sending ERC-721 tokens, the metadata SHOULD include the token address as the first 20 - /// bytes, and the token ID being sent as the following 32 bytes. - function announce( - bytes memory ephemeralPubKey, - bytes32 stealthRecipientAndViewTag, - bytes32 metadata - ) external; -} -``` - -### Sample Generator Implementation - -```solidity -/// @notice Sample IERC5564Generator implementation for the secp256k1 curve. -contract Secp256k1Generator is IERC5564Generator { - /// @notice Address of this chain's registry contract. - IERC5564Registry public constant REGISTRY = IERC5564Registry(address(0)); - - /// @notice Sample implementation for parsing stealth keys on the secp256k1 curve. - function stealthKeys(address registrant) - external - view - returns ( - uint256 spendingPubKeyX, - uint256 spendingPubKeyY, - uint256 viewingPubKeyX, - uint256 viewingPubKeyY - ) - { - // Fetch the raw spending and viewing keys from the registry. - (bytes memory spendingPubKey, bytes memory viewingPubKey) = - REGISTRY.stealthKeys(registrant, address(this)); - - // Parse the keys. - assembly { - spendingPubKeyX := mload(add(spendingPubKey, 0x20)) - spendingPubKeyY := mload(add(spendingPubKey, 0x40)) - viewingPubKeyX := mload(add(viewingPubKey, 0x20)) - viewingPubKeyY := mload(add(viewingPubKey, 0x40)) - } - } - - /// @notice Sample implementation for generating stealth addresses for the secp256k1 curve. - function generateStealthAddress(address registrant, bytes memory ephemeralPrivKey) - external - view - returns ( - address stealthAddress, - bytes memory ephemeralPubKey, - bytes memory sharedSecret, - bytes32 viewTag - ) - { - // Get the ephemeral public key from the private key. - ephemeralPubKey = ecMul(ephemeralPrivKey, G); - - // Get user's parsed public keys. - ( - uint256 spendingPubKeyX, - uint256 spendingPubKeyY, - uint256 viewingPubKeyX, - uint256 viewingPubKeyY - ) = stealthKeys(registrant, address(this)); - - // Generate shared secret from sender's private key and recipient's viewing key. - sharedSecret = ecMul(ephemeralPrivKey, viewingPubKeyX, viewingPubKeyY); - bytes32 sharedSecretHash = keccak256(sharedSecret); - - // Generate view tag for enabling faster parsing for the recipient - viewTag = sharedSecretHash[0:12]; - - // Generate a point from the hash of the shared secret - bytes memory sharedSecretPoint = ecMul(sharedSecret, G); - - // Generate sender's public key from their ephemeral private key. - bytes memory stealthPubKey = ecAdd(spendingPubKeyX, spendingPubKeyY, sharedSecretPoint); - - // Compute stealth address from the stealth public key. - stealthAddress = pubkeyToAddress(stealthPubKey); - } -``` - -Stealth addresses are computed using the algorithm below, assuming elliptic curves. -Other encryption schemes such as post-quantum encryption with Kyber may need to modify this approach. - -- $G$ is the generator point of the curve. - -- Recipient has private keys $p_{view}$ and $p_{spend}$. - -- Recipient publishes corresponding public keys $P_{view}$ and $P_{spend}$ in the `IERC5564Registry`. - -- Sender generates random 32-byte entropy ephemeral private key $p_{ephemeral}$. - -- Sender passes the recipient address and $p_{ephemeral}$ to the `IERC5564Generator` contract's `generateStealthAddress` function. - -- This function performs the following computations: - - A shared secret $s$ is computed as $s = p_{ephemeral} \cdot P_{view}$. - - The secret is hashed $s_{h} = h(s)$. - - The view tag $v$ is extracted by taking the most significant 12 bytes $s_{h}[0:12]$, - - Multiplying the shared secret with the generator point $S = s \cdot G$. - - The recipient's stealth public key is computed as $P_{stealth} = P_{spend} + S$. - - The recipient's stealth address $a_{stealth}$ is computed as $\textrm{pubkeyToAddress}(P_{stealth})$. - -Sending funds now works as follows: - -- Sender uses the contract of their choice to send something to $a_{stealth}$, and provides $P_{ephemeral}$ and any other metadata to the send method. - -- The contract calls `IERC5564Messenger.announce` with $a_{stealth}$, $v$, $P_{ephemeral}$, and any metadata. - -To scan for funds, a recipient must retrieve all logs from the `IERC5564Messenger` contract. -They then check if they can compute the stealth address $P_{stealth}$ that was emitted as stealth address $a_{stealth}$ in the `Announcement`. If successful, the recipient can generate $p_{stealth}$, representing the private key that can eventually access $P_{stealth}$. - -The parsing process can be presented as follows: - -- Recipient has private keys $p_{view}$ and $p_{spend}$. - -- Recipient parses all Announcements $a_i$ performs the following operations: - -- This function performs the following computations: - - Computing the shared secret $s$ is computed as $s = a_{i, P_{ephemeral}} \cdot p_{view}$. - - Hashing the shared secret, $s_{h} = h(s)$. - - Comparing the most significant 12 bytes of the resulting hash with the view tag emitted in the event and continue if they match. - - Multiplying the shared secret with the generator point $S = s \cdot G$. - - Compute stealth public key as $P_{stealth} = P_{spend} + S$. - - The recipient's address is computed as $a_{stealth} = \textrm{pubkeyToAddress}(P_{stealth})$. - - Compare $a_{stealth}$ with the stealth address logged the emitted `Announcement` event. - -### Parsing considerations - -Usually, the recipient of a stealth address transaction has to perform the following operations to check weather he was the recipient of a certain transaction: - -- 2x ecMUL, - -- 2x HASH, - -- 1x ecADD, - -The view tags approach is introduced to reduce the parsing time by around 6x. Users only need to perform 1x ecMUL and 1x HASH (skipping 1x ecMUL, 1x ecADD and 1x HASH) for every parsed announcement. The 12 bytes length was is based on the freely available space in the first log of the `Announcement` Event. With 12 bytes as `viewTag` the probability for users to skip the remaining computations after hashing the shared secret $h(s)$ can be determined as follows: $1/(256^{12})$. This means that users can almost certainly skip the above three operations for any announcements that to do not involve them. - -## Rationale - -This EIP emerged from the need of having privacy-preserving ways to transfer ownership without revealing the recipient's identity. Tokens can reveal sensitive private information about the owner. While users might want to donate money to a specific organization/country but they might not want to reveal personal account-related information at the same time. The standardization of stealth address generation represents a significant effort for privacy: privacy-preserving solutions require standards to gain adoption, therefore it is critical to focus on generalizable ways of implementing related solutions. - -The stealth address extension standardizes a protocol for generating and locating stealth addresses, enabling the transfer of assets without the need for prior interaction with the recipient and allowing recipients to verify the receipt of a transfer without interacting with the blockchain. Importantly, stealth addresses allow the recipient of a token transfer to verify receipt while maintaining their privacy, as only the recipient is able to see that they have been the recipient of the transfer. - -The authors identify the trade-off between on- and off-chain efficiency: Although, including a Monero-like `view tags` mechanism helps recipients to parse announcements more quickly, it adds complexity to the announcement event. - -The address of the recipient and the `viewTag` MUST be included in the announcement event, allowing users to quickly verify ownership without having to query the chain for positive account balances. - -## Backwards Compatibility - -This EIP is fully backward compatible. - -## Reference Implementation - -You can find an implementation of this standard in TBD. - -## Security Considerations - -The funding of the stealth address wallet represents a known issue that might breach privacy. The wallet that funds the stealth address MUST NOT have any physical connection to the stealth address owner in order to fully leverage the privacy improvements. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5564.md diff --git a/EIPS/eip-5568.md b/EIPS/eip-5568.md index 495bf6dc8986e2..0c0502988e344c 100644 --- a/EIPS/eip-5568.md +++ b/EIPS/eip-5568.md @@ -1,68 +1,7 @@ --- eip: 5568 -title: Revert Reason for Required Actions -description: Signal to wallets that an action is needed by returning a custom revert code -author: Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/eip-5568-revert-signals/10622 -status: Review -type: Standards Track category: ERC -created: 2022-08-31 -requires: 140 +status: Moved --- -## Abstract - -This EIP introduces a minimalistic machine-readable (binary) format to signal to wallets that an action needs to be taken by the user using a well-known revert reason. This custom revert reason contains just enough data to be extendable by future EIPs and to take in arbitrary parameters (up to 64 kB of data). Example use cases could include approving a token for an exchange, sending an HTTP request, or requesting the user to rotate their keys after a certain period of time to enforce good hygiene. - -## Motivation - -Oftentimes, a smart contract needs to signal to a wallet that an action needs to be taken, such as to sign a transaction or send an HTTP request to a URL. Traditionally, this has been done by hard-coding the logic into the frontend, but this EIP allows the smart contract itself to request the action. - -This means that, for example, an exchange or a market can directly tell the wallet to approve the smart contract to spend the token, vastly simplifying the front-end code. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Custom Revert Reason - -To signal an action needs to be taken, a compliant smart contract MUST revert with the following error: - -```solidity -error WalletSignal24(uint24 instruction_id, bytes instruction_data) -``` - -The `instruction_id` of an instruction defined by an EIP MUST be its EIP number unless there are exceptional circumstances (be reasonable). An EIP MUST define exactly zero or one `instruction_id`. The structure of the instruction data for any `instruction_id` MUST be defined by the EIP that defines the `instruction_id`. - -### Responding to a Revert - -Before submitting a transaction to the mempool, it MUST be evaluated locally. If it reverts and the revert signature matches the custom error, then the following applies. - -The `instruction_id`, and `instruction_data` MUST be parsed from the revert data. The instruction SHOULD be evaluated as per the relevant EIP. If the instruction is not supported by the wallet, it MUST display an error to the user indicating that is the case. The wallet MUST then re-evaluate the transaction, except if an instruction explicitly states that the transaction MUST NOT be re-evaluated. - -If an instruction is invalid, or the `instruction_id`, and `instruction_data` cannot be parsed, then an error MUST be displayed to the user indicating that is the case. The transaction MUST NOT be re-evaluated. - -## Rationale - -This EIP was explicitly optimized for deployment gas cost and simplicity. It is expected that libraries will eventually be developed that makes sending and receiving these well-known reverts more developer-friendly. - -## Backwards Compatibility - -### Human-Readable Revert Messages - -See [Revert Reason Collisions](#revert-reason-collisions). - -### [EIP-3668](./eip-3668.md) - -EIP-3668 can be used alongside this EIP, but it uses a different mechanism than this EIP. - -## Security Considerations - -### Revert Reason Collisions - -It is unlikely that the signature of the custom error matches any custom errors in the wild. In the case that it does, no harm is caused unless the data happen to be a valid instruction, which is even more unlikely. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5568.md diff --git a/EIPS/eip-5570.md b/EIPS/eip-5570.md index 04ed1d66f1a462..de758896830d33 100644 --- a/EIPS/eip-5570.md +++ b/EIPS/eip-5570.md @@ -1,277 +1,7 @@ --- eip: 5570 -title: Digital Receipt Non-Fungible Tokens -description: Non-Fungible Tokens as digital receipts for physical purchases, where the metadata represents a JSON receipt -author: Sean Darcy (@darcys22) -discussions-to: https://ethereum-magicians.org/t/idea-standard-digital-receipts-using-erc-721/9908 -status: Review -type: Standards Track category: ERC -created: 2022-09-01 -requires: 721 +status: Moved --- -## Abstract - -This EIP proposes a standard schema for digital receipts of transactions. Digital Receipt Non-Fungible Tokens are issued by a vendor when a customer makes a purchase from their store and contains transaction details necessary for record keeping. Digital Receipt Non-Fungible Tokens extend [EIP-721](./eip-721.md) which allows for the management and ownership of unique tokens. - -## Motivation - -Purchases from online retailers include a receipt that is emailed and/or physically provided to the customer. These receipts are critical for many reasons but are provided in an analogue form which is difficult to parse by financial systems. Digital receipts have never gained traction dispite the fact that point of sales systems are already digital and the customers often want this information in their own digital systems. So we are left with a redundant Digital -> Analogue -> Digital process which requires unnecessary data entry or the use of clunky receipt-scanning applications. - -Digital receipts are relatively simple and can be specified with a schema that can be parsed into JSON or other structured formats. In addition we can prove the receipts validity by digitally signing the receipt using the vendors private keys. - -As Ethereum scales tooling will need to be developed to provide end users with features (such as receipts) already available to fiat transactions. NFTs provide a unique opportunity to link an on chain purchase with its transaction details directly through the transaction state update. If we conceptually think of a transaction as funds provided to one participant and goods provided to another, then our real life state includes two sides of a transaction, 1) Funds changing ownership and 2) goods changing ownership. NFT receipts are first class citizens of a transaction reflecting the goods changing ownership as part of the transaction state. They will bring our on chain transaction state in line with the changes happening in the real world. - -The convenience of a direct link to the transaction receipt via the transaction state is significant, other methods of distributing receipts either off chain or through smart contracts separate to the initial transaction lose this link and force the end user to manually locate the transaction details when needed. -The benefit can be demonstrated by comparing a wallet that allows a user to click through a transaction to its receipt (available immediately after purchase without any further action) verses a user needing to search through a datastore to locate a receipt for a transaction that they can see in their wallet history. - -Digital receipt as NFTs can also conceptually include other important information such as item serial numbers and delivery tracking etc. - -One of the major roadblocks to fully automating our finance world has been the difficulty in tracking transaction details. Human beings physically tracking paper receipts is archaic and NFTs on the blockchain provide a pathway for these systems to be significantly improved. - -## Specification - -Transaction Flow: - - - A customer purchases an item from an online retailer, checking out leads the customer to an option to mint a NFT. - - The smart contract provides the user with a Digital Receipt Non-Fungible Token. - - When fulfilling the order, the retailer will upload the digital receipt specified in in the JSON schema below as the metadata to the previously minted NFT. - -### Digital Receipt JSON Schema - -The JSON schema is composed of 2 parts. The root schema contains high level details of the receipt (for example Date and Vendor) and another schema for the optionally recurring line items contained in the receipt. - -#### Root Schema - -```json -{ - "id": "receipt.json#", - "description": "Receipt Schema for Digital Receipt Non-Fungible Tokens", - "type": "object", - "required": ["name", "description", "image", "receipt"], - "properties": { - "name": { - "title": "Name", - "description": "Identifies the token as a digital receipt", - "type": "string" - }, - "description": { - "title": "Description", - "description": "Brief description of a digital receipt", - "type": "string" - }, - "receipt": { - "title": "Receipt", - "description": "Details of the receipt", - "type": "object", - "required": ["id", "date", "vendor", "items"], - "properties": { - "id": { - "title": "ID", - "description": "Unique ID for the receipt generated by the vendor", - "type": "string" - }, - "date": { - "title": "Date", - "description": "Date Receipt Issued", - "type": "string", - "format": "date" - }, - "vendor": { - "title": "Vendor", - "description": "Details of the entity issuing the receipt", - "type": "object", - "required": ["name", "website"], - "properties": { - "name": { - "title": "Name", - "description": "Name of the vendor. E.g. Acme Corp", - "type": "string" - }, - "logo": { - "title": "Logo", - "description": "URL of the issuer's logo", - "type": "string", - "format": "uri" - }, - "address": { - "title": "Address", - "description": "List of strings comprising the address of the issuer", - "type": "array", - "items": { "type": "string" }, - "minItems": 2, - "maxItems": 6 - }, - "website": { - "title": "Website", - "description": "URL of the issuer's website", - "type": "string", - "format": "uri" - }, - "contact": { - "title": "Contact Details", - "description": "Details of the person to contact", - "type": "object", - "required": [], - "properties": { - "name": { - "title": "Name", - "description": "Name of the contact person", - "type": "string" - }, - "position": { - "title": "Position", - "description": "Position / Role of the contact person", - "type": "string" - }, - "tel": { - "title": "Telephone Number", - "description": "Telephone number of the contact person", - "type": "string" - }, - "email": { - "title": "Email", - "description": "Email of the contact person", - "type": "string", - "format": "email" - }, - "address": { - "title": "Address", - "description": "List of strings comprising the address of the contact person", - "type": "array", - "items": { "type": "string" }, - "minItems": 2, - "maxItems": 6 - } - } - } - } - }, - "items": { - "title": "Items", - "description": "Items included into the receipt", - "type": "array", - "minItems": 1, - "uniqueItems": true, - "items": { - "$ref": "item.json#" - } - }, - "comments": { - "title": "Comments", - "description": "Any messages/comments the issuer wishes to convey to the customer", - "type": "string" - }, - } - }, - "image": { - "title": "Image", - "description": "Viewable/Printable Image of the Digital Receipt", - "type": "string" - }, - "signature": { - "title": "Signature", - "description": "Digital signature by the vendor of receipts data", - "type": "string" - } - "extra": { - "title": "Extra", - "description": "Extra information about the business/receipt as needed", - "type": "string" - } - } -} -``` - -#### Line Items Schema - -```json -{ - "type": "object", - "id": "item.json#", - "required": ["id", "title", "date", "amount", "tax", "quantity"], - "properties": { - "id": { - "title": "ID", - "description": "Unique identifier of the goods or service", - "type": "string" - }, - "title": { - "title": "Title", - "description": "Title of the goods or service", - "type": "string" - }, - "description": { - "title": "Description", - "description": "Description of the goods or service", - "type": "string" - }, - "link": { - "title": "Link", - "description": "URL link to the web page for the product or sevice", - "type": "string", - "format": "uri" - }, - "date": { - "title": "Supply Date", - "description": "The date the goods or service were provided", - "type": "string", - "format": "date" - }, - "amount": { - "title": "Unit Price", - "description": "Unit Price per item (excluding tax)", - "type": "number" - }, - "tax": { - "title": "Tax", - "description": "Amount of tax charged for unit", - "type": "array", - "items": { - "type": "object", - "required": ["name", "rate", "amount"], - "properties": { - "name": { - "title": "Name of Tax", - "description": "GST/PST etc", - "type": "string" - }, - "rate": { - "title": "Tax Rate", - "description": "Tax rate as a percentage", - "type": "number" - }, - "amount": { - "title": "Tax Amount", - "description": "Total amount of tax charged", - "type": "number" - } - } - } - }, - "quantity": { - "title": "Quantity", - "description": "Number of units", - "type": "integer" - } - } -} -``` - -## Rationale - -The schema introduced complies with EIP-721's metadata extension, conveniently allowing previous tools for viewing NFTs to show our receipts. The new property "receipt" contains our newly provided receipt structure and the signature property optionally allows the vendor to digitally sign the receipt structure. - -## Backwards Compatibility - -This standard is an extension of EIP-721. It is compatible with both optional extensions, Metadata and Enumerable, mentioned in EIP-721. - -## Security Considerations - -The data stored in the receipt contains personally identifying information. This information should be encrypted to ensure privacy for the customer. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5570.md diff --git a/EIPS/eip-5573.md b/EIPS/eip-5573.md index 781478bf6c3f49..5658cf8bf9e2dd 100644 --- a/EIPS/eip-5573.md +++ b/EIPS/eip-5573.md @@ -1,273 +1,7 @@ --- eip: 5573 -title: Sign-In with Ethereum Capabilities, ReCaps -description: Mechanism on top of Sign-In with Ethereum for informed consent to delegate capabilities with an extensible scope mechanism -author: Oliver Terbu (@awoie), Jacob Ward (@cobward), Charles Lehner (@clehner), Sam Gbafa (@skgbafa), Wayne Chang (@wyc) -discussions-to: https://ethereum-magicians.org/t/eip-5573-siwe-recap -status: Draft -type: Standards Track category: ERC -created: 2021-07-20 -requires: 4361 +status: Moved --- -## Abstract -[EIP-4361](./eip-4361.md), or Sign-In with Ethereum (SIWE), describes how Ethereum accounts authenticate with off-chain services. This proposal, known as ReCaps, describes a mechanism on top of SIWE to give informed consent to delegate capabilities with a certain extensible scope mechanism to an authorized delegee. How a delegee authenticates against the target resource is out of scope for this specification and depends on the implementation of the target resource. - -## Motivation - -SIWE ReCaps unlock integration of protocols and/or APIs for developers by reducing user friction, onchain state and increasing security by introducing informed consent and deterministic capability objects on top of Sign-In With Ethereum (EIP-4361). - -While SIWE focuses on authenticating the Ethereum account against the service (relying party or SIWE client) initiating the SIWE flow, there is no canonical way to interact with a third-party service (resource service) on behalf of the authenticated Ethereum account. For example, a relying party might want to interact with another service on behalf of the Ethereum account, for example a service that provides data storage for the Ethereum account. This specification introduces a mechanism, that allows the service (or more generally a delegee) to combine authentication and authorization of such while preserving security and optimizing UX. - -Note, this approach is a similar mechanism to combining OpenID Connect (SIWE auth) and OAuth2 (SIWE ReCap) whereas SIWE ReCap follows an Object Capability-based approach. - -## Specification - -This specification has three different audiences: -- Web3 application developers that want to integrate ReCaps to authenticate with any protocols and APIs that support object capabilities. -- Protocol or API developers that want to learn how to define their own ReCaps. -- Wallet implementers that want to improve the UI for ReCaps. - -### Terms and Definitions - -- ReCap - A SIWE Message complying with this specification, i.e., containing at least one ReCap URI in the `Resources` section and the corresponding human-readable ReCap Statement appended to the SIWE `statement`. -- ReCap URI - A type of URI under a certain namespace that resolves to a ReCap Details Object. -- ReCap Details Object - A JSON object describing the actions and optionally the resources associated with a ReCap Capability under a certain namespace. -- Resource Service (RS) - The entity that is providing third-party services for the Ethereum account. -- SIWE Client (SC) - The entity initiating the SIWE authentication and ReCap flow. -- Relying Party (RP) - same as SC in the context of authentication. - -### Overview - -This specification defines the following: -- ReCap SIWE Extension -- ReCap Capability - - ReCap URI Scheme - - ReCap Details Object Schema -- ReCap Translation Algorithm -- ReCap Verification - -### ReCap SIWE Extension - -A ReCap is an EIP-4361 message following a specific format that allows an Ethereum account to delegate a set of ReCap Capabilities to a delegee through informed consent. Each ReCap Capability MUST be represented by an entry in the `Resources` array of the SIWE message that MUST deterministically translate the ReCap Capability in human-readable form to the `statement` field in the SIWE message using the ReCap Translation Algorithm. - -The following SIWE message fields are used to further define (or limit) the scope of all ReCap Capabilities: -- The `URI` field MUST specify the intended delegee, e.g., `https://example.com`, `did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK`. It is expected that the RS authenticates the delegee before invoking an action for the ReCap Capability. -- The `Issued At` field MUST be used to specify the issuance date of the ReCap Capabilities. -- If present, the `Expiration Time` field MUST be used as the expiration time of the ReCap Capabilities, i.e. the time at which the RS will no longer accept an invocation of the capabilities expressed in this form. -- If present, the `Not Before` field MUST be used as the time that has to expire before the RS starts accepting invocations of the capabilities expressed in the message. - -The following is a non-normative example of a SIWE message with the SIWE ReCap Extension: -```text -example.com wants you to sign in with your Ethereum account: -0x0000000000000000000000000000000000000000 - -I further authorize https://example.com to perform the following actions on my behalf: (1) example: read for any. (2) example: append, delete for my.resource.1. (3) example: append for my.resource.2, my.resource.3. - -URI: https://example.com -Version: 1 -Chain ID: 1 -Nonce: n-0S6_WzA2Mj -Issued At: 2022-06-21T12:00:00.000Z -Resources: -- urn:recap:example:eyJkZWYiOlsicmVhZCJdLCJ0YXIiOnsibXkucmVzb3VyY2UuMSI6WyJhcHBlbmQiLCJkZWxldGUiXSwibXkucmVzb3VyY2UuMiI6WyJhcHBlbmQiXSwibXkucmVzb3VyY2UuMyI6WyJhcHBlbmQiXX19 -``` - -#### ReCap Capability - -A ReCap Capability is identified by their ReCap URI that resolves to a ReCap Details Object which defines the associated actions and optional target resources. The scope of each ReCap Capability is attenuated by common fields in the SWIE message as described in the previous chapter, e.g., `URI`, `Issued At`, `Expiration Time`, `Not Before`. - -##### ReCap URI Scheme - -A ReCap URI starts with `urn:recap:` followed by the namespace discriminator, followed by `:` and the base64url-encoded payload of the ReCap Details Object. Note, the term base64url is defined in RFC4648 - Base 64 Encoding with URL and Filename Safe Alphabet. - -The following is a non-normative example of a ReCap Capability that uses the `example` namespace: -```text -urn:recap:example:eyJkZWZhdWx0QWN0aW9ucyI6WyJyZWFkIl0sInRhcmdldGVkQWN0aW9ucyI6eyJteS5yZXNvdXJjZS4xIjpbImFwcGVuZCIsImRlbGV0ZSJdLCJteS5yZXNvdXJjZS4yIjpbImFwcGVuZCJdLCJteS5yZXNvdXJjZS4zIjpbImFwcGVuZCJdfX0 -``` - -It is expected that RS implementers define their own namespace, e.g., `urn:recap:service:`. - -##### ReCap Details Object Schema - -The ReCap Details Object denotes which actions on which resources the delegee is authorized to invoke on behalf of the delegee for the validity period defined in the SIWE message. It can also contain additional information that the RS may require to verify a capability invocation. A ReCap Details Object MUST follow the following JSON Schema: - -```jsonc -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "properties": { - "def": { - "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "minItems": 1 - }, - "tar": { - "type": "object", - "patternProperties": { - "^.+$": { - "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "minItems": 1 - } - }, - "additionalProperties": false, - "minProperties": 1 - }, - "ext": { - "type": "object", - "minProperties": 1 - } - }, - "minProperties": 1, - "additionalProperties": false, - "dependentSchemas": { - "ext": { - "minProperties": 2 - } - } -} -``` - -A ReCap Details Object defines the following properties: -- `def`: (CONDITIONAL) If present, `def` MUST be a JSON array of string values with at least one entry where each value describes an action the delegee MAY invoke in the RS on behalf of the Ethereum account without tying the scope to a particular target. -- `tar`: (CONDITIONAL) If present, `tar` MUST be a JSON object with variable properties where each property is a JSON array of string values each describing an action the delegee MAY invoke in the RS on behalf of the Ethereum account on the target resource denoted by the property name. -- `ext`: (OPTIONAL) If present, `ext` MUST be a JSON object with variable properties. - -The following is a non-normative example of a ReCap Capability Object with `def`, `tar` and `ext`: -```jsonc -{ - "def":[ - "read" - ], - "tar":{ - "my.resource.1":[ - "append", - "delete" - ], - "my.resource.2":[ - "append" - ], - "my.resource.3":[ - "append" - ] - }, - "ext":{ - "parentCapability": "bafybeigk7ly3pog6uupxku3b6bubirr434ib6tfaymvox6gotaaaaaaaaa" - } -} -``` - -In the example above, the delegee is authorized to perform the action `read` independent of any resource, `append`, `delete` on resource `my.resource.1`, `append` on resource `my.resource.2` and `append` on `my.resource.3`. Note, the delegee can invoke each action individually and independently from each other in the RS. Additionally the ReCap Capability Object contains some additional information that the RS will need during verification. The responsibility for defining the structure and semantics of this data lies with the RS. - -It is expected that RS implementers define which resources they want to expose through ReCap Details Objects and which actions they want to allow users to invoke on them. - -#### ReCap Translation Algorithm - -After applying the ReCap Translation Algorithm on a given SIWE message that MAY include a pre-defined `statement`, the `recap-transformed-statement` in a ReCap SIWE message MUST conform to the following ABNF: -```text -recap-transformed-statement = statement recap-preamble 1*(" " recap-statement-entry ".") - ; see EIP-4361 for definition of input-statement -recap-preamble = "I further authorize " uri " to perform the following actions on my behalf:" - ; see EIP-4361 for definition of uri -recap-statement-entry = "(" number ") " recap-namespace ": " - recap-action *("," recap-action) "for" - ( "any" / ( recap-resource *(", " recap-resource) ) ) - ; see RFC8259 for definition of number -recap-namespace = string - ; see RFC8259 for definition of string -recap-action = string - ; see RFC8259 for definition of string -recap-resource = string - ; see RFC8259 for definition of string -``` - -The following algorithm or an algorithm that produces the same output MUST be performed to generate the SIWE ReCap Transformed Statement. - -Inputs: -- Let `uri` be the uri field of the input SIWE message conforming to EIP-4361. -- Let `recap-uris` be a non-empty array of ReCap URIs, which represent the ReCap Capabilities that are to be encoded in the SIWE message, and which contain ReCap Details Objects which conform to the ReCap Details Object Schema. -- [Optional] Let `statement` be the statement field of the input SIWE message conforming to EIP-4361. -Algorithm: -- Let `recap-transformed-statement` be an empty string value. -- If `statement` is present, do the following: - - Append the value of the `statement` field of `siwe` to `recap-transformed-statement`. - - Append a single space character `" "` to `recap-transformed-statement`. -- Append the following string to `recap-transformed-statement`: "I further authorize ". -- Append `uri` to `recap-transformed-statement`. -- Append the following string to `recap-transformed-statement`: " to perform the following actions on my behalf:". -- Let `numbering` be an integer starting with 1. -- For each entry in `recap-uris` (starting with the first entry), perform the following: - - Let `namespace` be the `namespace` in the ReCap URI entry and let `capDetails` be the base64url-decoded ReCap Details Object of the ReCap URI entry. - - Let `defaultActions` be the `def` JSON array in `capDetails`, where each value represents an action. - - If `defaultActions` is present, do the following: - - Let `actions` be the string concatenation of each action in the array with the delimiter `", "`. - - Append the string concatenation of `" ("`, `numbering`, `")"` to `recap-transformed-statement`. - - Append `namespace` concatenated with `": "` to `recap-transformed-statement`. - - Append `actions` to `recap-transformed-statement`. - - Append the string `" for any."` to `recap-transformed-statement`. - - Increase `numbering` by 1. - - Let `targetedActions` be the `tar` JSON object in `capDetails`, where each key-value pair represents the set of actions allowed for a target. - - If `targetedActions` is present, do the following: - - Let `actionSets` be an array of arrays of strings; - - For each key-value pair in `targetedActions`, ordered alphabetically by key, append the string array value to `actionSets`. - - For each array of strings `actionSet` in `actionSets`, do the following: - - Sort the strings in `actionSet` alphabetically. - - Let `actions` be the string concatenation of each action in the array with the delimiter `", "`. - - Let `targets` be the string concatenation of each key in `targetedActions` with the delimiter `", "`, for those keys such that the associated value (or any permutation of that value) is identical to `actionSet`. - - Append the string concatenation of `" ("`, `numbering`, `")"` to `recap-transformed-statement`. - - Append `namespace` concatenated with `": "` to `recap-transformed-statement`. - - Append `actions` to `recap-transformed-statement`. - - Append the string `" for "` to `recap-transformed-statement`. - - Append `targets` to `recap-transformed-statement`. - - Append the string `" ."` to `recap-transformed-statement`. - - Increase `numbering` by 1. -- Return `recap-transformed-statement`. - -#### ReCap Verification Algorithm - -The following algorithm or an algorithm that produces the same output MUST be performed to verify a SIWE ReCap. - -Inputs: -- Let `recap-siwe` be the input SIWE message conforming to EIP-4361 and this EIP. -- Let `siwe-signature` be the output of signing `recap-siwe`, as defined in EIP-4361. -Algorithm: -- Perform EIP-4361 signature verification with `recap-siwe` and `siwe-signature` as inputs. -- Let `uri` be the uri field of `recap-siwe`. -- Let `recap-uris` be an array of recap URIs taken in order from the resources field of `recap-siwe`, such that URIs which are not valid ReCap URIs are ignored. -- Let `recap-transformed-statement` be the result of performing the above `ReCap Translation Algorithm` with `uri` and `recap-uris` as input. -- Assert that the statement field of `recap-siwe` ends with `recap-transformed-statement`. - -### Implementer's Guide - -TBD - -#### Web3 Application Implementers - -TBD - -#### Wallet Implementers - -TBD - -#### Protocol or API Implementers - -TBD - -## Rationale - -TBD - -## Security Considerations - -Resource service implementer's should not consider ReCaps as bearer tokens but instead require to authenticate the delegee in addition. The process of authenticating the delegee against the resource service is out of scope of this specification and can be done in various different ways. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5573.md diff --git a/EIPS/eip-5585.md b/EIPS/eip-5585.md index bb945e4789cfcf..bdbf243ee44f3f 100644 --- a/EIPS/eip-5585.md +++ b/EIPS/eip-5585.md @@ -1,172 +1,7 @@ --- eip: 5585 -title: EIP-721 NFT Authorization -description: Allows NFT owners to authorize other users to use their NFTs. -author: Veega Labs (@VeegaLabsOfficial), Sean NG (@ngveega), Tiger (@tiger0x), Fred (@apan), Fov Cao (@fovcao) -discussions-to: https://ethereum-magicians.org/t/nft-authorization-erc721-extension/10661 -status: Draft -type: Standards Track category: ERC -created: 2022-08-15 -requires: 721 +status: Moved --- -## Abstract - -This EIP separates the [EIP-721](./eip-721.md) NFT's commercial usage rights from it's ownership to allow for the independent management of those rights. - -## Motivation - -Most NFTs have a simplified ownership verification mechanism, with a sole owner of an NFT. Under this model, other rights, such as display, or creating derivative works or distribution, are not possible to grant, limiting the value and commercialization of NFTs. Therefore, the separation of an NFT's ownership and user rights can enhance its commercial value. - -Commercial right is a broad concept based on the copyright, including the rights of copy, display, distribution, renting, commercial use, modify, reproduce and sublicense etc. With the development of the Metaverse, NFTs are becoming more diverse, with new use cases such as digital collections, virtual real estate, music, art, social media, and digital asset of all kinds. The copyright and authorization based on NFTs are becoming a potential business form. - -## Specification - -The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY” and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Contract Interface - -```solidity -interface IERC5585 { - - struct UserRecord { - address user; - string[] rights; - uint256 expires - } - - /// @notice Get all available rights of this NFT project - /// @return All the rights that can be authorized to the user - function getRights() external view returns(string[]); - - /// @notice NFT holder authorizes all the rights of the NFT to a user for a specified period of time - /// @dev The zero address indicates there is no user - /// @param tokenId The NFT which is authorized - /// @param user The user to whom the NFT is authorized - /// @param duration The period of time the authorization lasts - function authorizeUser(uint256 tokenId, address user, uint duration) external; - - /// @notice NFT holder authorizes specific rights to a user for a specified period of time - /// @dev The zero address indicates there is no user. It will throw exception when the rights are not defined by this NFT project - /// @param tokenId The NFT which is authorized - /// @param user The user to whom the NFT is authorized - /// @param rights Rights autorised to the user, such as renting, distribution or display etc - /// @param duration The period of time the authorization lasts - function authorizeUser(uint256 tokenId, address user, string[] rights, uint duration) external; - - /// @notice NFT holder extends the duration of authorization - /// @dev The zero address indicates there is no user. It will throw exception when the rights are not defined by this NFT project - /// @param tokenId The NFT which has been authorized - /// @param user The user to whom the NFT has been authorized - /// @param duration The new duration of the authorization - function extendDuration(uint256 tokenId, address user, uint duration) external; - - /// @notice NFT holder updates the rights of authorization - /// @dev The zero address indicates there is no user - /// @param tokenId The NFT which has been authorized - /// @param user The user to whom the NFT has been authorized - /// @param rights New rights autorised to the user - function updateUserRights(uint256 tokenId, address user, string[] rights) external; - - /// @notice Get the authorization expired time of the specified NFT and user - /// @dev The zero address indicates there is no user - /// @param tokenId The NFT to get the user expires for - /// @param user The user who has been authorized - /// @return The authorization expired time - function getExpires(uint256 tokenId, address user) external view returns(uint); - - /// @notice Get the rights of the specified NFT and user - /// @dev The zero address indicates there is no user - /// @param tokenId The NFT to get the rights - /// @param user The user who has been authorized - /// @return The rights has been authorized - function getUserRights(uint256 tokenId, address user) external view returns(string[]); - - /// @notice The contract owner can update the number of users that can be authorized per NFT - /// @param userLimit The number of users set by operators only - function updateUserLimit(unit256 userLimit) external onlyOwner; - - /// @notice resetAllowed flag can be updated by contract owner to control whether the authorization can be revoked or not - /// @param resetAllowed It is the boolean flag - function updateResetAllowed(bool resetAllowed) external onlyOwner; - - /// @notice Check if the token is available for authorization - /// @dev Throws if tokenId is not a valid NFT - /// @param tokenId The NFT to be checked the availability - /// @return true or false whether the NFT is available for authorization or not - function checkAuthorizationAvailability(uint256 tokenId) public view returns(bool); - - /// @notice Clear authorization of a specified user - /// @dev The zero address indicates there is no user. The function works when resetAllowed is true and it will throw exception when false - /// @param tokenId The NFT on which the authorization based - /// @param user The user whose authorization will be cleared - function resetUser(uint256 tokenId, address user) external; - - /// @notice This is an OPTIONAL function that the operator MAY call, he can set the starting time of staking as a reward of the authorization for each user - /// @dev The zero address indicates there is no user - /// @param user To which user the staking time will be set - /// @param stakingTime The starting time of the staking for each user - function updateStakingTime(address[] user, uint[] stakingTime) external; - - - /// @notice Emitted when the user of a NFT is changed or the authorization expires time is updated - /// param tokenId The NFT on which the authorization based - /// param indexed user The user to whom the NFT authorized - /// @param rights Rights autorised to the user - /// param expires The expires time of the authorization - event authorizeUser(uint256 indexed tokenId, address indexed user, string[] rights, uint expires); -} -``` - -The `getRights()` function MAY be implemented as pure and view. - -The `authorizeUser(uint256 tokenId, address user, uint duration)` function MAY be implemented as `public` or `external`. - -The `authorizeUser(uint256 tokenId, address user, string[] rights; uint duration)` function MAY be implemented as `public` or `external`. - -The `extendDuration(uint256 tokenId, address user, uint duration)` function MAY be implemented as `public` or `external`. - -The `updateUserRights(uint256 tokenId, address user, string[] rights)` function MAY be implemented as `public` or `external`. - -The `getExpires(uint256 tokenId, address user)` function MAY be implemented as `pure` or `view`. - -The `getUserRights(uint256 tokenId, address user)` function MAY be implemented as pure and view. - -The `updateUserLimit(unit256 userLimit)` function MAY be implemented as`public` or `external`. - -The `updateResetAllowed(bool resetAllowed)` function MAY be implemented as `public` or `external`. - -The `checkAuthorizationAvailability(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `resetUser(uint256 tokenId, address user)` function MAY be implemented as `public` or `external`. - -The `updateStakingTime(address[] user, uint[] stakingTime)` function MAY be implemented as `public` or `external`. - -The `authorizeUser` event MUST be emittedwhen the user of a NFT is changed or the authorization expires time is updated. - -## Rationale - -First of all, NFT contract owner can set the maximum number of authorized users to each NFT and whether the NFT owner can cancel the authorization at any time to protect the interests of the parties involved. - -Secondly, this EIP combines the functions of staking and authorization, which means the NFT contract owner can update the number of authorized users to NFT owners depending on the period of staking. The function is optional, but it is a way to protect all parties from overhype and to ensure that the price of the NFT is more accurately to match its value. - -Thirdly, there is a resetAllowed flag to control the rights between the NFT owner and the users for the contract owner. If the flag is set to true, then the NFT owner can disable usage rights of all authorized users at any time. - -Fourthly, the rights within the user record struct is used to store what rights has been authorized to a user by the NFT owner, in other words, the NFT owner can authorize a user with specific rights and update it when necessary. - -Finally, this design can be seamlessly integrated with third parties. It is an extension of EIP-721, therefore it can be easily integrated into a new NFT project. Other projects can directly interact with these interfaces and functions to implement their own types of transactions. For example, an announcement platform could use this EIP to allow all NFT owners to make authorization or deauthorization at any time. - -## Backwards Compatibility - -This standard is compatible with [EIP-721](./eip-721.md) since it is an extension of it. - -## Security Considerations - -If someone buys an NFT within the duration of an authorization, they will not have to stake anything, providing no incentive to cancel the authorization. - -To solve this problem, the authorization fee paid by the users will be held in an escrow contract for a period of time depending on the duration of the authorization. For example, if the authorization duration is 12 months and the fee in total is 10 ETH, then if the NFT is transferred after 3 months, then only 2.5 ETH would be sent and the remaining 7.5 ETH would be refunded. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5585.md diff --git a/EIPS/eip-5593.md b/EIPS/eip-5593.md index 3f68a16f430d04..49df3983be2e30 100644 --- a/EIPS/eip-5593.md +++ b/EIPS/eip-5593.md @@ -4,7 +4,7 @@ title: Restrict Ethereum Provider API Injection description: Wallet guidance for restricting Ethereum Provider API access to secure contexts for improved privacy and security for wallet users. author: Yan Zhu (@diracdeltas), Brian R. Bondy (@bbondy), Andrea Brancaleoni (@thypon), Kyle Den Hartog (@kdenhartog) discussions-to: https://ethereum-magicians.org/t/rfc-limiting-provider-object-injection-to-secure-contexts/10670 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2022-09-05 diff --git a/EIPS/eip-5604.md b/EIPS/eip-5604.md index 43b0a60a7a084f..ae82aa0b2d9afb 100644 --- a/EIPS/eip-5604.md +++ b/EIPS/eip-5604.md @@ -1,95 +1,7 @@ --- eip: 5604 -title: NFT Lien -description: Extend EIP-721 to support putting liens on NFT -author: Allen Zhou , Alex Qin , Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/creating-a-new-erc-proposal-for-nft-lien/10683 -status: Review -type: Standards Track category: ERC -created: 2022-09-05 -requires: 165, 721 +status: Moved --- -## Abstract - -This EIP introduces NFT liens, a form of security interest over an item of property to secure the recovery of liability or performance of some other obligation. It introduces an interface to place and removes a lien, plus an event. - -## Motivation - -Liens are widely used for finance use cases, such as car and property liens. An example use case for an NFT lien is for a deed. -This EIP provides an interface to implement an interface that performs the lien holding relationships. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -1. Any compliant contract MUST implement [EIP-721](./eip-721.md), and [EIP-165](./eip-165.md). - -2. Any compliant contract MUST implement the following interface: - -```solidity -interface IERC_LIEN is EIP721, EIP165 { - - /// === Events === - - /// @notice MUST be emitted when new lien is successfully placed. - /// @param tokenId the token a lien is placed on. - /// @param holder the holder of the lien. - /// @param extraParams of the original request to add the lien. - event OnLienPlaced(uint256 tokenId, address holder, bytes calldata extraParams); - - /// @notice MUST be emitted when an existing lien is successfully removed. - /// @param tokenId the token a lien was removed from. - /// @param holder the holder of the lien. - /// @param extraParams of the original request to remove the lien. - event OnLienRemoved(uint256 tokenId, address holder, bytes calldata extraParams); - - /// === CRUD === - - /// @notice The method to place a lien on a token - /// it MUST throw an error if the same holder already has a lien on the same token. - /// @param tokenId the token a lien is placed on. - /// @param holder the holder of the lien - /// @param extraParams extra data for future extension. - function addLienHolder(uint256 tokenId, address holder, bytes calldata extraParams) public; - - /// @notice The method to remove a lien on a token - /// it MUST throw an error if the holder already has a lien. - /// @param tokenId the token a lien is being removed from. - /// @param holder the holder of the lien - /// @param extraParams extra data for future extension. - function removeLienHolder(uint256 tokenId, address holder, bytes calldata extraParams) public; - - /// @notice The method to query if an active lien exists on a token. - /// it MUST throw an error if the tokenId doesn't exist or is not owned. - /// @param tokenId the token a lien is being queried for - /// @param holder the holder about whom the method is querying about lien holding. - /// @param extraParams extra data for future extension. - function hasLien(uint256 tokenId, address holder, bytes calldata extraParams) public view returns (bool); -} -``` - -## Rationale - -1. We only support [EIP-721](./eip-721.md) NFTs for simplicity and gas efficiency. We have not considered other EIPs, which can be left for future extensions. For example, [EIP-20](./eip-20.md) and [EIP-1155](./eip-1155.md) were not considered. - -2. We choose separate "addLienHolder" and "removeLienHolder" instead of use a single `changeLienholder` with amount because we believe -the add or remove action are significantly different and usually require different Access Control, -for example, the token holder shall be able to add someone else as a lien holder but the lien holder of that token. - -3. We have not specified the "amount of debt" in this interface. We believe this is complex enough and worthy of an individual EIP by itself. - -4. We have not specified how endorsement can be applied to allow holder to signal their approval for transfer or swapping. We believe this is complex enough and worthy of an individual EIP by itself. - -## Backwards Compatibility - -The EIP is designed as an extension of EIP-721 and therefore compliant contracts need to fully comply with EIP-721. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5604.md diff --git a/EIPS/eip-5606.md b/EIPS/eip-5606.md index a4307f09e8d250..488d8314532ff8 100644 --- a/EIPS/eip-5606.md +++ b/EIPS/eip-5606.md @@ -1,114 +1,7 @@ --- eip: 5606 -title: Multiverse NFTs -description: A universal representation of multiple related NFTs as a single digital asset across various platforms -author: Gaurang Torvekar (@gaurangtorvekar), Khemraj Adhawade (@akhemraj), Nikhil Asrani (@nikhilasrani) -discussions-to: https://ethereum-magicians.org/t/eip-5606-multiverse-nfts-for-digital-asset-interoperability/10698 -status: Last Call -last-call-deadline: 2023-01-02 -type: Standards Track category: ERC -created: 2022-09-06 -requires: 721, 1155 +status: Moved --- -## Abstract - -This specification defines a minimal interface to create a multiverse NFT standard for digital assets such as wearables and in-game items that, in turn, index the delegate NFTs on each platform where this asset exists. These platforms could be metaverses, play-to-earn games or NFT marketplaces. This proposal depends on and extends [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). The standard also allows for the ‘bundling’ and ‘unbundling’ of these delegate NFTs within the multiverse NFT so holders can trade them individually or as a bundle. - -## Motivation - -Several metaverses and blockchain games ("platforms") exist that use NFT standards such as EIP-721 and EIP-1155 for creating in-universe assets like avatar wearables, in-game items including weapons, shields, potions and much more. The biggest shortcoming while using these standards is that there is no interoperability between these platforms. As a publisher, you must publish the same digital asset (for example, a shirt) on various platforms as separate EIP-721 or EIP-1155 tokens. Moreover, there is no relationship between these, although they represent the same digital asset in reality. Hence, it is very difficult to prove the scarcity of these items on-chain. - -Since their inception, NFTs were meant to be interoperable and prove the scarcity of digital assets. Although NFTs can arguably prove the scarcity of items, the interoperability aspect hasn’t been addressed yet. Creating a multiverse NFT standard that allows for indexing and ownership of a digital asset across various platforms would be the first step towards interoperability and true ownership across platforms. - -In the web3 ecosystem, NFTs have evolved to represent multiple types of unique and non-fungible assets. One type of asset includes a set of NFTs related to one another. For instance, if a brand releases a new sneaker across various metaverses, it would be minted as a separate NFT on each platform. However, it is, in reality, the same sneaker. -There is a need to represent the relationship and transferability of these types of NFTs as metaverses and blockchain games gain more mainstream adoption. The ecosystem needs a better framework to address this issue rather than relying on the application level. This framework should define the relationship between these assets and the nature of their association. There is more value in the combined recognition, use and transferability of these individual NFTs as a bundle rather than their selves. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -A multiverse NFT contract represents a digital asset across multiple platforms. This contract can own one or more delegate NFT tokens of the digital asset on the various platforms through bundling or unbundling. - -``` -/** -* @dev Interface of the Multiverse NFT standard as defined in the EIP. -*/ -interface IMultiverseNFT { - - /** - * @dev struct to store delegate token details - * - */ - struct DelegateData { - address contractAddress; - uint256 tokenId; - uint256 quantity; - } - - /** - * @dev Emitted when one or more new delegate NFTs are added to a Multiverse NFT - */ - event Bundled(uint256 multiverseTokenID, DelegateData[] delegateData, address ownerAddress); - - - /** - * @dev Emitted when one or more delegate NFTs are removed from a Multiverse NFT - */ - event Unbundled(uint256 multiverseTokenID, DelegateData[] delegateData); - - /** - * @dev Accepts the tokenId of the Multiverse NFT and returns an array of delegate token data - */ - function delegateTokens(uint256 multiverseTokenID) external view returns (DelegateData[] memory); - - /** - * @dev Removes one or more delegate NFTs from a Multiverse NFT - * This function accepts the delegate NFT details and transfers those NFTs out of the Multiverse NFT contract to the owner's wallet - */ - function unbundle(DelegateData[] memory delegateData, uint256 multiverseTokenID) external; - - /** - * @dev Adds one or more delegate NFTs to a Multiverse NFT - * This function accepts the delegate NFT details and transfers those NFTs to the Multiverse NFT contract - * Need to ensure that approval is given to this Multiverse NFT contract for the delegate NFTs so that they can be transferred programmatically - */ - function bundle(DelegateData[] memory delegateData, uint256 multiverseTokenID) external; - - /** - * @dev Initialises a new bundle, mints a Multiverse NFT and assigns it to msg.sender - * Returns the token ID of a new Multiverse NFT - * Note - When a new Multiverse NFT is initialised, it is empty; it does not contain any delegate NFTs - */ - function initBundle(DelegateData[] memory delegateData) external; -} -``` - -Any dapp implementing this standard would initialise a bundle by calling the function `initBundle`. This mints a new multiverse NFT and assigns it to msg.sender. While creating a bundle, the delegate token contract addresses and the token IDs are set during the initialisation and cannot be changed after that. This avoids unintended edge cases where non-related NFTs could be bundled together by mistake. - -Once a bundle is initialised, the delegate NFT tokens can then be transferred to this Multiverse NFT contract by calling the function `bundle` and passing the token ID of the multiverse NFT. It is essential for a dapp to get the delegate NFTs ‘approved’ from the owner to this Multiverse NFT contract before calling the bundle function. After that, the Multiverse NFT owns one or more versions of this digital asset across the various platforms. - -If the owner of the multiverse NFT wants to sell or use the individual delegate NFTs across any of the platforms, they can do so by calling the function `unbundle`. This function transfers the particular delegate NFT token(s) to msg.sender (only if msg.sender is the owner of the multiverse NFT). - -## Rationale - -The `delegateData` struct contains information about the delegate NFT tokens on each platform. It contains variables such as `contractAddress`, `tokenId`, `quantity` to differentiate the NFTs. These NFTs could be following either the EIP-721 standard or the EIP-1155 standard. - -The `bundle` and `unbundle` functions accept an array of DelegateData struct because of the need to cater to partial bundling and unbundling. For instance, a user could initialise a bundle with three delegate NFTs, but they should be able to bundle and unbundle less than three at any time. They can never bundle or unbundle more than three. They also need the individual token IDs of the delegate NFTs to bundle and unbundle selectively. - -## Backwards Compatibility - -This standard is fully compatible with EIP-721 and EIP-1155. Third-party applications that don’t support this EIP will still be able to use the original NFT standards without any problems. - -## Reference Implementation - -[MultiverseNFT.sol](../assets/eip-5606/contracts/MultiverseNFT.sol) - -## Security Considerations - -The bundle function involves calling an external contract(s). So reentrancy prevention measures should be applied while implementing this function. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5606.md diff --git a/EIPS/eip-5615.md b/EIPS/eip-5615.md index ec4900adc4f4c5..af38feff8a22b4 100644 --- a/EIPS/eip-5615.md +++ b/EIPS/eip-5615.md @@ -1,56 +1,7 @@ --- eip: 5615 -title: EIP-1155 Supply Extension -description: A simple mechanism to fetch token supply data from EIP-1155 tokens -author: Pandapip1 (@Pandapip1) -discussions-to: https://ethereum-magicians.org/t/eip-5615-eip-1155-supply-extension/10732 -status: Review -type: Standards Track category: ERC -created: 2022-09-07 -requires: 1155 +status: Moved --- -## Abstract - -This EIP standardizes an existing mechanism to fetch token supply data from [EIP-1155](./eip-1155.md) tokens. It adds a `totalSupply` function, which fetches the number of tokens with a given `id`, and an `exists` function, which checks for the existence of a given `id`. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -interface ERC1155Supply is ERC1155 { - // @notice This function MUST return whether the given token id exists, previously existed, or may exist - // @param id The token id of which to check the existence - // @return Whether the given token id exists, previously existed, or may exist - function exists(uint256 id) external view returns (bool); - - // @notice This function MUST return the number of tokens with a given id. If the token id does not exist, it MUST return 0. - // @param id The token id of which fetch the total supply - // @return The total supply of the given token id - function totalSupply(uint256 id) external view returns (uint256); -} -``` - -## Rationale - -This EIP does not implement [EIP-165](./eip-165.md), as this interface is simple enough that the extra complexity is unnecessary and would cause incompatibilities with pre-existing implementations. - -The `totalSupply` and `exists` functions were modeled after [EIP-721](./eip-721.md) and [EIP-20](./eip-20.md). - -`totalSupply` does not revert if the token ID does not exist, since contracts that care about that case should use `exists` instead (which might return false even if `totalSupply` is zero). - -`exists` is included to differentiate between the two ways that `totalSupply` could equal zero (either no tokens with the given ID have been minted yet, or no tokens with the given ID will ever be minted). - -## Backwards Compatibility - -This EIP is designed to be backward compatible with the OpenZeppelin `ERC1155Supply`. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5615.md diff --git a/EIPS/eip-5625.md b/EIPS/eip-5625.md index dc480c8b37cc82..f507904b1114b9 100644 --- a/EIPS/eip-5625.md +++ b/EIPS/eip-5625.md @@ -1,185 +1,7 @@ --- eip: 5625 -title: NFT Metadata JSON Schema dStorage Extension -description: Add a dStorage property to non-fungible tokens (NFTs) metadata JSON schema to provide decentralized storage information of NFT assets -author: Gavin Fu (@gavfu) -discussions-to: https://ethereum-magicians.org/t/eip-5625-nft-metadata-json-schema-dstorage-extension/10754 -status: Review -type: Standards Track category: ERC -created: 2022-09-08 -requires: 721, 1155 +status: Moved --- -## Abstract - -This EIP extends the NFT metadata JSON schema defined in [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md), adding a `dStorage` key that provides information about how the NFT data is stored. - -## Motivation - -As highly valuable crypto properties, NFT assets intrinsically demand guaranteed storage to assure their **immutability**, **reliability**, and **durability**. NFT ownership is tracked by [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md) smart contracts, hence persisted in blockchain, which is not a problem. But how about the mime-type assets that NFT tokens represent? Ideally, they should also be stored in some reliable and verifiable decentralized storage system that is designed to store larger amounts of data than the blockchain itself. As an effort to promote **decentralized storage** adoption in NFT world, we propose to add additional **dStorage** information into NFT metadata JSON schema. - -As a refresher, let's review existing NFT metadata JSON schema standards. [EIP-721](./eip-721.md) defines a standard contract method `tokenURI` to return a given NFT's metadata JSON file, conforming to the *[EIP-721](./eip-721.md) Metadata JSON Schema*, which defines three properties: `name`, `description` and `image`. - -Similarly, [EIP-1155](./eip-1155.md) also defines a standard contract method `uri` to return NFT metadata JSON files conforming to the *[EIP-1155](./eip-1155.md) Metadata JSON Schema*, which defines properties like `name`, `decimals`, `description`, `image`, `properties`, `localization`, etc. - -Besides, as the world's largest NFT marketplace nowadays, OpenSea defines their own *Metadata Standards*, including a few more properties like `image_data`, `external_url`, `attributes`, `background_color`, `animation_url`, `youtube_url`, etc. This standard is de facto respected and followed by other NFT marketplaces like LooksRare. - -None of these standards conveys storage information about the mime-type asset that the NFT token represents. This proposal is an effort to fill the missing part. - - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -In addition to the existing properties, the Metadata JSON file returned by [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) smart contracts (via `tokenURI` and `uri` methods, respectively), should OPTIONALLY contains one more `dStorage` property. - -For [EIP-721](./eip-721.md) smart contracts, the Metadata JSON file schema is: - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents" - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "dStorage": { - "type": "object", - "required": ["platform", "description", "persistence_mechanism", "challenge_mechanism", "consensus", "dstorage_note"], - "properties": { - "platform": { - "type": "string", - "description": "dStorage platform name like Swarm, Arweave, Filecoin, Crust, etc" - }, - "description": { - "type": "string", - "description": "A brief description of the dStorage platform" - }, - "persistence_mechanism": { - "type": "string", - "description": "Persistence mechanism or incentive structure of the dStorage platform, like 'blockchain-based', 'contract-based', etc" - }, - "challenge_mechanism": { - "type": "string", - "description": "Challenge mechanism of the dStorage platform, like Arweave's proof-of-access, etc" - }, - "consensus": { - "type": "string", - "description": "Consensus mechanism of the dStorage platform, like PoW, PoS, etc" - }, - "dstorage_note": { - "type": "string", - "description": "A note to prove the storage of the NFT asset on the dStorage platform, like a Filecoin deal id, a Crust place_storage_order transaction hash, etc" - } - } - } - } -} -``` - -For [EIP-1155](./eip-1155.md) smart contracts, the Metadata JSON file schema is: - -```json -{ - "title": "Token Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this token represents", - }, - "decimals": { - "type": "integer", - "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation." - }, - "description": { - "type": "string", - "description": "Describes the asset to which this token represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - }, - "properties": { - "type": "object", - "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.", - }, - "localization": { - "type": "object", - "required": ["uri", "default", "locales"], - "properties": { - "uri": { - "type": "string", - "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request." - }, - "default": { - "type": "string", - "description": "The locale of the default data within the base JSON" - }, - "locales": { - "type": "array", - "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)." - } - } - }, - "dStorage": { - "type": "object", - "required": ["platform", "description", "persistence_mechanism", "challenge_mechanism", "consensus", "dstorage_note"], - "properties": { - "platform": { - "type": "string", - "description": "dStorage platform name like Swarm, Arweave, Filecoin, Crust, etc" - }, - "description": { - "type": "string", - "description": "A brief description of the dStorage platform" - }, - "persistence_mechanism": { - "type": "string", - "description": "Persistence mechanism or incentive structure of the dStorage platform, like 'blockchain-based', 'contract-based', etc" - }, - "challenge_mechanism": { - "type": "string", - "description": "Challenge mechanism of the dStorage platform, like Arweave's proof-of-access, etc" - }, - "consensus": { - "type": "string", - "description": "Consensus mechanism of the dStorage platform, like PoW, PoS, etc" - }, - "dstorage_note": { - "type": "string", - "description": "A note to prove the storage of the NFT asset on the dStorage platform, like a Filecoin deal id, a Crust place_storage_order transaction hash, etc" - } - } - } - } -} -``` - -## Rationale - -### Choice between Interface and JSON Schema Extension - -An extension of the EIP-721 or EIP-1155 contract interfaces would unnecessarily require additional code to implement, and would not be available for use by NFT projects that already have their NFT smart contracts finalized and deployed. An optional JSON schema extension is noninvasive, and more easily adopted. - -# Backwards Compatibility - -This EIP is backward compatible with [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). \ No newline at end of file +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5625.md diff --git a/EIPS/eip-5630.md b/EIPS/eip-5630.md index 45cea4e9d3a619..62260c8f7873b8 100644 --- a/EIPS/eip-5630.md +++ b/EIPS/eip-5630.md @@ -1,205 +1,7 @@ --- eip: 5630 -title: New approach for encryption / decryption -description: defines a specification for encryption and decryption using Ethereum wallets. -author: Firn Protocol (@firnprotocol), Fried L. Trout, Weiji Guo (@weijiguo) -discussions-to: https://ethereum-magicians.org/t/eip-5630-encryption-and-decryption/10761 -status: Draft -type: Standards Track category: ERC -created: 2022-09-07 +status: Moved --- - -## Abstract - -This EIP proposes a new way to encrypt and decrypt using Ethereum keys. This EIP uses _only_ the `secp256k1` curve, and proposes two new RPC methods: `eth_getEncryptionPublicKey` and `eth_performECDH`. These two methods, in conjunction, allow users to receive encryptions and perform decryptions (respectively). We require that the wallet _only_ perform the core ECDH operation, leaving the ECIES operations up to implementers (we do suggest a standardized version of ECIES, however). In contrast, a previous EIPs used the same secret key, in both signing and encryption, on two _different_ curves (namely, `secp256k1` and `ec25519`), and hardcoded a particular version of ECIES. - -## Motivation - -We discuss a few motivating examples. One key motivation is direct-to-address encryption on Ethereum. Using our EIP, one can directly send encrypted messages to some desired recipient on-chain, without having a prior direct channel to that recipient. (Note that in this EIP, we standardize _only_ the encryption procedure—that is, the generation of the ciphertext—and _not_ how exactly the on-chain message should be sent. In practice, ideally, smart-contract infrastructure will be set up for this purpose; barring this, encryptors could make use of the raw `data` field available in each standard transfer.) - -We discuss a second sort of example. In a certain common design pattern, a dApp generates a fresh secret on behalf of a user. It is of interest if, instead of forcing this user to independently store, safeguard, and back up this latter secret, the dApp may instead encrypt this secret to a public key which the user controls—and whose secret key, crucially, resides within the user's HD wallet hierarchy—and then post the resulting ciphertext to secure storage (e.g., on-chain). This design pattern allows the dApp/user to bootstrap the security of the _fresh_ secret onto the security of the user's existing HD wallet seed phrase, which the user has already gone through the trouble of safeguarding and storing. This represents a far lower UX burden than forcing the user to store and manage fresh keys directly (which can, and often does, lead to loss of funds). We note that this design pattern described above is used today by, various dApps (e.g., Tornado Cash). - -## Specification - -We describe our approach here; we compare our approach to prior EIPs in the **Rationale** section below. Throughout, we make reference to SEC 1: Elliptic Curve Cryptography, by Daniel R. L. Brown. - -We use the `secp256k1` curve for both signing and encryption. -For encryption, we use ECIES. We specify that the wallet _only_ perform the sensitive ECDH operation. This lets implementers select their own ECIES variants at will. - -We propose that all binary data be serialized to and from `0x`-prefixed hex strings. We moreover use `0x`-prefixed hex strings to specify private keys and public keys, and represent public keys in compressed form. We represent Ethereum accounts in the usual way (`0x`-prefixed, 20-byte hex strings). Specifically, to serialize and deserialize elliptic curve points, implementers MUST use the following standard: - -- to serialize a point: use [SEC 1, §2.3.3], with point compression. -- to deserialize a point: use [SEC 1, §2.3.3], while _requiring_ point compression; that is: - - - the input byte string MUST have length ⌈log₂q / 8⌉ + 1 = `33`. - - the first byte MUST be `0x02` or `0x03`. - - the integer represented by the remaining 32 bytes (as in [SEC 1, §2.3.8]) MUST reside in {0, ..., _p_ - 1}, and moreover MUST yield a quadratic residue modulo _p_ under the Weierstrass expression X^3 + 7 (modulo _p_). - -For application-level implementers actually implementing ECIES, we propose the following variant. Unless they have a reason to do otherwise, implementers SHOULD use the following standardized choices: - -- the KDF `ANSI-X9.63-KDF`, where the hash function `SHA-512` is used, -- the HMAC `HMAC–SHA-256–256 with 32 octet or 256 bit keys`, -- the symmetric encryption scheme `AES–256 in CBC mode`. - -We propose that the binary, _concatenated_ serialization mode for ECIES ciphertexts be used, both for encryption and decryption, where moreover elliptic curve points are _compressed_. - -Thus, on the request: - -```javascript -request({ - method: 'eth_getEncryptionPublicKey', - params: [account] -}) -``` - -where `account` is a standard 20-byte, `0x`-prefixed, hex-encoded Ethereum account, the client should operate as follows: - -- find the secret signing key `sk` corresponding to the Ethereum account `account`, or else return an error if none exists. -- compute the `secp256k1` public key corresponding to `sk`. -- return this public key in compressed, `0x`-prefixed, hex-encoded form, following [SEC 1, §2.3.3]. - -On the request - -```javascript -request({ - method: 'eth_performECDH', - params: [account, ephemeralKey] -}) -``` - -where `account` is as above, and `ephemeralKey` is an elliptic curve point encoded as above: - -- find the secret key `sk` corresponding to the Ethereum account `account`, or else return an error if none exists. -- deserialize `ephemeralKey` to an elliptic curve point using [SEC 1, §2.3.3] (where compression is required), throwing an error if deserialization fails. -- compute the elliptic curve Diffie–Hellman secret, following [SEC 1, §3.3.1]. -- return the resulting field element as an 0x-prefixed, hex-encoded, 32-byte string, using [SEC 1, §2.3.5]. - -Test vectors are given below. - -### Encrypting to a smart contract - -In light of account abstraction, [EIP-4337](eip-4337.md), and the advent of smart-contract wallets, we moreover specify a way to encrypt to a contract. -More precisely, we specify a way for a contract to _advertise_ how it would like encryptions to it to be constructed. This should be viewed as an analogue of [EIP-1271](eip-1271.md), but for encryption, as opposed to signing. - -Our specification is as follows. - -```solidity -pragma solidity ^0.8.0; - -contract ERC5630 { - /** - * @dev Should return an encryption of the provided plaintext, using the provided randomness. - * @param plaintext Plaintext to be encrypted - * @param randomness Entropy to be used during encryption - */ - function encryptTo(bytes memory plaintext, bytes32 randomness) - public - view - returns (bytes memory ciphertext); -} -``` - -Each contract MAY implement `encryptTo` as it desires. Unless it has a good reason to do otherwise, it SHOULD use the ECIES variant we propose above. - -## Rationale - -There is _no security proof_ for a scheme which simultaneously invokes signing on the `secp256k1` curve and encryption on the `ec25519` curve, and where _the same secret key is moreover used in both cases_. Though no attacks are known, it is not desirable to use a scheme which lacks a proof in this way. -We, instead, propose the reuse of the same key in signing and encryption, but where _the same curve is used in both_. This very setting has been studied in prior work; see, e.g., Degabriele, Lehmann, Paterson, Smart and Strefler, _On the Joint Security of Encryption and Signature in EMV_, 2011. That work found this joint scheme to be secure in the generic group model. -We note that this very joint scheme (i.e., using ECDSA and ECIES on the same curve) is used live in production in EMV payments. - -We now discuss a few further aspects of our approach. - -**On-chain public key discovery.** Our proposal has an important feature whereby an encryption _to_ some account can be constructed whenever that account has signed at least one transaction. -Indeed, it is possible to recover an account's `secp256k1` public key directly from any signature on behalf of that account. - -**ECDH vs. ECIES.** We specify that the wallet _only_ perform the sensitive ECDH operation, and let application-level implementers perform the remaining steps of ECIES. This has two distinct advantages: - -- **Flexibility.** It allows implementers to select arbitrary variants of ECIES, without having to update what the wallet does. -- **Bandwidth.** Our approach requires that only small messages (on the order of 32 bytes) be exchanged between the client and the wallet. This could be material in settings in which the plaintexts and ciphertexts at play are large, and when the client and the wallet are separated by an internet connection. - -**Twist attacks.** A certain GitHub post by Christian Lundkvist warns against "twist attacks" on the `secp256k1` curve. These attacks are not applicable to this EIP, for multiple _distinct_ reasons, which we itemize: - -- **Only applies to classical ECDH, not ECIES.** This attack only applies to classical ECDH (i.e., in which both parties use persistent, authenticated public keys), and not to ECIES (in which one party, the encryptor, uses an ephemeral key). Indeed, it only applies to a scenario in which an attacker can induce a victim to exponentiate an attacker-supplied point by a sensitive scalar, and then moreover send the result back to the attacker. But this pattern only happens in classical Diffie–Hellman, and never in ECIES. Indeed, in ECIES, we recall that the only sensitive Diffie–Hellman operation happens during decryption, but in this case, the victim (who would be the decryptor) never sends the resulting DH point back to the attacker (rather, the victim merely uses it locally to attempt an AES decryption). During _encryption_, the exponentiation is done by the encryptor, who has no secret at all (sure enough, the exponentiation is by an ephemeral scalar), so here there would be nothing for the attacker to learn. -- **Only applies to uncompressed points.** Indeed, we use compressed points in this EIP. When compressed points are used, each 33-byte string _necessarily_ either resolves to a point on the correct curve, or else has no reasonable interpretation. There is no such thing as "a point not on the curve" (which, in particular, can pass undetectedly as such). -- **Only applies when you fail to check a point is on the curve.** But this is inapplicable for us anyway, since we use compressed points (see above). We also require that all validations be performed. - -## Backwards Compatibility - -Our `eth_performECDH` method is new, and so doesn't raise any backwards compatibility issues. - -A previous proposal proposed an `eth_getEncryptionPublicKey` method (together with an `eth_decrypt` method unrelated to this EIP). Our proposal overwrites the previous behavior of `eth_getEncryptionPublicKey`. -It is unlikely that this will be an issue, since encryption keys need be newly retrieved _only_ upon the time of encryption; on the other hand, _new_ ciphertexts will be generated using our new approach. -(In particular, our modification will not affect the ability of ciphertexts generated using the old EIP to be `eth_decrypt`ed.) - -In any case, the previous EIP was never standardized, and is _not_ (to our knowledge) implemented in a non-deprecated manner in _any_ production code today. - -### Test Cases - -The secret _signing key_ - -``` - 0x439047a312c8502d7dd276540e89fe6639d39da1d8466f79be390579d7eaa3b2 -``` - -with Ethereum address `0x72682F2A3c160947696ac3c9CC48d290aa89549c`, has `secp256k1` public key - -``` - 0x03ff5763a2d3113229f2eda8305fae5cc1729e89037532a42df357437532770010 -``` - -Thus, the request: - -```javascript -request({ - method: 'eth_getEncryptionPublicKey', - params: ["0x72682F2A3c160947696ac3c9CC48d290aa89549c"] -}) -``` - -should return: - -```javascript -"0x03ff5763a2d3113229f2eda8305fae5cc1729e89037532a42df357437532770010" -``` - -If an encryptor were to encrypt a message—say, `I use Firn Protocol to gain privacy on Ethereum.`—under the above public key, using the above ECIES variant, he could obtain, for example: - -```javascript -"0x036f06f9355b0e3f7d2971da61834513d5870413d28a16d7d68ce05dc78744daf850e6c2af8fb38e3e31d679deac82bd12148332fa0e34aecb31981bd4fe8f7ac1b74866ce65cbe848ee7a9d39093e0de0bd8523a615af8d6a83bbd8541bf174f47b1ea2bd57396b4a950a0a2eb77af09e36bd5832b8841848a8b302bd816c41ce" -``` - -Upon obtaining this ciphertext, the decryptor would extract the relevant ephemeral public key, namely: - -```javascript -"0x036f06f9355b0e3f7d2971da61834513d5870413d28a16d7d68ce05dc78744daf8" -``` - -And submit the request: - -```javascript -request({ - method: 'eth_performECDH', - params: [ - "0x72682F2A3c160947696ac3c9CC48d290aa89549c", - "0x036f06f9355b0e3f7d2971da61834513d5870413d28a16d7d68ce05dc78744daf8" - ] -}) -``` - -which in turn would return the Diffie–Hellman secret: - -```javascript -"0x4ad782e7409702101abe6d0279f242a2c545c46dd50a6704a4b9e3ae2730522e" -``` - -Upon proceeding with the above ECIES variant, the decryptor would then obtain the string `I use Firn Protocol to gain privacy on Ethereum.`. - -## Security Considerations - -Our proposal uses heavily standardized algorithms and follows all best practices. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5630.md diff --git a/EIPS/eip-5633.md b/EIPS/eip-5633.md index 559473b3fd4d6f..4872e01c561d4a 100644 --- a/EIPS/eip-5633.md +++ b/EIPS/eip-5633.md @@ -1,78 +1,7 @@ --- eip: 5633 -title: Composable Soulbound NFT, EIP-1155 Extension -description: Add composable soulbound property to EIP-1155 tokens -author: HonorLabs (@honorworldio) -discussions-to: https://ethereum-magicians.org/t/composable-soulbound-nft-eip-1155-extension/10773 -status: Draft -type: Standards Track category: ERC -created: 2022-09-09 -requires: 165, 1155 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-1155](./eip-1155.md). It proposes a smart contract interface that can represent any number of soulbound and non-soulbound NFT types. Soulbound is the property of a token that prevents it from being transferred between accounts. This standard allows for each token ID to have its own soulbound property. - -## Motivation - -The soulbound NFTs similar to World of Warcraft’s soulbound items are attracting more and more attention in the Ethereum community. In a real world game like World of Warcraft, there are thousands of items, and each item has its own soulbound property. For example, the amulate Necklace of Calisea is of soulbound property, but another low level amulate is not. This proposal provides a standard way to represent soulbound NFTs that can coexist with non-soulbound ones. It is easy to design a composable NFTs for an entire collection in a single contract. - -This standard outline a interface to EIP-1155 that allows wallet implementers and developers to check for soulbound property of token ID using [EIP-165](./eip-165.md). the soulbound property can be checked in advance, and the transfer function can be called only when the token is not soulbound. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -A token type with a `uint256 id` is soulbound if function `isSoulbound(uint256 id)` returning true. In this case, all EIP-1155 functions of the contract that transfer the token from one account to another MUST throw, except for mint and burn. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface IERC5633 { - /** - * @dev Emitted when a token type `id` is set or cancel to soulbound, according to `bounded`. - */ - event Soulbound(uint256 indexed id, bool bounded); - - /** - * @dev Returns true if a token type `id` is soulbound. - */ - function isSoulbound(uint256 id) external view returns (bool); -} -``` -Smart contracts implementing this standard MUST implement the EIP-165 supportsInterface function and MUST return the constant value true if 0x911ec470 is passed through the interfaceID argument. - -## Rationale - -If all tokens in a contract are soulbound by default, `isSoulbound(uint256 id)` should return true by default during implementation. - -## Backwards Compatibility - -This standard is fully EIP-1155 compatible. - -## Test Cases - -Test cases are included in [test.js](../assets/eip-5633/test/test.js). - -Run in terminal: - -```shell -cd ../assets/eip-5633 -npm install -npx hardhat test -``` - -Test contract are included in [`ERC5633Demo.sol`](../assets/eip-5633/contracts/ERC5633Demo.sol). - -## Reference Implementation - -See [`ERC5633.sol`](../assets/eip-5633/contracts/ERC5633.sol). - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5633.md diff --git a/EIPS/eip-5635.md b/EIPS/eip-5635.md index 370c41e82913c0..687b7b8f5600a3 100644 --- a/EIPS/eip-5635.md +++ b/EIPS/eip-5635.md @@ -1,265 +1,7 @@ --- eip: 5635 -title: NFT Licensing Agreements -description: An oracle for retrieving NFT licensing agreements -author: Timi (@0xTimi), 0xTriple7 (@ysqi) -discussions-to: https://ethereum-magicians.org/t/eip-5635-discussion-nft-licensing-agreement-standard/10779 -status: Draft -type: Standards Track category: ERC -created: 2022-08-10 -requires: 165, 721, 1155, 2981 +status: Moved --- -## Abstract - -This EIP standardizes an NFT licensing oracle to store (register) and retrieve (discover) granted licensing agreements for non-fungible token (NFT) derivative works, which are also NFTs but are created using properties of some other underlying NFTs. - -In this standard, an NFT derivative work is referred to as a **dNFT**, while the original underlying NFT is referred to as an **oNFT**. - -The NFT owner, known as the `licensor`, may authorize another creator, known as the `licensee`, to create a derivative works (dNFTs), in exchange for an agreed payment, known as a `Royalty`. A licensing agreement outlines terms and conditions related to the deal between the licensor and licensee. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -In general, there are three important roles in this standard: - -- oNFT: An original underlying NFT. The holder of an oNFT is a licensor. An oNFT can be any NFT. -- dNFT: A derivative work based on one or more oNFTs. The holder of a dNFT is a licensee. -- Registry: A trusted smart contract able to verify whether a credential is signed or released by the holder of oNFT. - -Every **dNFT** contract must implement the `IERC5635NFT` and `IERC165` inferfaces. - -```solidity -pragma solidity ^0.6.0; -import "./IERC165.sol"; - -/// -/// @notice Interface of NFT derivatives (dNFT) for the NFT Licensing Standard -/// @dev The ERC-165 identifier for this interface is 0xd584841c. -interface IERC5635DNFT is IERC165 { - - /// ERC165 bytes to add to interface array - set in parent contract - /// implementing this standard - /// - /// bytes4(keccak256("IERC5635DNFT{}")) == 0xd584841c - /// bytes4 private constant _INTERFACE_ID_IERC5635DNFT = 0xd584841c; - /// _registerInterface(_INTERFACE_ID_IERC5635XDNFT); - - /// @notice Get the number of credentials. - /// @param _tokenId - ID of the dNFT asset queried - /// @return _number - the number of credentials - function numberOfCredentials( - uint256 _tokenId - ) external view returns ( - uint256 _number - ); - - /// @notice Called with the sale price to determine how much royalty is owed and to whom. - /// @param _tokenId - ID of the dNFT asset queried - /// @param _credentialId - ID of the licensing agreement credential, the max id is numberOfCredentials(_tokenId)-1 - /// @return _oNFT - the oNFT address where the licensing from - /// @return _tokenID - the oNFT ID where the licensing from - /// @return _registry - the address of registry which can verify this credential - function authorizedBy( - uint256 _tokenId, - uint256 _credentialId - ) external view returns ( - address _oNFT, - uint256 _tokenId, - address _registry - ); - -} - -interface IERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -Every **Registry** contract must implement the `IERC5635Registry` and `IERC165` inferfaces. - -```solidity -pragma solidity ^0.6.0; -import "./IERC165.sol"; - -/// -/// @dev Interface of NFT derivatives (dNFT) for the NFT Licensing Standard -/// Note: the ERC-165 identifier for this interface is 0xb5065e9f -interface IERC5635Registry is IERC165 { - - /// ERC165 bytes to add to interface array - set in parent contract - /// implementing this standard - /// - /// bytes4(keccak256("IERC5635Registry{}")) == 0xb5065e9f - /// bytes4 private constant _INTERFACE_ID_IERC5635Registry = 0xb5065e9f; - /// _registerInterface(_INTERFACE_ID_IERC5635Registry); - - // TODO: Is the syntax correct? - enum LicensingAgreementType { - NonExclusive, - Exclusive, - Sole - } - - - /// @notice - /// @param _dNFT - - /// @param _dNFT_Id - - /// @param _oNFT - - /// @param _oNFT_Id - - /// @return _licensed - - /// @return _tokenID - the oNFT ID where the licensing from - /// @return _registry - the address of registry which can verify this credential - function isLicensed( - address _dNFT, - uint256 _dNFT_Id, - address _oNFT, - uint256 _oNFT_Id - ) external view returns ( - bool _licensed - ); - - /// @return _licenseIdentifier - the identifier, e.g. `MIT` or `Apache`, similar to `SPDX-License-Identifier: MIT` in SPDX. - function licensingInfo( - address _dNFT, - uint256 _dNFT_Id, - address _oNFT, - uint256 _oNFT_Id - ) external view returns ( - bool _licensed, - address _licensor, - uint64 _timeOfSignature, - uint64 _expiryTime, - LicensingAgreementType _type, - string _licenseName, - string _licenseUri // - ); - - function royaltyRate( - address _dNFT, - uint256 _dNFT_Id, - address _oNFT, - uint256 _oNFT_Id - ) external view returns ( - address beneficiary, - uint256 rate // The decimals is 9, means to divide the rate by 1,000,000,000 - ); -} -``` - -The **Registry** contract MAY implement the `IERC5635Licensing` and `IERC165` inferfaces. - -```solidity -pragma solidity ^0.6.0; -import "./IERC165.sol"; - -/// -/// -interface IERC5635Licensing is IERC165, IERC5635Registry { - - event Licence(address indexed _oNFT, uint256 indexed _oNFT_Id, address indexed _dNFT, uint256 indexed _dNFT_Id, uint64 _expiryTime, LicensingAgreementType _type, string _licenseName, string _licenseUri); - - event Approval(address indexed _oNFT, address indexed _owner, address indexed _approved, uint256 indexed _tokenId); - - event ApprovalForAll(address indexed _oNFT, address indexed _owner, address indexed _operator, bool _approved); - - function licence(address indexed _oNFT, uint256 indexed _oNFT_Id, address indexed _dNFT, uint256 indexed _dNFT_Id, uint64 _expiryTime, LicensingAgreementType _type, string _licenseName, string _licenseUri) external payable; //TODO: mortgages or not? - - function approve(address indexed _oNFT, address _approved, uint256 _tokenId) external payable; //TODO: why payable? - - function setApprovalForAll(address indexed _oNFT, address _operator, bool _approved) external; - - function getApproved(address indexed _oNFT, uint256 _tokenId) external view returns (address); - - function isApprovedForAll(address indexed _oNFT, address _owner, address _operator) external view returns (bool); - -} -``` - -## Rationale - -Licensing credentials from a dNFT's contract can be retrieved with `authorizedBy`, which specifies the details of a licensing agreement, which may include the oNFT. Those credentials may be verified with a `registry` service. - -Anyone can retrieve licensing royalty information with `licensingRoyalty` via the registry. While it is not possible to enforce the rules set out in this EIP on-chain, just like [EIP-2981](./eip-2981.md), we encourages NFT marketplaces to follow this EIP. - -### Two stages: Licensing and Discovery - -Taking the moment when the dNFT is minted as the cut-off point, the stage before is called the **Licensing** stage, and the subsequent stage is called the **Discovery** stage. The interface `IERC5635Licensing` is for the **Licensing** stage, and the interfaces `IERC5635DNFT` and `IERC5635Registry` are for the **Discovery** stage. - -### Design decision: beneficiary of licensing agreement - -As soon as someone sells their NFT, the full licensed rights are passed along to the new owner without any encumbrances, so that the beneficiary should be the new owner. - -### Difference between CantBeEvil Licenses and Licensing Agreements. - -CantBeEvil licenses are creator-holder licenses which indicate what rights the NFTs' holder are granted from the creator. Meanwhile, licensing agreements is a contract between a licensor and licensee. So, CantBeEvil licenses cannot be used as a licensing agreement. - -### Design decision: Relationship between different approval levels - -The approved address can `license()` the licensing agreement to **dNFT** on behalf of the holder of an **oNFT**. We define two levels of approval like that: - -1. `approve` will lead to approval for one NFT related to an id. -2. `setApprovalForAll` will lead to approval of all NFTs owned by `msg.sender`. - -## Backwards Compatibility - -This standard is compatible with [EIP-721](./eip-721.md), [EIP-1155](./eip-1155.md), and [EIP-2981](./eip-2981.md). - -## Reference Implementation - -### Examples - -#### Deploying an [EIP-721](./eip-721.md) NFT and signaling support for dNFT - -```solidity -constructor (string memory name, string memory symbol, string memory baseURI) { - _name = name; - _symbol = symbol; - _setBaseURI(baseURI); - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(_INTERFACE_ID_ERC721); - _registerInterface(_INTERFACE_ID_ERC721_METADATA); - _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); - // dNFT interface - _registerInterface(_INTERFACE_ID_IERC5635DNFT); -} -``` - -#### Checking if the NFT being sold on your marketplace is a dNFT - -```solidity -bytes4 private constant _INTERFACE_ID_IERC5635DNFT = 0xd584841c; - -function checkDNFT(address _contract) internal returns (bool) { - (bool success) = IERC165(_contract).supportsInterface(_INTERFACE_ID_IERC5635DNFT); - return success; -} -``` - -#### Checking if an address is a Registry - -```solidity -bytes4 private constant _INTERFACE_ID_IERC5635Registry = 0xb5065e9f; - -function checkLARegistry(address _contract) internal returns (bool) { - (bool success) = IERC165(_contract).supportsInterface(_INTERFACE_ID_IERC5635Registry); - return success; -} -``` - -## Security Considerations - -Needs discussion. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5635.md diff --git a/EIPS/eip-5639.md b/EIPS/eip-5639.md index ff06ae69f65057..971febdb0dc3bf 100644 --- a/EIPS/eip-5639.md +++ b/EIPS/eip-5639.md @@ -1,283 +1,7 @@ --- eip: 5639 -title: Delegation Registry -description: Delegation of permissions for safer and more convenient signing operations. -author: foobar (@0xfoobar), Wilkins Chung (@wwhchung), ryley-o (@ryley-o), Jake Rockland (@jakerockland), andy8052 (@andy8052) -discussions-to: https://ethereum-magicians.org/t/eip-5639-delegation-registry/10949 -status: Draft -type: Standards Track category: ERC -created: 2022-09-09 +status: Moved --- -## Abstract -This EIP describes the details of the Delegation Registry, a proposed protocol and ABI definition that provides the ability to link one or more delegate wallets to a vault wallet in a manner which allows the linked delegate wallets to prove control and asset ownership of the vault wallet. - -## Motivation -Proving ownership of an asset to a third party application in the Ethereum ecosystem is common. Users frequently sign payloads of data to authenticate themselves before gaining access to perform some operation. However, this method--akin to giving the third party root access to one's main wallet--is both insecure and inconvenient. - -***Examples:*** - 1. In order for you to edit your profile on OpenSea, you must sign a message with your wallet. - 2. In order to access NFT gated content, you must sign a message with the wallet containing the NFT in order to prove ownership. - 3. In order to gain access to an event, you must sign a message with the wallet containing a required NFT in order to prove ownership. - 4. In order to claim an airdrop, you must interact with the smart contract with the qualifying wallet. - 5. In order to prove ownership of an NFT, you must sign a payload with the wallet that owns that NFT. - -In all the above examples, one interacts with the dApp or smart contract using the wallet itself, which may be - - inconvenient (if it is controlled via a hardware wallet or a multi-sig) - - insecure (since the above operations are read-only, but you are signing/interacting via a wallet that has write access) - -Instead, one should be able to approve multiple wallets to authenticate on behalf of a given wallet. - -### Problems with existing methods and solutions -Unfortunately, we've seen many cases where users have accidentally signed a malicious payload. The result is almost always a significant loss of assets associated with the delegate address. - -In addition to this, many users keep significant portions of their assets in 'cold storage'. With the increased security from 'cold storage' solutions, we usually see decreased accessibility because users naturally increase the barriers required to access these wallets. - -### Proposal: Use of a Delegation Registry -This proposal aims to provide a mechanism which allows a vault wallet to grant wallet, contract or token level permissions to a delegate wallet. This would achieve a safer and more convenient way to sign and authenticate, and provide 'read only' access to a vault wallet via one or more secondary wallets. - -From there, the benefits are twofold. This EIP gives users increased security via outsourcing potentially malicious signing operations to wallets that are more accessible (hot wallets), while being able to maintain the intended security assumptions of wallets that are not frequently used for signing operations. - -#### Improving dApp Interaction Security -Many dApps requires one to prove control of a wallet to gain access. At the moment, this means that you must interact with the dApp using the wallet itself. This is a security issue, as malicious dApps or phishing sites can lead to the assets of the wallet being compromised by having them sign malicious payloads. - -However, this risk would be mitigated if one were to use a secondary wallet for these interactions. Malicious interactions would be isolated to the assets held in the secondary wallet, which can be set up to contain little to nothing of value. - -#### Improving Multiple Device Access Security -In order for a non-hardware wallet to be used on multiple devices, you must import the seed phrase to each device. Each time a seed phrase is entered on a new device, the risk of the wallet being compromised increases as you are increasing the surface area of devices that have knowledge of the seed phrase. - -Instead, each device can have its own unique wallet that is an authorized secondary wallet of the main wallet. If a device specific wallet was ever compromised or lost, you could simply remove the authorization to authenticate. - -Further, wallet authentication can be chained so that a secondary wallet could itself authorize one or many tertiary wallets, which then have signing rights for both the secondary address as well as the root main address. This, can allow teams to each have their own signer while the main wallet can easily invalidate an entire tree, just by revoking rights from the root stem. - -#### Improving Convenience -Many invididuals use hardware wallets for maximum security. However, this is often inconvenient, since many do not want to carry their hardware wallet with them at all times. - -Instead, if you approve a non-hardware wallet for authentication activities (such as a mobile device), you would be able to use most dApps without the need to have your hardware wallet on hand. - -## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Let: - - `vault` represent the vault address we are trying to authenticate or prove asset ownership for. - - `delegate` represent the address we want to use for signing in lieu of `vault`. - - -**A Delegation Registry must implement IDelegationRegistry** - -```solidity -** - * @title An immutable registry contract to be deployed as a standalone primitive - * @dev New project launches can read previous cold wallet -> hot wallet delegations - * from here and integrate those permissions into their flow - */ -interface IDelegationRegistry { - /// @notice Delegation type - enum DelegationType { - NONE, - ALL, - CONTRACT, - TOKEN - } - - /// @notice Info about a single delegation, used for onchain enumeration - struct DelegationInfo { - DelegationType type_; - address vault; - address delegate; - address contract_; - uint256 tokenId; - } - - /// @notice Info about a single contract-level delegation - struct ContractDelegation { - address contract_; - address delegate; - } - - /// @notice Info about a single token-level delegation - struct TokenDelegation { - address contract_; - uint256 tokenId; - address delegate; - } - - /// @notice Emitted when a user delegates their entire wallet - event DelegateForAll(address vault, address delegate, bool value); - - /// @notice Emitted when a user delegates a specific contract - event DelegateForContract(address vault, address delegate, address contract_, bool value); - - /// @notice Emitted when a user delegates a specific token - event DelegateForToken(address vault, address delegate, address contract_, uint256 tokenId, bool value); - - /// @notice Emitted when a user revokes all delegations - event RevokeAllDelegates(address vault); - - /// @notice Emitted when a user revoes all delegations for a given delegate - event RevokeDelegate(address vault, address delegate); - - /** - * ----------- WRITE ----------- - */ - - /** - * @notice Allow the delegate to act on your behalf for all contracts - * @param delegate The hotwallet to act on your behalf - * @param value Whether to enable or disable delegation for this address, true for setting and false for revoking - */ - function delegateForAll(address delegate, bool value) external; - - /** - * @notice Allow the delegate to act on your behalf for a specific contract - * @param delegate The hotwallet to act on your behalf - * @param contract_ The address for the contract you're delegating - * @param value Whether to enable or disable delegation for this address, true for setting and false for revoking - */ - function delegateForContract(address delegate, address contract_, bool value) external; - - /** - * @notice Allow the delegate to act on your behalf for a specific token - * @param delegate The hotwallet to act on your behalf - * @param contract_ The address for the contract you're delegating - * @param tokenId The token id for the token you're delegating - * @param value Whether to enable or disable delegation for this address, true for setting and false for revoking - */ - function delegateForToken(address delegate, address contract_, uint256 tokenId, bool value) external; - - /** - * @notice Revoke all delegates - */ - function revokeAllDelegates() external; - - /** - * @notice Revoke a specific delegate for all their permissions - * @param delegate The hotwallet to revoke - */ - function revokeDelegate(address delegate) external; - - /** - * @notice Remove yourself as a delegate for a specific vault - * @param vault The vault which delegated to the msg.sender, and should be removed - */ - function revokeSelf(address vault) external; - - /** - * ----------- READ ----------- - */ - - /** - * @notice Returns all active delegations a given delegate is able to claim on behalf of - * @param delegate The delegate that you would like to retrieve delegations for - * @return info Array of DelegationInfo structs - */ - function getDelegationsByDelegate(address delegate) external view returns (DelegationInfo[] memory); - - /** - * @notice Returns an array of wallet-level delegates for a given vault - * @param vault The cold wallet who issued the delegation - * @return addresses Array of wallet-level delegates for a given vault - */ - function getDelegatesForAll(address vault) external view returns (address[] memory); - - /** - * @notice Returns an array of contract-level delegates for a given vault and contract - * @param vault The cold wallet who issued the delegation - * @param contract_ The address for the contract you're delegating - * @return addresses Array of contract-level delegates for a given vault and contract - */ - function getDelegatesForContract(address vault, address contract_) external view returns (address[] memory); - - /** - * @notice Returns an array of contract-level delegates for a given vault's token - * @param vault The cold wallet who issued the delegation - * @param contract_ The address for the contract holding the token - * @param tokenId The token id for the token you're delegating - * @return addresses Array of contract-level delegates for a given vault's token - */ - function getDelegatesForToken(address vault, address contract_, uint256 tokenId) - external - view - returns (address[] memory); - - /** - * @notice Returns all contract-level delegations for a given vault - * @param vault The cold wallet who issued the delegations - * @return delegations Array of ContractDelegation structs - */ - function getContractLevelDelegations(address vault) - external - view - returns (ContractDelegation[] memory delegations); - - /** - * @notice Returns all token-level delegations for a given vault - * @param vault The cold wallet who issued the delegations - * @return delegations Array of TokenDelegation structs - */ - function getTokenLevelDelegations(address vault) external view returns (TokenDelegation[] memory delegations); - - /** - * @notice Returns true if the address is delegated to act on the entire vault - * @param delegate The hotwallet to act on your behalf - * @param vault The cold wallet who issued the delegation - */ - function checkDelegateForAll(address delegate, address vault) external view returns (bool); - - /** - * @notice Returns true if the address is delegated to act on your behalf for a token contract or an entire vault - * @param delegate The hotwallet to act on your behalf - * @param contract_ The address for the contract you're delegating - * @param vault The cold wallet who issued the delegation - */ - function checkDelegateForContract(address delegate, address vault, address contract_) - external - view - returns (bool); - - /** - * @notice Returns true if the address is delegated to act on your behalf for a specific token, the token's contract or an entire vault - * @param delegate The hotwallet to act on your behalf - * @param contract_ The address for the contract you're delegating - * @param tokenId The token id for the token you're delegating - * @param vault The cold wallet who issued the delegation - */ - function checkDelegateForToken(address delegate, address vault, address contract_, uint256 tokenId) - external - view - returns (bool); -} -``` - -### Checking Delegation -A dApp or smart contract would check whether or not a delegate is authenticated for a vault by checking the return value of checkDelegateForAll. - -A dApp or smart contract would check whether or not a delegate can authenticated for a contract associated with a by checking the return value of checkDelegateForContract. - -A dApp or smart contract would check whether or not a delegate can authenticated for a specific token owned by a vault by checking the return value of checkDelegateForToken. - -A delegate can act on a token if they have a token level delegation, contract level delegation (for that token's contract) or vault level delegation. - -A delegate can act on a contract if they have contract level delegation or vault level delegation. - -For the purposes of saving gas, it is expected if delegation checks are performed at a smart contract level, the dApp would provide a hint to the smart contract which level of delegation the delegate has so that the smart contract can verify with the Delegation Registry using the most gas efficient check method. - -## Rationale - -### Allowing for vault, contract or token level delegation -In order to support a wide range of delegation use cases, the proposed specification allows a vault to delegate all assets it controls, assets of a specific contract, or a specific token. This ensures that a vault has fine grained control over the security of their assets, and allows for emergent behavior around granting third party wallets limited access only to assets relevant to them. - -### On-chain enumeration -In order to support ease of integration and adoption, this specification has chosen to include on-chain enumeration of delegations and incur the additional gas cost associated with supporting enumeration. On-chain enumeration allows for dApp frontends to identify the delegations that any connected wallet has access to, and can provide UI selectors. - -Without on-chain enumeration, a dApp would require the user to manually input the vault, or would need a way to index all delegate events. - - -## Reference Implementation - -## Security Considerations -The core purpose of this EIP is to enhance security and promote a safer way to authenticate wallet control and asset ownership when the main wallet is not needed and assets held by the main wallet do not need to be moved. Consider it a way to do 'read only' authentication. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5639.md diff --git a/EIPS/eip-5643.md b/EIPS/eip-5643.md index 25c70f7065b450..520d3dc92e1571 100644 --- a/EIPS/eip-5643.md +++ b/EIPS/eip-5643.md @@ -1,225 +1,7 @@ --- eip: 5643 -title: Subscription NFTs -description: Add subscription-based functionality to EIP-721 tokens -author: cygaar (@cygaar) -discussions-to: https://ethereum-magicians.org/t/eip-5643-subscription-nfts/10802 -status: Review -type: Standards Track category: ERC -created: 2022-09-10 -requires: 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes an additional interface for NFTs to be used as recurring, expirable subscriptions. The interface includes functions to renew and cancel the subscription. - -## Motivation - -NFTs are commonly used as accounts on decentralized apps or membership passes to communities, events, and more. However, it is currently rare to see NFTs like these that have a finite expiration date. The "permanence" of the blockchain often leads to memberships that have no expiration dates and thus no required recurring payments. However, for many real-world applications, a paid subscription is needed to keep an account or membership valid. - -The most prevalent on-chain application that makes use of the renewable subscription model is the Ethereum Name Service (ENS), which utilizes a similar interface to the one proposed below. Each domain can be renewed for a certain period of time, and expires if payments are no longer made. A common interface will make it easier for future projects to develop subscription-based NFTs. In the current Web2 world, it's hard for a user to see or manage all of their subscriptions in one place. With a common standard for subscriptions, it will be easy for a single application to determine the number of subscriptions a user has, see when they expire, and renew/cancel them as requested. - -Additionally, as the prevalence of secondary royalties from NFT trading disappears, creators will need new models for generating recurring income. For NFTs that act as membership or access passes, pivoting to a subscription-based model is one way to provide income and also force issuers to keep providing value. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -interface IERC5643 { - /// @notice Emitted when a subscription expiration changes - /// @dev When a subscription is canceled, the expiration value should also be 0. - event SubscriptionUpdate(uint256 indexed tokenId, uint64 expiration); - - /// @notice Renews the subscription to an NFT - /// Throws if `tokenId` is not a valid NFT - /// @param tokenId The NFT to renew the subscription for - /// @param duration The number of seconds to extend a subscription for - function renewSubscription(uint256 tokenId, uint64 duration) external payable; - - /// @notice Cancels the subscription of an NFT - /// @dev Throws if `tokenId` is not a valid NFT - /// @param tokenId The NFT to cancel the subscription for - function cancelSubscription(uint256 tokenId) external payable; - - /// @notice Gets the expiration date of a subscription - /// @dev Throws if `tokenId` is not a valid NFT - /// @param tokenId The NFT to get the expiration date of - /// @return The expiration date of the subscription - function expiresAt(uint256 tokenId) external view returns(uint64); - - /// @notice Determines whether a subscription can be renewed - /// @dev Throws if `tokenId` is not a valid NFT - /// @param tokenId The NFT to get the expiration date of - /// @return The renewability of a the subscription - function isRenewable(uint256 tokenId) external view returns(bool); -} -``` - -The `expiresAt(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `isRenewable(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `renewSubscription(uint256 tokenId, uint64 duration)` function MAY be implemented as `external` or `public`. - -The `cancelSubscription(uint256 tokenId)` function MAY be implemented as `external` or `public`. - -The `SubscriptionUpdate` event MUST be emitted whenever the expiration date of a subscription is changed. - -The `supportsInterface` method MUST return `true` when called with `0x8c65f84d`. - -## Rationale - -This standard aims to make on-chain subscriptions as simple as possible by adding the minimal required functions and events for implementing on-chain subscriptions. It is important to note that in this interface, the NFT itself represents ownership of a subscription, there is no facilitation of any other fungible or non-fungible tokens. - -### Subscription Management - -Subscriptions represent agreements to make advanced payments in order to receive or participate in something. In order to facilitate these agreements, a user must be able to renew or cancel their subscriptions hence the `renewSubscription` and `cancelSubscription` functions. It also important to know when a subscription expires - users will need this information to know when to renew, and applications need this information to determine the validity of a subscription NFT. The `expiresAt` function provides this functionality. Finally, it is possible that a subscription may not be renewed once expired. The `isRenewable` function gives users and applications that information. - -### Easy Integration - -Because this standard is fully EIP-721 compliant, existing protocols will be able to facilitate the transfer of subscription NFTs out of the box. With only a few functions to add, protocols will be able to fully manage a subscription's expiration, determine whether a subscription is expired, and see whether it can be renewed. - -## Backwards Compatibility - -This standard can be fully EIP-721 compatible by adding an extension function set. - -The new functions introduced in this standard add minimal overhead to the existing EIP-721 interface, which should make adoption straightforward and quick for developers. - -## Test Cases - -The following tests require Foundry. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.13; - -import "forge-std/Test.sol"; -import "../src/ERC5643.sol"; - -contract ERC5643Mock is ERC5643 { - constructor(string memory name_, string memory symbol_) ERC5643(name_, symbol_) {} - - function mint(address to, uint256 tokenId) public { - _mint(to, tokenId); - } -} - -contract ERC5643Test is Test { - event SubscriptionUpdate(uint256 indexed tokenId, uint64 expiration); - - address user1; - uint256 tokenId; - ERC5643Mock erc5643; - - function setUp() public { - tokenId = 1; - user1 = address(0x1); - - erc5643 = new ERC5643Mock("erc5369", "ERC5643"); - erc5643.mint(user1, tokenId); - } - - function testRenewalValid() public { - vm.warp(1000); - vm.prank(user1); - vm.expectEmit(true, true, false, true); - emit SubscriptionUpdate(tokenId, 3000); - erc5643.renewSubscription(tokenId, 2000); - } - - function testRenewalNotOwner() public { - vm.expectRevert("Caller is not owner nor approved"); - erc5643.renewSubscription(tokenId, 2000); - } - - function testCancelValid() public { - vm.prank(user1); - vm.expectEmit(true, true, false, true); - emit SubscriptionUpdate(tokenId, 0); - erc5643.cancelSubscription(tokenId); - } - - function testCancelNotOwner() public { - vm.expectRevert("Caller is not owner nor approved"); - erc5643.cancelSubscription(tokenId); - } - - function testExpiresAt() public { - vm.warp(1000); - - assertEq(erc5643.expiresAt(tokenId), 0); - vm.startPrank(user1); - erc5643.renewSubscription(tokenId, 2000); - assertEq(erc5643.expiresAt(tokenId), 3000); - - erc5643.cancelSubscription(tokenId); - assertEq(erc5643.expiresAt(tokenId), 0); - } -} -``` - -## Reference Implementation - -Implementation: `ERC5643.sol` - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.13; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./IERC5643.sol"; - -contract ERC5643 is ERC721, IERC5643 { - mapping(uint256 => uint64) private _expirations; - - constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {} - - function renewSubscription(uint256 tokenId, uint64 duration) external payable { - require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); - - uint64 currentExpiration = _expirations[tokenId]; - uint64 newExpiration; - if (currentExpiration == 0) { - newExpiration = uint64(block.timestamp) + duration; - } else { - if (!_isRenewable(tokenId)) { - revert SubscriptionNotRenewable(); - } - newExpiration = currentExpiration + duration; - } - - _expirations[tokenId] = newExpiration; - - emit SubscriptionUpdate(tokenId, newExpiration); - } - - function cancelSubscription(uint256 tokenId) external payable { - require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); - delete _expirations[tokenId]; - emit SubscriptionUpdate(tokenId, 0); - } - - function expiresAt(uint256 tokenId) external view returns(uint64) { - return _expirations[tokenId]; - } - - function isRenewable(uint256 tokenId) external pure returns(bool) { - return true; - } - - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC5643).interfaceId || super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations - -This EIP standard does not affect ownership of an NFT and thus can be considered secure. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5643.md diff --git a/EIPS/eip-5646.md b/EIPS/eip-5646.md index db381c1f58fac1..5ca4900bbca46d 100644 --- a/EIPS/eip-5646.md +++ b/EIPS/eip-5646.md @@ -1,119 +1,7 @@ --- eip: 5646 -title: Token State Fingerprint -description: Unambiguous token state identifier -author: Naim Ashhab (@ashhanai) -discussions-to: https://ethereum-magicians.org/t/eip-5646-discussion-token-state-fingerprint/10808 -status: Final -type: Standards Track category: ERC -created: 2022-09-11 -requires: 165 +status: Moved --- -## Abstract - -This specification defines the minimum interface required to unambiguously identify the state of a mutable token without knowledge of implementation details. - -## Motivation - -Currently, protocols need to know about tokens' state properties to create the unambiguous identifier. Unfortunately, this leads to an obvious bottleneck in which protocols need to support every new token specifically. - -![](../assets/eip-5646/support-per-abi.png) - -## Specification - -The key words "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", and "MAY" in this document are to be interpreted as described in RFC 2119. - -```solidity -pragma solidity ^0.8.0; - -interface ERC5646 is ERC165 { - - /// @notice Function to return current token state fingerprint. - /// @param tokenId Id of a token state in question. - /// @return Current token state fingerprint. - function getStateFingerprint(uint256 tokenId) external view returns (bytes32); - -} -``` - -- `getStateFingerprint` MUST return a different value when the token state changes. -- `getStateFingerprint` MUST NOT return a different value when the token state remains the same. -- `getStateFingerprint` MUST include all state properties that might change during the token lifecycle (are not immutable). -- `getStateFingerprint` MAY include computed values, such as values based on a current timestamp (e.g., expiration, maturity). -- `getStateFingerprint` MAY include token metadata URI. -- `supportsInterface(0xf5112315)` MUST return `true`. - -## Rationale - -Protocols can use state fingerprints as a part of a token identifier and support mutable tokens without knowing any state implementation details. - -![](../assets/eip-5646/support-per-eip.png) - -State fingerprints don't have to factor in state properties that are immutable, because they can be safely identified by a token id. - -This standard is not for use cases where token state property knowledge is required, as these cases cannot escape the bottleneck problem described earlier. - -## Backwards Compatibility - -This EIP is not introducing any backward incompatibilities. - -## Reference Implementation - -```solidity -pragma solidity ^0.8.0; - -/// @title Example of a mutable token implementing state fingerprint. -contract LPToken is ERC721, ERC5646 { - - /// @dev Stored token states (token id => state). - mapping (uint256 => State) internal states; - - struct State { - address asset1; - address asset2; - uint256 amount1; - uint256 amount2; - uint256 fee; // Immutable - address operator; // Immutable - uint256 expiration; // Parameter dependent on a block.timestamp - } - - - /// @dev State fingerprint getter. - /// @param tokenId Id of a token state in question. - /// @return Current token state fingerprint. - function getStateFingerprint(uint256 tokenId) override public view returns (bytes32) { - State storage state = states[tokenId]; - - return keccak256( - abi.encode( - state.asset1, - state.asset2, - state.amount1, - state.amount2, - // state.fee don't need to be part of the fingerprint computation as it is immutable - // state.operator don't need to be part of the fingerprint computation as it is immutable - block.timestamp >= state.expiration - ) - ); - } - - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return super.supportsInterface(interfaceId) || - interfaceId == type(ERC5646).interfaceId; - } - -} -``` - -## Security Considerations - -Token state fingerprints from two different contracts may collide. Because of that, they should be compared only in the context of one token contract. - -If the `getStateFingerprint` implementation does not include all parameters that could change the token state, a token owner would be able to change the token state without changing the token fingerprint. It could break the trustless assumptions of several protocols, which create, e.g., buy offers for tokens. The token owner would be able to change the state of the token before accepting an offer. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5646.md diff --git a/EIPS/eip-5656.md b/EIPS/eip-5656.md index f9abca0a7e1a9d..d0cd8902e2243b 100644 --- a/EIPS/eip-5656.md +++ b/EIPS/eip-5656.md @@ -1,10 +1,10 @@ --- eip: 5656 -title: Memory copying instruction +title: MCOPY - Memory copying instruction description: An efficient EVM instruction for copying memory areas author: Alex Beregszaszi (@axic), Paul Dworzanski (@poemm), Jared Wasinger (@jwasinger), Casey Detrio (@cdetrio), Pawel Bylica (@chfast), Charles Cooper (@charles-cooper) discussions-to: https://ethereum-magicians.org/t/eip-5656-mcopy-instruction/10890 -status: Draft +status: Final type: Standards Track category: Core created: 2021-02-01 @@ -33,6 +33,7 @@ masked, or'd, and stored again. This overhead is significant. One edge case is i it can be efficiently stored using `MSTORE8`. As example use case, copying 256 bytes costs: + - at least 757 gas pre-EIP-2929 using the identity precompile - at least 157 gas post-EIP-2929 using the identity precompile - at least 96 gas using unrolled `MLOAD`/`MSTORE` instructions @@ -55,7 +56,7 @@ where it is identified as a significant overhead. ## Specification -The instruction `MCOPY` is introduced at `0x5c`. +The instruction `MCOPY` is introduced at `0x5E`. ### Input stack @@ -67,14 +68,25 @@ The instruction `MCOPY` is introduced at `0x5c`. This ordering matches the other copying instructions, i.e. `CALLDATACOPY`, `RETURNDATACOPY`. +### Gas costs + +Per yellow paper terminology, it should be considered part of the `W_copy` group of opcodes, and follow the gas calculation for `W_copy` in the yellow paper. While the calculation in the yellow paper should be considered the final word, for reference, as of time of this writing, that currently means its gas cost is: + +``` +words_copied = (length + 31) // 32 +g_verylow = 3 +g_copy = 3 * words_copied + memory_expansion_cost +gas_cost = g_verylow + g_copy +``` + ### Output stack -This instructions returns no stack items. +This instruction returns no stack items. ### Semantics It copies `length` bytes from the offset pointed at `src` to the offset pointed at `dst` in memory. -Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap. +Copying takes place as if an intermediate buffer was used, allowing the destination and source to overlap. If `length > 0` and (`src + length` or `dst + length`) is beyond the current memory length, the memory is extended with respective gas cost applied. @@ -89,15 +101,83 @@ This is still prohibitive for making the precompile a reasonable alternative aga ## Backwards Compatibility -This EIP introduces a new instruction which did not exists previously. Already deployed contracts using this instruction could change their behaviour after this EIP. +This EIP introduces a new instruction which did not exist previously. Already deployed contracts using this instruction could change their behaviour after this EIP. ## Test Cases -TBA +`MCOPY 0 32 32` - copy 32 bytes from offset 32 to offset 0. + +pre (spaces included for readability): + +``` +0000000000000000000000000000000000000000000000000000000000000000 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f +``` + +post: + +``` +000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f +``` + +gas used: 6 + +`MCOPY 0 0 32` - copy 32 bytes from offset 0 to offset 0. + +pre: + +``` +0101010101010101010101010101010101010101010101010101010101010101 +``` + +post: + +``` +0101010101010101010101010101010101010101010101010101010101010101 +``` + +gas used: 6 + +`MCOPY 0 1 8` - copy 8 bytes from offset 1 to offset 0 (overlapping). + +pre (space at byte 8): + +``` +0001020304050607 080000000000000000000000000000000000000000000000 +``` + +post: + +``` +0102030405060708 080000000000000000000000000000000000000000000000 +``` + +gas used: 6 + +`MCOPY 1 0 8` - copy 8 bytes from offset 0 to offset 1 (overlapping). + +pre (space at byte 8): + +``` +0001020304050607 080000000000000000000000000000000000000000000000 +``` + +post: + +``` +0000010203040506 070000000000000000000000000000000000000000000000 +``` + +gas used: 6 + +### Full test suite + +A full suite of tests can be found in the execution spec tests: [MCOPY suite](https://github.com/ethereum/execution-spec-tests/tree/c0065176a79f89d93f4c326186fc257ec5b8d5f1/tests/cancun/eip5656_mcopy). ## Security Considerations -TBA +Clients should take care that their implementation does not use an intermediate buffer (see for instance that the C stdlib `memmove` function does not use an intermediate buffer), as this is a potential Denial of Service (DoS) vector. Most language builtins / standard library functions for moving bytes have the correct performance characteristics here. + +This aside, the analysis for Denial of Service (DoS) and memory exhaustion attacks is identical to other opcodes which touch memory, as the memory expansion follows the same pricing rules. ## Copyright diff --git a/EIPS/eip-5679.md b/EIPS/eip-5679.md index 988127a5bb524c..9b7fe22dfd6dc5 100644 --- a/EIPS/eip-5679.md +++ b/EIPS/eip-5679.md @@ -1,124 +1,7 @@ --- eip: 5679 -title: Token Minting and Burning -description: An extension for minting and burning EIP-20, EIP-721, and EIP-1155 tokens -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-5679-mint-and-burn-tokens/10913 -status: Final -type: Standards Track category: ERC -created: 2022-09-17 -requires: 20, 165, 721, 1155 +status: Moved --- -## Abstract - -This EIP introduces a consistent way to extend token standards for minting and burning. - -## Motivation - -Minting and Burning are typical actions for creating and destroying tokens. -By establishing a consistent way to mint and burn a token, we complete the basic lifecycle. - -Some implementations of [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) -have been able to use `transfer` methods or the-like -to mint and burn tokens. However, minting and burning change token supply. The access controls -of minting and burning also usually follow different rules than transfer. -Therefore, creating separate methods for burning and minting simplifies implementations -and reduces security error. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -1. Any contract complying with [EIP-20](./eip-20.md) when extended with this EIP, -**MUST** implement the following interface: - -```solidity -// The EIP-165 identifier of this interface is 0xd0017968 -interface IERC5679Ext20 { - function mint(address _to, uint256 _amount, bytes calldata _data) external; - function burn(address _from, uint256 _amount, bytes calldata _data) external; -} -``` - -2. Any contract complying with [EIP-721](./eip-721.md) when extended with this EIP, -**MUST** implement the following interface: - -```solidity -// The EIP-165 identifier of this interface is 0xcce39764 -interface IERC5679Ext721 { - function safeMint(address _to, uint256 _id, bytes calldata _data) external; - function burn(address _from, uint256 _id, bytes calldata _data) external; -} -``` - -3. Any contract complying with [EIP-1155](./eip-1155.md) when extended with this EIP, -**MUST** implement the following interface: - -```solidity -// The EIP-165 identifier of this interface is 0xf4cedd5a -interface IERC5679Ext1155 { - function safeMint(address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; - function safeMintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; - function burn(address _from, uint256 _id, uint256 _amount, bytes[] calldata _data) external; - function burnBatch(address _from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata _data) external; -} -``` - -4. When the token is being minted, the transfer events **MUST** be emitted as if -the token in the `_amount` for EIP-20 and EIP-1155 and token id being `_id` for EIP-721 and EIP-1155 -were transferred from address `0x0` to the recipient address identified by `_to`. -The total supply **MUST** increase accordingly. - -5. When the token is being burned, the transfer events **MUST** be emitted as if -the token in the `_amount` for EIP-20 and EIP-1155 and token id being `_id` for EIP-721 and EIP-1155 -were transferred from the recipient address identified by `_to` to the address of `0x0`. -The total supply **MUST** decrease accordingly. - -6. `safeMint` MUST implement the same receiver restrictions as `safeTransferFrom` as defined in -[EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). - -7. It's RECOMMENDED for the client to implement [EIP-165](./eip-165.md) identifiers as specified above. - -## Rationale - -1. It's possible that the interface be consolidated to the same as EIP-1155 which is always bearing `_amount` field, -regardless of whether it's a EIP-20, EIP-721 or EIP-1155. But we choose that each ERC token should have their own -standard way of representing the amount of token to follow the same way of `_id` and `_amount` in their original -token standard. - -2. We have chosen to identify the interface with [EIP-165](./eip-165.md) identifiers each individually, -instead of having a single identifier because the signatures of interface are different. - -3. We have chosen NOT to create new events but to require the usage of existing transfer event as required by EIP-20 -EIP-721 and EIP-1155 for maximum compatibility. - -4. We have chosen to add `safeMintBatch` and `burnBatch` methods for EIP-1155 but not for EIP-721 to follow the -convention of EIP-721 and EIP-1155 respectively. - -5. We have not add extension for [EIP-777](./eip-777.md) because it already handles Minting and Burning. - -## Backwards Compatibility - -This EIP is designed to be compatible for EIP-20, EIP-721 and EIP-1155 respectively. - -## Security Considerations - -This EIP depends on the security soundness of the underlying book keeping behavior of the token implementation. -In particular, a token contract should carefully design the access control for which role is granted permission -to mint a new token. Failing to safe guard such behavior can cause fraudulent issuance and an elevation of total supply. - -The burning should also carefully design the access control. Typically only the following two roles are entitled to burn a token: - -- Role 1. The current token holder -- Role 2. An role with special privilege. - -Either Role 1 OR Role 2 or a consensus between the two are entitled to conduct the burning action. -However as author of this EIP we do recognize there are potentially other use case where a third type of role shall be entitled -to burning. We keep this EIP less opinionated in such restriction but implementors should be cautious about designing -the restriction. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5679.md diff --git a/EIPS/eip-5700.md b/EIPS/eip-5700.md index 0de0f5c8ae402c..7a4b05e72f0c99 100644 --- a/EIPS/eip-5700.md +++ b/EIPS/eip-5700.md @@ -1,826 +1,7 @@ --- eip: 5700 -title: Bindable Token Interface -description: Interface for binding fungible and non-fungible tokens to assets. -author: Leeren (@leeren) -discussions-to: https://ethereum-magicians.org/t/eip-5700-bindable-token-standard/11077 -status: Draft -type: Standards Track category: ERC -created: 2022-09-22 -requires: 165, 721, 1155 +status: Moved --- -## Abstract - -The proposed standard defines an interface by which fungible and non-fungible tokens may be bound to arbitrary assets (typically represented as NFTs themselves), enabling token ownership and transfer attribution to be proxied through the assets they are bound to. - -A bindable token ("bindable") is an [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md) token which, when bound to an asset, delegates ownership and tracking through its bound asset, remaining locked for direct transfers until it is unbound. When unbound, bindable tokens function normally according to their base token implementations. - -A bound asset ("binder") has few restrictions on how it is represented, except that it be unique and expose an interface for ownership queries. A binder would most commonly be represented as an [EIP-721](./eip-721.md) NFT. Binders and bindables form a one-to-many relationship. - -Below are example use-cases that benefit from such a standard: - -- NFT-bundled physical assets: microchipped streetwear bundles, digitized automobile collections, digitally-twinned real-estate property -- NFT-bundled digital assets: accessorizable virtual wardrobes, composable music tracks, customizable metaverse land - -## Motivation - -A standard interface for token binding allows tokens to be bundled and transferred with other assets in a way that is easily integrable with wallets, marketplaces, and other NFT applications, and avoids the need for ad-hoc ownership attribution strategies that are neither flexible nor backwards-compatible. - -Unlike other standards tackling delegated ownership attribution, which look at composability on the account level, this standard addresses composability on the asset level, with the goal of creating a universal interface for token modularity that is compatible with existing [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md) standards. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### EIP-721 Bindable - -**Smart contracts implementing the EIP-721 bindable standard MUST implement the `IERC721Bindable` interface.** - -**Implementers of the `IER721Bindable` interface MUST return `true` if `0x82a34a7d` is passed as the identifier to the `supportsInterface` function.** - -```solidity -/// @title ERC-721 Bindable Token Standard -/// @dev See https://eips.ethereum.org/EIPS/eip-5700 -/// Note: the ERC-165 identifier for this interface is 0x82a34a7d. -interface IERC721Bindable /* is IERC721 */ { - - /// @notice The `Bind` event MUST emit when NFT ownership is delegated - /// through an asset and when minting an NFT bound to an existing asset. - /// @dev When minting bound NFTs, `from` MUST be set to the zero address. - /// @param operator The address calling the bind. - /// @param from The unbound NFT owner address. - /// @param to The bound NFT owner delegate address. - /// @param tokenId The identifier of the NFT being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param bindAddress The contract address handling asset ownership. - event Bind( - address indexed operator, - address indexed from, - address to, - uint256 tokenId, - uint256 bindId, - address indexed bindAddress - ); - - /// @notice The `Unbind` event MUST emit when asset-bound NFT ownership is - /// revoked, as well as when burning an NFT bound to an existing asset. - /// @dev When burning bound NFTs, `to` MUST be set to the zero address. - /// @param operator The address calling the unbind. - /// @param from The bound asset owner address. - /// @param to The unbound NFT owner address. - /// @param tokenId The identifier of the NFT being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - event Unbind( - address indexed operator, - address indexed from, - address to, - uint256 tokenId, - uint256 bindId, - address indexed bindAddress - ); - - /// @notice Binds NFT `tokenId` owned by `from` to asset `bindId` at address - /// `bindAddress`, delegating NFT-bound ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is the current owner, - /// an authorized operator, or the approved address for the NFT. It also - /// MUST throw if the NFT is already bound, if `from` is not the NFT owner, - /// or if `to` is not `bindAddress` or its asset owner. After binding, the - /// function MUST check if `bindAddress` is a valid contract / (code size - /// > 0), and if so, call `onERC721Bind` on it, throwing if the wrong - /// identifier is returned (see "Binding Rules") or if the contract is - /// invalid. On bind completion, the function MUST emit `Bind` & `Transfer` - /// events to reflect delegated ownership change. - /// @param from The unbound NFT original owner address. - /// @param to The bound NFT delegate owner address (SHOULD be `bindAddress`). - /// @param tokenId The identifier of the NFT being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param bindAddress The contract address handling asset ownership. - /// @param data Additional data sent with the `onERC721Bind` hook. - function bind( - address from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Unbinds NFT `tokenId` from asset `bindId` owned by `from` at - /// address `bindAddress`, assigning unbound NFT ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is the asset owner or - /// an approved operator. It also MUST throw if NFT `tokenId` is not bound, - /// if `from` is not the asset owner, or if `to` is the zero address. After - /// unbinding, the function MUST check if `bindAddress` is a valid contract - /// (code size > 0), and if so, call `onERC721Unbind` on it, throwing if - /// the wrong identifier is returned (see "Binding Rules") or if the - /// contract is invalid. The function also MUST check if `to` is a valid - /// contract, and if so, call `onERC721Received`, throwing if the wrong - /// identifier is returned. On unbind completion, the function MUST emit - /// `Unbind` & `Transfer` events to reflect delegated ownership change. - /// @param from The bound asset owner address. - /// @param to The unbound NFT owner address. - /// @param tokenId The identifier of the NFT being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param data Additional data sent with the `onERC721Unbind` hook. - function unbind( - address from, - address to, - uint256 tokenId, - uint256 bindId, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Gets the asset identifier and address which an NFT is bound to. - /// @param tokenId The identifier of the NFT being queried. - /// @return The bound asset identifier and contract address. - function binderOf(uint256 tokenId) external returns (uint256, address); - - /// @notice Counts NFTs bound to asset `bindId` at address `bindAddress`. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param bindId The identifier of the bound asset. - /// @return The total number of NFTs bound to the asset. - function boundBalanceOf(address bindAddress, uint256 bindId) external returns (uint256); - -``` - -**Smart contracts managing assets MUST implement the `IERC721Binder` interface if they are to accept binds from EIP-721 bindables.** - -**Implementers of the `IERC721Binder` interface MUST return `true` if `0x2ac2d2bc` is passed as the identifier to the `supportsInterface` function.** - -```solidity -/// @dev Note: the ERC-165 identifier for this interface is 0x2ac2d2bc. -interface IERC721Binder /* is IERC165 */ { - - /// @notice Handles the binding of an IERC721Bindable-compliant NFT. - /// @dev An IERC721Bindable-compliant smart contract MUST call this function - /// at the end of a `bind` after ownership is delegated through an asset. - /// The function MUST revert if `to` is not the asset owner or the binder - /// address. The function MUST revert if it rejects the bind. If accepting - /// the bind, the function MUST return `bytes4(keccak256("onERC721Bind(address,address,address,uint256,uint256,bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the binding NFT is `msg.sender`. - /// @param operator The address initiating the bind. - /// @param from The unbound NFT owner address. - /// @param to The bound NFT owner delegate address. - /// @param tokenId The identifier of the NFT being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param data Additional data sent along with no specified format. - /// @return `bytes4(keccak256("onERC721Bind(address,address,address,uint256,uint256,bytes)"))` - function onERC721Bind( - address operator, - address from, - address to, - uint256 tokenId, - uint256 bindId, - bytes calldata data - ) external returns (bytes4); - - /// @notice Handles the unbinding of an IERC721Bindable-compliant NFT. - /// @dev An IERC721Bindable-compliant smart contract MUST call this function - /// at the end of an `unbind` after revoking asset-delegated ownership. - /// The function MUST revert if `from` is not the asset owner of `bindId`. - /// The function MUST revert if it rejects the unbind. If accepting the - /// unbind, the function MUST return `bytes4(keccak256("onERC721Unbind(address,address,address,uint256,uint256,bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the unbinding NFT is `msg.sender`. - /// @param from The bound asset owner address. - /// @param to The unbound NFT owner address. - /// @param tokenId The identifier of the NFT being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param data Additional data with no specified format. - /// @return `bytes4(keccak256("onERC721Unbind(address,address,address,uint256,uint256,bytes)"))` - function onERC721Unbind( - address operator, - address from, - address to, - uint256 tokenId, - uint256 bindId, - bytes calldata data - ) external returns (bytes4); - - /// @notice Gets the owner address of the asset identified by `bindId`. - /// @dev This function MUST throw for assets assigned to the zero address. - /// @param bindId The identifier of the asset whose owner is being queried. - /// @return The address of the owner of the asset. - function ownerOf(uint256 bindId) external view returns (address); - - /// @notice Checks if an operator can act on behalf of an asset owner. - /// @param owner The address that owns an asset. - /// @param operator The address that can act on behalf of the asset owner. - /// @return True if `operator` can act on behalf of `owner`, else False. - function isApprovedForAll(address owner, address operator) external view returns (bool); - -} -``` - -### EIP-1155 Bindable - -**Smart contracts implementing the EIP-1155 Bindable standard MUST implement the `IERC1155Bindable` interface.** - -**Implementers of the `IER1155Bindable` interface MUST return `true` if `0xd0d55c6` is passed as the identifier to the `supportsInterface` function.** - -```solidity -/// @title ERC-1155 Bindable Token Standard -/// @dev See https://eips.ethereum.org/EIPS/eip-5700 -/// Note: the ERC-165 identifier for this interface is 0xd0d555c6. -interface IERC1155Bindable /* is IERC1155 */ { - - /// @notice The `Bind` event MUST emit when token ownership is delegated - /// through an asset and when minting tokens bound to an existing asset. - /// @dev When minting bound tokens, `from` MUST be set to the zero address. - /// @param operator The address calling the bind. - /// @param from The owner address of the unbound tokens. - /// @param to The delegate owner address of the bound tokens. - /// @param tokenId The identifier of the token type being bound. - /// @param amount The number of tokens of type `tokenId` being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param bindAddress The contract address handling asset ownership. - event Bind( - address indexed operator, - address indexed from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - address indexed bindAddress - ); - - /// @notice The `BindBatch` event MUST emit when token ownership of - /// different token types are delegated through multiple assets and when - /// minting different token types bound to multiple existing assets. - /// @dev When minting bound tokens, `from` MUST be set to the zero address. - /// @param operator The address calling the bind. - /// @param from The owner address of the unbound tokens. - /// @param to The delegate owner address of the bound tokens. - /// @param tokenIds The identifiers of the token types being bound. - /// @param amounts The number of tokens for each token type being bound. - /// @param bindIds The identifiers of the assets being bound to. - /// @param bindAddress The contract address handling asset ownership. - event BindBatch( - address indexed operator, - address indexed from, - address to, - uint256[] tokenIds, - uint256[] amounts, - uint256[] bindIds, - address indexed bindAddress - ); - - /// @notice The `Unbind` event MUST emit when asset-delegated token - /// ownership is revoked and when burning tokens bound to existing assets. - /// @dev When burning bound tokens, `to` MUST be set to the zero address. - /// @param operator The address calling the unbind. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenId The identifier of the token type being unbound. - /// @param amount The number of tokens of type `tokenId` being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - event Unbind( - address indexed operator, - address indexed from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - address indexed bindAddress - ); - - /// @notice The `UnbindBatch` event MUST emit when asset-delegated token - /// ownership is revoked for different token types and when burning - /// different token types bound to multiple existing assets. - /// @dev When burning bound tokens, `to` MUST be set to the zero address. - /// @param operator The address calling the unbind. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenIds The identifiers of the token types being unbound. - /// @param amounts The number of tokens for each token type being unbound. - /// @param bindIds The identifiers of the assets being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - event UnbindBatch( - address indexed operator, - address indexed from, - address to, - uint256[] tokenIds, - uint256[] amounts, - uint256[] bindIds, - address indexed bindAddress - ); - - /// @notice Binds `amount` tokens of type `tokenId` owned by `from` to asset - /// `bindId` at `bindAddress`, delegating token-bound ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is an approved operator - /// for `from`. The function also MUST throw if `from` owns fewer than - /// `amount` tokens, or if `to` is not `bindAddress` or its asset owner. - /// After binding, the function MUST check if `bindAddress` is a valid - /// contract (code size > 0), and if so, call `onERC1155Bind` on it, - /// throwing if the wrong identifier is returned (see "Binding Rules") or - /// if the contract is invalid. On bind completion, the function MUST emit - /// `Bind` & `TransferSingle` events to reflect delegated ownership change. - /// @param from The owner address of the unbound tokens. - /// @param to The delegate owner address of the bound tokens (SHOULD be `bindAddress`). - /// @param tokenId The identifier of the token type being bound. - /// @param amount The number of tokens of type `tokenId` being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param bindAddress The contract address handling asset ownership. - /// @param data Additional data sent with the `onERC1155Bind` hook. - function bind( - address from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Binds `amounts` tokens of types `tokenIds` owned by `from` to - /// assets `bindIds` at `bindAddress`, delegating bound ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is an approved operator - /// for `from`. The function also MUST throw if length of `amounts` is not - /// the same as `tokenIds` or `bindIds`, if any balances of `tokenIds` for - /// `from` is less than that of `amounts`, or if `to` is not `bindAddress` - /// or the asset owner. After delegating ownership, the function MUST check - /// if `bindAddress` is a valid contract (code size > 0), and if so, call - /// `onERC1155BatchBind` on it, throwing if the wrong identifier is - /// returned (see "Binding Rules") or if the contract is invalid. On bind - /// completion, the function MUST emit `BindBatch` & `TransferBatch` events - /// to reflect delegated ownership changes. - /// @param from The owner address of the unbound tokens. - /// @param to The delegate owner address of the bound tokens (SHOULD be `bindAddress`). - /// @param tokenIds The identifiers of the token types being bound. - /// @param amounts The number of tokens for each token type being bound. - /// @param bindIds The identifiers of the assets being bound to. - /// @param bindAddress The contract address handling asset ownership. - /// @param data Additional data sent with the `onERC1155BatchBind` hook. - function batchBind( - address from, - address to, - uint256[] calldata tokenIds, - uint256[] calldata amounts, - uint256[] calldata bindIds, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Revokes delegated ownership of `amount` tokens of type `tokenId` - /// owned by `from` bound to `bindId`, switching ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is the asset owner or - /// an approved operator. It also MUST throw if `from` is not the asset - /// owner, if fewer than `amount` tokens are bound to the asset, or if `to` - /// is the zero address. Once delegated ownership is revoked, the function - /// MUST check if `bindAddress` is a valid contract (code size > 0), and if - /// so, call `onERC1155Unbind` on it, throwing if the wrong identifier is - /// returned (see "Binding Rules") or if the contract is invalid. The - /// function also MUST check if `to` is a contract, and if so, call on it - /// `onERC1155Received`, throwing if the wrong identifier is returned. On - /// unbind completion, the function MUST emit `Unbind` & `TransferSingle` - /// events to reflect delegated ownership change. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenId The identifier of the token type being unbound. - /// @param amount The number of tokens of type `tokenId` being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param data Additional data sent with the `onERC1155Unbind` hook. - function unbind( - address from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Revokes delegated ownership of `amounts` tokens of `tokenIds` - /// owned by `from` bound to assets `bindIds`, switching ownership to `to`. - /// @dev The function MUST throw unless `msg.sender` is the assets' owner or - /// approved operator. It also MUST throw if the length of `amounts` is not - /// the same as `tokenIds` or `bindIds`, if `from` is not the owner of all - /// assets, if any count in `amounts` is fewer than the number of tokens - /// bound for the corresponding token-asset pair given by `tokenIds` and - /// `bindIds`, or if `to` is the zero address. Once delegated ownership is - /// revoked for all tokens, the function MUST check if `bindAddress` is a - /// valid contract (code size > 0), and if so, call `onERC1155BatchUnbind` - /// on it, throwing if a wrong identifier is returned (see "Binding Rules") - /// or if the contract is invalid. The function also MUST check if `to` is - /// valid contract, and if so, call `onERC1155BatchReceived` on it, - /// throwing if the wrong identifier is returned. On unbind completion, the - /// function MUST emit `BatchUnbind` and `TransferBatch` events to reflect - /// delegated ownership change. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenIds The identifiers of the token types being unbound. - /// @param amounts The number of tokens for each token type being unbound. - /// @param bindIds The identifier of the assets being unbound from. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param data Additional data sent with the `onERC1155BatchUnbind` hook. - function batchUnbind( - address from, - address to, - uint256[] calldata tokenIds, - uint256[] calldata amounts, - uint256[] calldata bindIds, - address bindAddress, - bytes calldata data - ) external; - - /// @notice Gets the balance of bound tokens of type `tokenId` bound to the - /// asset `bindId` at address `bindAddress`. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param bindId The identifier of the bound asset. - /// @param tokenId The identifier of the counted bound token type. - /// @return The total number of tokens of type `tokenId` bound to the asset. - function boundBalanceOf( - address bindAddress, - uint256 bindId, - uint256 tokenId - ) external returns (uint256); - - /// @notice Gets the balance of bound tokens for multiple token types given - /// by `tokenIds` bound to assets `bindIds` at address `bindAddress`. - /// @param bindAddress The contract address handling bound asset ownership. - /// @param bindIds List of bound asset identifiers. - /// @param tokenIds The identifiers of the counted bound token types. - /// @return balances The bound balances for each asset / token type pair. - function boundBalanceOfBatch( - address bindAddress, - uint256[] calldata bindIds, - uint256[] calldata tokenIds - ) external returns (uint256[] memory balances); - -} -``` - -**Smart contracts managing assets MUST implement the `IERC1155Binder` interface if they are to accept binds from EIP-1155 bindables.** - -**Implementers of the `IERC1155Binder` interface MUST return `true` if `0x6fc97e78` is passed as the identifier to the `supportsInterface` function.** - -```solidity -pragma solidity ^0.8.16; - -/// @dev Note: the ERC-165 identifier for this interface is 0x6fc97e78. -interface IERC1155Binder /* is IERC165 */ { - - /// @notice Handles binding of an IERC1155Bindable-compliant token type. - /// @dev An IERC1155Bindable-compliant smart contract MUST call this - /// function at the end of a `bind` after ownership is delegated through an - /// asset. The function MUST revert if `to` is not the asset owner or - /// binder address. The function MUST revert if it rejects the bind. If - /// accepting the bind, the function MUST return `bytes4(keccak256("onERC1155Bind(address,address,address,uint256,uint256,uint256,bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the binding token is `msg.sender`. - /// @param operator The address responsible for binding. - /// @param from The owner address of the unbound tokens. - /// @param to The delegate owner address of the bound tokens. - /// @param tokenId The identifier of the token type being bound. - /// @param bindId The identifier of the asset being bound to. - /// @param data Additional data sent along with no specified format. - /// @return `bytes4(keccak256("onERC1155Bind(address,address,address,uint256,uint256,uint256,bytes)"))` - function onERC1155Bind( - address operator, - address from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - bytes calldata data - ) external returns (bytes4); - - /// @notice Handles binding of multiple IERC1155Bindable-compliant tokens - /// `tokenIds` to multiple assets `bindIds`. - /// @dev An IERC1155Bindable-compliant smart contract MUST call this - /// function at the end of a `batchBind` after delegating ownership of - /// multiple token types to the asset owner. The function MUST revert if - /// `to` is not the asset owner or binder address. The function MUST revert - /// if it rejects the bind. If accepting the bind, the function MUST return - /// `bytes4(keccak256("onERC1155BatchBind(address,address,address,uint256[],uint256[],uint256[],bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the binding token is `msg.sender`. - /// @param operator The address responsible for performing the binds. - /// @param from The unbound tokens' original owner address. - /// @param to The bound tokens' delegate owner address (SHOULD be `bindAddress`). - /// @param tokenIds The list of token types being bound. - /// @param amounts The number of tokens for each token type being bound. - /// @param bindIds The identifiers of the assets being bound to. - /// @param data Additional data sent along with no specified format. - /// @return `bytes4(keccak256("onERC1155Bind(address,address,address,uint256[],uint256[],uint256[],bytes)"))` - function onERC1155BatchBind( - address operator, - address from, - address to, - uint256[] calldata tokenIds, - uint256[] calldata amounts, - uint256[] calldata bindIds, - bytes calldata data - ) external returns (bytes4); - - /// @notice Handles unbinding of an IERC1155Bindable-compliant token type. - /// @dev An IERC1155Bindable-compliant contract MUST call this function at - /// the end of an `unbind` after revoking delegated asset ownership. The - /// function MUST revert if `from` is not the asset owner. The function - /// MUST revert if it rejects the unbind. If accepting the unbind, the - /// function MUST return `bytes4(keccak256("onERC1155Unbind(address,address,address,uint256,uint256,uint256,bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the unbinding token is `msg.sender`. - /// @param operator The address responsible for performing the unbind. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenId The token type being unbound. - /// @param amount The number of tokens of type `tokenId` being unbound. - /// @param bindId The identifier of the asset being unbound from. - /// @param data Additional data sent along with no specified format. - /// @return `bytes4(keccak256("onERC1155Unbind(address,address,address,uint256,uint256,uint256,bytes)"))` - function onERC1155Unbind( - address operator, - address from, - address to, - uint256 tokenId, - uint256 amount, - uint256 bindId, - bytes calldata data - ) external returns (bytes4); - - /// @notice Handles unbinding of multiple IERC1155Bindable-compliant token types. - /// @dev An IERC1155Bindable-compliant contract MUST call this function at - /// the end of a `batchUnbind` after revoking asset-delegated ownership. - /// The function MUST revert if `from` is not the asset owner. The function - /// MUST revert if it rejects the unbinds. If accepting the unbinds, the - /// function MUST return `bytes4(keccak256("onERC1155Unbind(address,address,address,uint256[],uint256[],uint256[],bytes)"))` - /// Caller MUST revert the transaction if the above value is not returned. - /// Note: The contract address of the unbinding token is `msg.sender`. - /// @param operator The address responsible for performing the unbinds. - /// @param from The owner address of the bound asset. - /// @param to The owner address of the unbound tokens. - /// @param tokenIds The list of token types being unbound. - /// @param amounts The number of tokens for each token type being unbound. - /// @param bindIds The identifiers of the assets being unbound from. - /// @param data Additional data sent along with no specified format. - /// @return `bytes4(keccak256("onERC1155Unbind(address,address,address,uint256[],uint256[],uint256[],bytes)"))` - function onERC1155BatchUnbind( - address operator, - address from, - address to, - uint256[] calldata tokenIds, - uint256[] calldata amounts, - uint256[] calldata bindIds, - bytes calldata data - ) external returns (bytes4); - - /// @notice Gets the owner address of the asset represented by id `bindId`. - /// @param bindId The identifier of the asset whose owner is being queried. - /// @return The address of the owner of the asset. - function ownerOf(uint256 bindId) external view returns (address); - - /// @notice Checks if an operator can act on behalf of an asset owner. - /// @param owner The owner address of an asset. - /// @param operator The address operating on behalf of the asset owner. - /// @return True if `operator` can act on behalf of `owner`, else False. - function isApprovedForAll(address owner, address operator) external view returns (bool); - -} -``` - -### Rules - -This standard supports two modes of binding, depending on whether ownership is delegated to the asset owner or binder address. - -- _Delegated (RECOMMENDED):_ - - Bindable ownership is delegated to the binder address (`to` is `bindAddress` in a bind). - - Bindable ownership queries return the binder address. - - Bindable transfers MUST always throw. -- _Legacy (NOT RECOMMENDED):_ - - Bindable ownership is delegated to the asset owner address (`to` is the asset owner address in a bind). - - Bindable ownership queries return the asset owner address. - - Bindable transfers MUST always throw, except when invoked as a result of bound assets being transferred. - - Transferrable bound assets MUST keep track of bound tokens following this binding mode. - - On transfer, bound assets MUST invoke ownership transfers for bound tokens following this binding mode. - -_Binders SHOULD choose to only support the "delegated" binding mode by throwing if `to` is not `bindAddress`, otherwise both modes MAY be supported._ - -**_`bind` rules:_** - -- When binding an EIP-721 bindable to an asset: - - MUST throw if caller is not the current NFT owner, the approved address for the NFT, or an approved operator for `from`. - - MUST throw if NFT `tokenId` is already bound. - - MUST throw if `from` is not the NFT owner. - - MUST throw if `to` is not `bindAddress` or the asset owner. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC721Bind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit the `Bind` event to reflect asset-bound ownership delegation. - - MUST emit the `Transfer` event if `from` is different than `to` to reflect delegated ownership change. -- When binding an EIP-1155 bindable to an asset: - - MUST throw if caller is not an approved operator for `from`. - - MUST throw if `from` owns fewer than `amount` unbound tokens of type `tokenId`. - - MUST throw if `to` is not `bindAddress` or the asset owner. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC1155Bind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit the `Bind` event to reflect asset-bound ownership delegation. - - MUST emit the `TransferSingle` event if `from` is different than `to` to reflect delegated ownership change. - -**_`unbind` rules:_** - -- When unbinding an EIP-721 bindable from an asset: - - MUST throw if caller is not the owner of the asset or an approved asset operator for `from`. - - MUST throw if NFT `tokenId` is not bound. - - MUST throw if `from` is not the asset owner. - - MUST throw if `to` is the zero address. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC721Unbind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - In addition, it MUST check if `to` is a smart contract (code size > 0), and call `onERC721Received` on `to` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit the `Unbind` event to reflect asset-bound ownership revocation. - - MUST emit the `Transfer` event if `from` is different than `to` to reflect delegated ownership change. -- When unbinding a an EIP-1155 bindable from an asset: - - MUST throw if caller is not the owner of the asset or an approved asset operator for `from`. - - MUST throw if `from` is not the asset owner. - - MUST throw if fewer than `amount` tokens of type `tokenId` are bound to `bindId`. - - MUST throw if `to` is the zero address. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC1155Unbind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - In addition, it MUST check if `to` is a smart contract (code size > 0), and call `onERC1155Received` on `to` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit the `Unbind` event to reflect asset-bound ownership revocation. - - MUST emit the `TransferSingle` event if `from` is different than `to` to reflect delegated ownership change. - -**_`batchBind` & `batchUnbind` rules:_** - -- When performing a `batchBind` on EIP-1155 bindables: - - MUST throw if caller is not an approved operator for `from`. - - MUST throw if length of `tokenIds` is not the same as that of `amounts` or `bindIds`. - - MUST throw if any unbound token balances of `tokenIds` for `from` are less than that of `amounts`. - - MUST throw if `to` is not `bindAddress` or the asset owner. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchBind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit either `Bind` or `BindBatch` events to properly reflect asset-delegated ownership attribution for all bound tokens. - - MUST emit either `TransferSingle` or `TransferBatch` events if `from` is different than `to` to reflect delegated ownership changes for all tokens. -- When performing a `batchUnbind` on EIP-1155 bindables: - - MUST throw if caller is not the owner of all assets or an approved asset operator for `from`. - - MUST throw if length of `tokenIds` is not the same as that of `amounts` or `bindIds`. - - MUST throw if `from` is not the owner of all assets. -- MUST throw if any count in `amounts` is fewer than the number of tokens bound for the corresponding token-asset pair given by `tokenIds` and `bindIds`. - - MUST throw if `to` is the zero address. - - After above conditions are met, MUST check if `bindAddress` is a smart contract (code size > 0). If so, it MUST call `onERC1155Unbind` on `bindAddress` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - In addition, it MUST check if `to` is a smart contract (code size > 0), and call `onERC1155Received` on `to` with `data` passed unaltered and act appropriately (see "Hook Rules"). - - MUST emit `Bind` event to reflect asset-bound ownership revocation. - - MUST emit the `TransferSingle` event if `from` is different than `to` to reflect delegated ownership change. - -**_`Bind` event rules:_** - -- When emitting an EIP-721 bindable `Bind` event: - - SHOULD be emitted to indicate a single bind has occurred between a `tokenId` and `bindId` pair. - - MAY be emitted multiple times to indicate multiple binds have occurred in a single transaction. - - The `operator` argument MUST be the owner of the NFT `tokenId`, the approved address for the NFT, or the authorized operator of `from`. - - The `from` argument MUST be the owner of the NFT `tokenId`. - - The `to` argument MUST be `binderAddress` (indicates "delegated" bind) or the owner of the bound asset (indicates "legacy" bind). - - The `tokenId` argument MUST be the NFT being bound. - - The `bindId` argument MUST be the identifier of the asset being bound to. - - The `bindAddress` argument MUST be the contract address of the asset being bound to. - - When minting NFTs bound to an asset, the `Bind` event must be emitted with the `from` argument set to `0x0`. - - `Bind` events MUST be emitted to reflect asset-bound ownership delegation before calls to `onERC721Bind`. -- When emitting an EIP-1155 bindable `Bind` event: - - SHOULD be emitted to indicate a bind has occurred between a single `tokenId` type and `binderId` pair. - - MAY be emitted multiple times to indicate multiple binds have occurred in a single transaction, but `BindBatch` should be preferred in this case to reduce gas consumption. - - The `operator` argument MUST be an authorized operator for `from`. - - The `from` argument MUST be the owner of the unbound tokens. - - The `to` argument MUST be `binderAddress` (indicates "delegated" bind) or the owner of the bound asset `bindId` (indicates "legacy" bind). - - The `tokenId` argument MUST be the token type being bound. - - The `amount` argument MUST be the number of tokens of type `tokenId` being bound. - - The `bindId` argument MUST be the identifier of the asset being bound to. - - The `bindAddress` argument MUST be the contract address of the asset being bound to. - - When minting NFTs bound to an asset, the `Bind` event must be emitted with the `from` argument set to `0x0`. - - `Bind` events MUST be emitted to reflect asset-bound ownership delegation before calls to `onERC1155Bind` or `onERC1155BindBatch`. - -**_`Unbind` event rules:_** - -- When emitting an EIP-721 bindable `Unbind` event: - - SHOULD be emitted to indicate a single unbind has occurred between a `tokenId` and `bindId` pair. - - MAY be emitted multiple times to indicate multiple unbinds have occurred in a single transaction. - - The `operator` argument MUST be the owner of the asset or an approved asset operator for `from`. - - The `from` argument MUST be the owner of the asset. - - The `to` argument MUST be the recipient address of the unbound NFT. - - The `tokenId` argument MUST be the NFT being unbound. - - The `bindId` argument MUST be the identifier of the asset being unbound from. - - The `bindAddress` argument MUST be the contract address of the asset being unbound from. - - When burning NFTs bound to an asset, the `Bind` event must be emitted with the `to` argument set to `0x0`. - - `Bind` events MUST be emitted to reflect delegated ownership revocation changes before calls to `onERC721Unbind`. -- When emitting an EIP-1155 bindable `Unbind` event: - - SHOULD be emitted to indicate an unbind has occurred between a single `tokenId` type and `binderId` pair. - - MAY be emitted multiple times to indicate multiple unbinds have occurred in a single transaction, but `UnbindBatch` should be preferred in this case to reduce gas consumption. - - The `operator` argument MUST be the owner of the asset or an approved asset operator for `from`. - - The `from` argument MUST be the asset owner. - - The `to` argument MUST be the recipient address of the unbound tokens. - - The `tokenId` argument MUST be the token type being unbound. - - The `amount` argument MUST be the number of tokens of type `tokenId` being unbound. - - The `bindId` argument MUST be the identifier of the asset being unbound from. - - The `bindAddress` argument MUST be the contract address of the asset being unbound from. - - When burning NFTs bound to an asset, the `Bind` event must be emitted with the `to` argument set to `0x0`. - - `Bind` events MUST be emitted to reflect delegated ownership revocation changes before calls to `onERC1155Unbind` or `onERC1155UnbindBatch` - -**_`BindBatch` & `UnbindBatch` event rules:_** - -- When emitting a `BindBatch` event: - - SHOULD be emitted to indicate a bind has occurred between multiple `tokenId` and `binderId` pairs. - - The `operator` argument MUST be an authorized operator for `from`. - - The `from` argument MUST be the owner of the unbound tokens. - - The `to` argument MUST be `binderAddress` (indicates "delegated" bind) or the owner of the bound asset (indicates "legacy" bind). - - The `tokenIds` argument MUST be the identifiers of the token types being bound. - - The `amounts` argument MUST be the number of tokens for each type in `tokenIds` being bound. - - The `bindIds` argument MUST be the identifiers for all assets being bound to. - - The `bindAddress` argument MUST be the contract address of the assets being bound to. - - When batch minting NFTs bound to an asset, the `BindBatch` event must be emitted with the `from` argument set to `0x0`. - - `BindBatch` events MUST be emitted to reflect asset-bound ownership delegation before calls to `onERC1155BindBatch` -- When emitting a `batchUnbind` event: - - SHOULD be emitted to indicate an unbind has occurred between multiple `tokenId` and `binderId` pairs. - - The `operator` argument MUST be an authorized operator or owner of the asset. - - The `from` argument MUST be the owner of all assets. - - The `to` argument MUST be the recipient address of the unbound tokens. - - The `tokenIds` argument MUST be the identifiers of the token types being unbound. - - The `amounts` argument MUST be the number of tokens for each type `tokenId` being unbound. - - The `bindIds` argument MUST be the identifiers for the assets being unbound from. - - The `bindAddress` argument MUST be the contract address of the assets being unbound from. - - When burning tokens bound to an asset, the `UnbindBatch` event must be emitted with the `to` argument set to `0x0`. - - `UnbindBatch` events MUST be emitted to reflect asset-delegated ownership changes before calls to `onERC1155UnbindBatch` - -**_`bind` hook rules:_** - -- The `operator` argument MUST be the address calling the bind hook. -- The `from` argument MUST be the owner of the NFT or token type being bound. - - FROM must be `0x0` for a mint. -- The `to` argument MUST be `binderAddress` (indicates "delegated" bind) or the owner of the bound asset (indicates "legacy" bind). - - The binder contract MAY choose to reject legacy binds. -- For `onERC721Bind` / `onERC1155Bind`, the `tokenId` argument MUST be the NFT / token type being bound. -- For `onERC1155BatchBind`, `tokenIds` MUST be the list of token types being bound. -- For `onERC1155Bind`, the `amount` argument MUST be the number of tokens of type `tokenId` being bound. -- For `onERC1155BatchBind`, the `amounts` argument MUST be a list of the number of tokens of each token type being bound. -- For `onERC721Bind` / `onERC1155Bind`, the `bindId` argument MUST be the identifier for the asset being bound to. -- For `onERC1155BatchBind`, `bindIds` MUST be the list of assets being bound to. -- The `data` argument MUST contain data provided by the caller for the bind with contents unaltered. -- The binder contract MAY accept the bind by returning the binder call's designated magic value, in which case the bind MUST complete or revert if any other conditions for success are not met: - - `onERC721Bind`: `bytes4(keccak256("onERC721Bind(address,address,address,uint256,uint256,bytes)"))` - - `onERC1155Bind`: `bytes4(keccak256("onERC1155Bind(address,address,address,uint256,uint256,uint256,bytes)"))` - - `onERC1155BindBatch`: `bytes4(keccak256("onERC1155BindBatch(address,address,address,uint256[],uint256[],uint256[],bytes)"))` -- The binder contract MAY reject the bind by calling revert. -- A return of any other value than the designated magic value MUST result in the transaction being reverted by the caller. - -**_`unbind` hook rules:_** - -- The `operator` argument MUST be the address calling the unbind hook. -- The `from` argument MUST be the asset owner. -- The `to` argument MUST the the recipient address of the unbound NFT or token type. - - TO must be `0x0` for a burn. -- For `onERC721Unbind` / `onERC1155Unbind`, the `tokenId` argument MUST be the NFT / token type being unbound. -- For `onERC1155BatchUnbind`, `tokenIds` MUST be the list of token types being unbound. -- For `onERC1155Unbind`, the `amount` argument MUST be the number of tokens of type `tokenId` being unbound. -- For `onERC1155BatchUnbind`, the `amounts` argument MUST be a list of the number of tokens of each token type being unbound. -- For `onERC721Bind` / `onERC1155Bind`, the `bindId` argument MUST be the identifier for the asset being unbound from. -- For `onERC1155BatchBind`, `bindIds` MUST be the list of assets being unbound from. -- The `data` argument MUST contain data provided by the caller for the bind with contents unaltered. -- The binder contract MAY accept the unbind by returning the binder call's designated magic value, in which case the unbind MUST complete or MUST revert if any other conditions for success are not met: - - `onERC721Unbind`: `bytes4(keccak256("onERC721Unbind(address,address,address,uint256,uint256,bytes)"))` - - `onERC1155Unbind`: `bytes4(keccak256("onERC1155Unbind(address,address,address,uint256,uint256,uint256,bytes)"))` - - `onERC1155UnbindBatch`: `bytes4(keccak256("onERC1155UnbindBatch(address,address,address,uint256[],uint256[],uint256[],bytes)"))` -- The binder contract MAY reject the bind by calling revert. -- A return of any other value than the designated magic value MUST result in the transaction being reverted by the caller. - -## Rationale - -A backwards-compatible standard for token binding unlocks a new layer of composability for allowing wallets, applications, and protocols to interact with, trade and display bundled assets. One example use-case of this is at Dopamine, where microchipped streetwear garments may be bundled with NFTs such as music, avatars, or digital-twins of the garments themselves, by linking chips to binder smart contracts capable of accepting token binds. - -### Binding Mechanism - -In the “delegated” mode, because token ownership is attributed to the contract address of the asset it is bound to, asset ownership modifications are completely decoupled from bound tokens, making bundled transfers efficient as no state management overhead is imposed. This is the recommended binding mode. - -The “legacy” binding mode was included purely for backwards-compatibility purposes, so that existing applications that have yet to integrate the standard can still display bundled tokens out-of-the-box. Here, since token ownership is attributed to the owner of the bound asset, asset ownership modifications are coupled to that of its bound tokens, making bundled transfers inefficient as binder contracts are required to track all bound tokens. - -Binder and bindable implementations MAY choose to support both modes of binding. - -### Transfer Mechanism - -One important consideration was whether binds should support transfers or not. Indeed, it would be much simpler for binds and unbinds to be processed only by addresses who owns both the bindable tokens and assets being bound to. Going this route, binds would not require any dependence on transfers, as asset-delegated ownership would not change, and applications could simply transfer the assets themselves following prescribed asset transfer rules. However, this was ruled out due to the lack of flexibility offered, especially around friction added for consumers wishing to bind their tokens to unowned assets. - -## Backwards Compatibility - -The bindable interface is designed to be compatible with existing EIP-721 and EIP-1155 standards. - -## Reference Implementation - -For reference EIP-721 implementations supporting "delegated" and "legacy" binding modes: - -- [EIP-721 Bindable](../assets/eip-5700/erc721/ERC721Bindable.sol). -- [EIP-721 Binder](../assets/eip-5700/erc721/ERC721Binder.sol). - -For reference EIP-1155 implementations supporting only the "delegated" binding mode: - -- [EIP-1155 Bindable](../assets/eip-5700/erc1155/ERC1155Bindable.sol). -- [EIP-1155 Binder](../assets/eip-5700/erc1155/ERC1155Binder.sol). - -## Security Considerations - -Bindable contracts supporting the "legacy" binding mode should be cautious with authorizing transfers once their tokens are bound. These should only be authorized as a result of their bound assets being transferred, and careful consideration must be taken when ensuring account balances are properly processed. - -Binder contracts supporting the "legacy" binding mode must ensure that any accepted binds are tracked, and that asset transfers result in proper changing of bound token ownership. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5700.md diff --git a/EIPS/eip-5719.md b/EIPS/eip-5719.md index 5304c05386ddec..3e470f1cba6948 100644 --- a/EIPS/eip-5719.md +++ b/EIPS/eip-5719.md @@ -1,94 +1,7 @@ --- eip: 5719 -title: Signature replacement interface -description: Non-interactive replacing of smart contract wallet signatures that became stale due to configuration changes. -author: Agustin Aguilar (@Agusx1211) -discussions-to: https://ethereum-magicians.org/t/erc-signature-replacing-for-smart-contract-wallets/11059 -status: Draft -type: Standards Track category: ERC -created: 2022-09-26 -requires: 1271 +status: Moved --- -## Abstract - -Smart contract wallet signed messages can become stale, meaning a signature that once was valid could become invalid at any point. - -Signatures MAY become stale for reasons like: - -* The internal set of signers changed -* The wallet makes signatures expirable -* The contract was updated to a new implementation - -The following standard allows smart contract wallets to expose a URI that clients can use to replace a stale signature with a valid one. - -## Motivation - -In contrast to EOA signatures, [EIP-1271](./eip-1271.md) signatures are not necessarily idempotent; they can become invalid at any point in time. This poses a challenge to protocols that rely on signatures remaining valid for extended periods of time. - -A signature MAY need to be mutated due to one of the following scenarios: - -1. The wallet removes a signer that contributed to signing the initial message. -2. The wallet uses a Merkle tree to store signers, adding a new signer. -3. The wallet uses a Merkle tree to store signatures, adding new signatures. -4. The wallet is updated to a new implementation, and the signature schema changes. - -Non-interactive signature replacement SHOULD be possible, since the wallet that originally signed the message MAY NOT be available when the signature needs to be validated. An example use-case is the settlement of a trade in an exchange that uses an off-chain order book. - -## Specification - -The wallet contract MUST implement the following function: - -```solidity -function getAlternativeSignature(bytes32 _digest) external view returns (string); -``` - -The returned string MUST be a URI pointing to a JSON object with the following schema: - -```json -{ - "title": "Signature alternative", - "type": "object", - "properties": { - "blockHash": { - "type": "string", - "description": "A block.hash on which the signature should be valid." - }, - "signature": { - "type": "string", - "description": "The alternative signature for the given digest." - } - } -} -``` - -### Client process for replacing a signature - -A client is an entity that holds a signature and intends to validate it, either for off-chain or on-chain use. To use the smart contract wallet signature, the client MUST perform the following actions: - -1) Try validating the signature using [EIP-1271](./eip-1271.md); if the signature is valid, then the signature can be used as-is. -2) If the signature is not valid, call `getAlternativeSignature(_digest)`, passing the `digest` corresponding to the old signature. -3) If the call fails, no URI is returned, or the content of the URI is not valid, then the signature MUST be considered invalid. -4) Try validating the new signature using [EIP-1271](./eip-1271.md); if the signature is valid, it can be used as a drop-in replacement of the original signature. -5) If the validation fails, repeat the process from step (2) (notice: if the URI returns the same signature, the signature MUST be considered invalid). - -Clients MUST implement a retry limit when fetching alternative signatures. This limit is up to the client to define. - -## Rationale - -A URI is chosen because it can accommodate centralized and decentralized solutions. For example, a server can implement live re-encoding for Merkle proofs, or an IPFS link could point to a directory with all the pre-computed signature mutations. - -The `getAlternativeSignature` method points to an off-chain source because it's expected that the smart contract wallet doesn't contain on-chain records for all signed digests, if that were the case then such contract wouldn't need to use this EIP since it could directly validate the `digest` on`isValidSignature` ignoring the stale signature. - -## Backwards Compatibility - -Existing wallets that do not implement the `getAlternativeSignature` method can still sign messages without any changes; if any signatures become invalidated, clients will drop them on step (3). - -## Security Considerations - -Some applications use signatures as secrets; these applications would risk leaking such secrets if the EIP exposes the signatures. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5719.md diff --git a/EIPS/eip-5725.md b/EIPS/eip-5725.md index 8c2aa2108f8348..70859e00221b7f 100644 --- a/EIPS/eip-5725.md +++ b/EIPS/eip-5725.md @@ -1,216 +1,7 @@ --- eip: 5725 -title: Transferable Vesting NFT -description: An interface for transferable vesting NFTs which release underlying tokens over time. -author: Apeguru (@Apegurus), Marco De Vries , Mario , DeFiFoFum (@DeFiFoFum) -discussions-to: https://ethereum-magicians.org/t/eip-5725-transferable-vesting-nft/11099 -status: Draft -type: Standards Track category: ERC -created: 2022-09-08 -requires: 721 +status: Moved --- -## Abstract - -A **Non-Fungible Token** (NFT) standard used to vest tokens ([EIP-20](./eip-20.md) or otherwise) over a vesting release curve. - -The following standard allows for the implementation of a standard API for NFT based contracts that hold and represent the vested and locked properties of any underlying token ([EIP-20](./eip-20.md) or otherwise) that is emitted to the NFT holder. This standard is an extension of the [EIP-721](./eip-721.md) token that provides basic functionality for creating vesting NFTs, claiming the tokens and reading vesting curve properties. - -## Motivation - -Vesting contracts, including timelock contracts, lack a standard and unified interface, which results in diverse implementations of such contracts. Standardizing such contracts into a single interface would allow for the creation of an ecosystem of on- and off-chain tooling around these contracts. In addition, liquid vesting in the form of non-fungible assets can prove to be a huge improvement over traditional **Simple Agreement for Future Tokens** (SAFTs) or **Externally Owned Account** (EOA)-based vesting as it enables transferability and the ability to attach metadata similar to the existing functionality offered by with traditional NFTs. - -Such a standard will not only provide a much-needed [EIP-20](./eip-20.md) token lock standard, but will also enable the creation of secondary marketplaces tailored for semi-liquid SAFTs. - -This standard also allows for a variety of different vesting curves to be implement easily. - -These curves could represent: - -- linear vesting -- cliff vesting -- exponential vesting -- custom deterministic vesting - -### Use Cases - -1. A framework to release tokens over a set period of time that can be used to build many kinds of NFT financial products such as bonds, treasury bills, and many others. -2. Replicating SAFT contracts in a standardized form of semi-liquid vesting NFT assets. - - SAFTs are generally off-chain, while today's on-chain versions are mainly address-based, which makes distributing vesting shares to many representatives difficult. Standardization simplifies this convoluted process. -3. Providing a path for the standardization of vesting and token timelock contracts. - - There are many such contracts in the wild and most of them differ in both interface and implementation. -4. NFT marketplaces dedicated to vesting NFTs. - - Whole new sets of interfaces and analytics could be created from a common standard for token vesting NFTs. -5. Integrating vesting NFTs into services like Gnosis Safe. - - A standard would mean services like Gnosis Safe could more easily and uniformly support interactions with these types of contracts inside of a multisig contract. -6. Enable standardized fundraising implementations and general fundraising that sell vesting tokens (eg. SAFTs) in a more transparent manner. -7. Allows tools, front-end apps, aggregators, etc. to show a more holistic view of the vesting tokens and the properties available to users. - - Currently, every project needs to write their own visualization of the vesting schedule of their vesting assets. If this is standardized, third-party tools could be developed aggregate all vesting NFTs from all projects for the user, display their schedules and allow the user to take aggregated vesting actions. - - Such tooling can easily discover compliance through the [EIP-165](./eip-165.md) `supportsInterface(InterfaceID)` check. -8. Makes it easier for a single wrapping implementation to be used across all vesting standards that defines multiple recipients, periodic renting of vesting tokens etc. - - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; -import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; - -/** - * @title Non-Fungible Vesting Token Standard - * @notice A non-fungible token standard used to vest tokens (EIP-20 or otherwise) over a vesting release curve - * scheduled using timestamps. - * @dev Because this standard relies on timestamps for the vesting schedule, it's important to keep track of the - * tokens claimed per Vesting NFT so that a user cannot withdraw more tokens than alloted for a specific Vesting NFT. - */ -interface IERC5725 is IERC721 { - /** - * This event is emitted when the payout is claimed through the claim function - * @param tokenId the NFT tokenId of the assets being claimed. - * @param recipient The address which is receiving the payout. - * @param _claimAmount The amount of tokens being claimed. - */ - event PayoutClaimed(uint256 indexed tokenId, address indexed recipient, uint256 _claimAmount); - - /** - * @notice Claim the pending payout for the NFT - * @dev MUST grant the claimablePayout value at the time of claim being called - * MUST revert if not called by the token owner or approved users - * SHOULD revert if there is nothing to claim - * @param tokenId The NFT token id - */ - function claim(uint256 tokenId) external; - - /** - * @notice Total amount of tokens which have been vested at the current timestamp. - * This number also includes vested tokens which have been claimed. - * @dev It is RECOMMENDED that this function calls `vestedPayoutAtTime` with - * `block.timestamp` as the `timestamp` parameter. - * @param tokenId The NFT token id - * @return payout Total amount of tokens which have been vested at the current timestamp. - */ - function vestedPayout(uint256 tokenId) external view returns (uint256 payout); - - /** - * @notice Total amount of vested tokens at the provided timestamp. - * This number also includes vested tokens which have been claimed. - * @dev `timestamp` MAY be both in the future and in the past. - * Zero MUST be returned if the timestamp is before the token was minted. - * @param tokenId The NFT token id - * @param timestamp The timestamp to check on, can be both in the past and the future - * @return payout Total amount of tokens which have been vested at the provided timestamp - */ - function vestedPayoutAtTime(uint256 tokenId, uint256 timestamp) external view returns (uint256 payout); - - /** - * @notice Number of tokens for an NFT which are currently vesting (locked). - * @dev The sum of vestedPayout and vestingPayout SHOULD always be the total payout. - * @param tokenId The NFT token id - * @return payout The number of tokens for the NFT which have not been claimed yet, - * regardless of whether they are ready to claim - */ - function vestingPayout(uint256 tokenId) external view returns (uint256 payout); - - /** - * @notice Number of tokens for the NFT which can be claimed at the current timestamp - * @dev It is RECOMMENDED that this is calculated as the `vestedPayout()` value with the total - * amount of tokens claimed subtracted. - * @param tokenId The NFT token id - * @return payout The number of vested tokens for the NFT which have not been claimed yet - */ - function claimablePayout(uint256 tokenId) external view returns (uint256 payout); - - /** - * @notice The start and end timestamps for the vesting of the provided NFT - * MUST return the timestamp where no further increase in vestedPayout occurs for `vestingEnd`. - * @param tokenId The NFT token id - * @return vestingStart The beginning of the vesting as a unix timestamp - * @return vestingEnd The ending of the vesting as a unix timestamp - */ - function vestingPeriod(uint256 tokenId) external view returns (uint256 vestingStart, uint256 vestingEnd); - - /** - * @notice Token which is used to pay out the vesting claims - * @param tokenId The NFT token id - * @return token The token which is used to pay out the vesting claims - */ - function payoutToken(uint256 tokenId) external view returns (address token); -} -``` - - -## Rationale - -### Terms - -These are base terms used around the specification which function names and definitions are based on. - -- _vesting_: Tokens which are locked until a future date. -- _vested_: Tokens which have reached their unlock date. (The usage in this specification relates to the **total** vested tokens for a given Vesting NFT.) -- _claimable_: Amount of tokens which can be claimed at the current `timestamp`. -- _timestamp_: The unix `timestamp` (seconds) representation of dates used for vesting. - -### Vesting Functions - -**`vestingPayout` + `vestedPayout`** - -`vestingPayout(uint256 tokenId)` and `vestedPayout(uint256 tokenId)` add up to the total number of tokens which can be claimed by the end of of the vesting schedule. This is also equal to `vestedPayoutAtTime(uint256 tokenId, uint256 timestamp)` with `type(uint256).max` as the `timestamp`. - -The rationale for this is to guarantee that the tokens `vested` and tokens `vesting` are always in sync. The intent is that the vesting curves created are deterministic across the `vestingPeriod`. - - -**`vestedPayout` vs `claimablePayout`** - -- `vestedPayout(uint256 tokenId)` will provide the total amount of tokens which are eligible for release **including claimed tokens**. -- `claimablePayout(uint256 tokenId)` provides the amount of tokens which can be claimed at the current `timestamp`. - -The rationale for providing two functions is so that the return of `vestedPayout(uint256 tokenId)` will always match the return of `vestedPayoutAtTime(uint256 tokenId, uint256 timestamp)` with `block.timestamp` as the `timestamp`, and a separate function can be called to read how many tokens are available to claim. - -`vestedPayoutAtTime(uint256 tokenId, uint256 timestamp)` provides functionality to iterate through the `vestingPeriod(uint256 tokenId)` and provide a visual of the release curve. The intent is that release curves are created which makes `vestedPayoutAtTime(uint256 tokenId, uint256 timestamp)` deterministic. - -### Timestamps - -Generally in Solidity development it is advised against using `block.timestamp` as a state dependant variable as the timestamp of a block can be manipulated by a miner. The choice to use a `timestamp` over a `block` is to allow the interface to work across multiple **Ethereum Virtual Machine** (EVM) compatible networks which generally have different block times. Block proposal with a significantly fabricated timestamp will generally be dropped by all node implementations which makes the window for abuse negligible. - -The `timestamp` makes cross chain integration easy, but internally, the reference implementation keeps track of the token payout per Vesting NFT to ensure that excess tokens alloted by the vesting terms cannot be claimed. - -### Limitation of Scope - -The standard does not implement the following features: - -- Vesting Curves -- Rental -- Beneficiary - -This is done intentionally to keep the base standard simple. These features can and likely will be added through extensions of this standard. - -## Backwards Compatibility - -- The Vesting NFT standard is meant to be fully backwards compatible with any current [EIP-721](./eip-721.md) integrations and marketplaces. -- The Vesting NFT standard also supports [EIP-165](./eip-165.md) interface detection for detecting `EIP-721` compatibility, as well as Vesting NFT compatibility. - -## Test Cases - -The reference vesting NFT repository includes tests written in Hardhat. - -## Reference Implementation - -A reference implementation of this EIP can be found in [eip-5725 assets](../assets/eip-5725/README.md/). - -## Security Considerations - -**timestamps** - -- Vesting schedules are based on timestamps. As such, it's important to keep track of the number of tokens which have been claimed and to not give out more tokens than alloted for a specific Vesting NFT. - - `vestedPayoutAtTime(tokenId, type(uint256).max)`, for example, must return the total payout for a given `tokenId` - -**approvals** - -- When an approval is made on a Vesting NFT, the operator would have the rights to transfer the Vesting NFT to themselves and then claim the vested tokens. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5725.md diff --git a/EIPS/eip-5727.md b/EIPS/eip-5727.md index 5784ebabfe8d1e..c041e425898da5 100644 --- a/EIPS/eip-5727.md +++ b/EIPS/eip-5727.md @@ -1,703 +1,7 @@ --- eip: 5727 -title: Semi-Fungible Soulbound Token -description: An interface for soulbound tokens, also known as badges or account-bound tokens, that can be both fungible and non-fungible. -author: Austin Zhu (@AustinZhu), Terry Chen -discussions-to: https://ethereum-magicians.org/t/eip-5727-semi-fungible-soulbound-token/11086 -status: Draft -type: Standards Track category: ERC -created: 2022-09-28 -requires: 165 +status: Moved --- -## Abstract - -An interface for soulbound tokens (SBT), which are non-transferable tokens representing a person's identity, credentials, affiliations, and reputation. - -Our interface can handle a combination of fungible and non-fungible tokens in an organized way. It provides a set of core methods that can be used to manage the lifecycle of soulbound tokens, as well as a rich set of extensions that enables DAO governance, privacy protection, token expiration, and account recovery. - -This interface aims to provide a flexible and extensible framework for the development of soulbound token systems. - -## Motivation - -The Web3 ecosystem nowadays is largely dominated by highly-financialized tokens, which are designed to be freely transferable and interchangeable. However, there are many use cases in our society that require non-transferablity. For example, a membership card guarantees one's proprietary rights in a community, and such rights should not be transferable to others. - -We have already seen many attempts to create such non-transferable tokens in the Ethereum community. However, most of them rely heavily on NFT standards like [EIP-721](./eip-721.md), which are not designed for non-transferability. Others lack the flexibility to support both fungible and non-fungible tokens and do not provide extensible features for critical use cases. - -Our interface can be used to represent non-transferable ownerships, and provides features for common use cases including but not limited to: - -- granular lifecycle management of SBTs (e.g. minting, revocation, expiration) -- management of SBTs via community voting and delegation (e.g. DAO governance, operators) -- recovery of SBTs (e.g. switching to a new wallet) -- token visibility control (e.g. private SBTs, hiding negative tokens) -- fungible and non-fungible SBTs (e.g. membership card and loyalty points) -- the grouping of SBTs using slots (e.g. complex reward schemes with a combination of vouchers, points, and badges) - -A common interface for soulbound tokens will not only help enrich the Web3 ecosystem but also facilitates the growth of a decentralized society. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -A token is identified by its `tokenId`, which is a 256-bit unsigned integer. A token can also have a value denoting its denomination. - -A slot is identified by its `slotId`, which is a 256-bit unsigned integer. Slots are used to group fungible and non-fungible tokens together, thus make tokens semi-fungible. A token can only belong to one slot at a time. - -### Core - -The core methods are used to manage the lifecycle of SBTs. They MUST be supported by all semi-fungible SBT implementations. - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; - -/** - * @title ERC5727 Soulbound Token Interface - * @dev The core interface. It allows basic query of information about tokens and slots. - * @dev interfaceId = 0x35f61d8a - */ -interface IERC5727 is IERC165 { - /** - * @dev MUST emit when a token is minted. - * @param owner The address that the token is minted to - * @param tokenId The token minted - * @param value The value of the token minted - */ - event Minted(address indexed owner, uint256 indexed tokenId, uint256 value); - - /** - * @dev MUST emit when a token is revoked. - * @param owner The owner of the revoked token - * @param tokenId The revoked token - */ - event Revoked(address indexed owner, uint256 indexed tokenId); - - /** - * @dev MUST emit when a token is charged. - * @param tokenId The token to charge - * @param value The value to charge - */ - event Charged(uint256 indexed tokenId, uint256 value); - - /** - * @dev MUST emit when a token is consumed. - * @param tokenId The token to consume - * @param value The value to consume - */ - event Consumed(uint256 indexed tokenId, uint256 value); - - /** - * @dev MUST emit when a token is destroyed. - * @param owner The owner of the destroyed token - * @param tokenId The token to destroy. - */ - event Destroyed(address indexed owner, uint256 indexed tokenId); - - /** - * @dev MUST emit when the slot of a token is set or changed. - * @dev In case a new slot is set, the `oldSlot` MUST be 0. - * @param tokenId The token of which slot is set or changed - * @param oldSlot The previous slot of the token - * @param newSlot The updated slot of the token - */ - event SlotChanged( - uint256 indexed tokenId, - uint256 indexed oldSlot, - uint256 indexed newSlot - ); - - /** - * @notice Get the value of a token. - * @dev MUST revert if the `tokenId` does not exist - * @param tokenId the token for which to query the balance - * @return The value of `tokenId` - */ - function valueOf(uint256 tokenId) external view returns (uint256); - - /** - * @notice Get the slot of a token. - * @dev MUST revert if the `tokenId` does not exist - * @param tokenId the token for which to query the slot - * @return The slot of `tokenId` - */ - function slotOf(uint256 tokenId) external view returns (uint256); - - /** - * @notice Get the owner of a token. - * @dev MUST revert if the `tokenId` does not exist - * @param tokenId the token for which to query the owner - * @return The address of the owner of `tokenId` - */ - function ownerOf(uint256 tokenId) external view returns (address); - - /** - * @notice Get the validity of a token. - * @dev MUST revert if the `tokenId` does not exist - * @dev A token is valid if it is not revoked. - * @param tokenId the token for which to query the validity - * @return If the token is valid - */ - function isValid(uint256 tokenId) external view returns (bool); - - /** - * @notice Get the issuer of a token. - * @dev MUST revert if the `tokenId` does not exist - * @param tokenId the token for which to query the issuer - * @return The address of the issuer of `tokenId` - */ - function issuerOf(uint256 tokenId) external view returns (address); -} -``` - -### Extensions - -All extensions below are OPTIONAL for [EIP-5727](./eip-5727.md) implementations. An implementation MAY choose to implement some, none, or all of them. - -#### Enumerable - -This extension provides methods to enumerate the tokens of a owner. It is recommended to be implemented together with the core interface. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Enumerable Interface - * @dev This extension allows querying the tokens of a owner. - * @dev interfaceId = 0x211ec300 - */ -interface IERC5727Enumerable is IERC5727 { - /** - * @notice Get the total number of tokens emitted. - * @return The total number of tokens emitted - */ - function emittedCount() external view returns (uint256); - - /** - * @notice Get the total number of owners. - * @return The total number of owners - */ - function ownersCount() external view returns (uint256); - - /** - * @notice Get the tokenId with `index` of the `owner`. - * @dev MUST revert if the `index` exceed the number of tokens owned by the `owner`. - * @param owner The owner whose token is queried for. - * @param index The index of the token queried for - * @return The token is queried for - */ - function tokenOfSoulByIndex(address owner, uint256 index) - external - view - returns (uint256); - - /** - * @notice Get the tokenId with `index` of all the tokens. - * @dev MUST revert if the `index` exceed the total number of tokens. - * @param index The index of the token queried for - * @return The token is queried for - */ - function tokenByIndex(uint256 index) external view returns (uint256); - - /** - * @notice Get the number of tokens owned by the `owner`. - * @dev MUST revert if the `owner` does not have any token. - * @param owner The owner whose balance is queried for - * @return The number of tokens of the `owner` - */ - function balanceOf(address owner) external view returns (uint256); - - /** - * @notice Get if the `owner` owns any valid tokens. - * @param owner The owner whose valid token information is queried for - * @return if the `owner` owns any valid tokens - */ - function hasValid(address owner) external view returns (bool); -} -``` - -#### Metadata - -This extension provides methods to fetch the metadata of a token, a slot and the contract itself. It is recommended to be implemented if you need to specify the appearance and properties of tokens, slots and the contract (i.e. the SBT collection). - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Metadata Interface - * @dev This extension allows querying the metadata of soulbound tokens. - * @dev interfaceId = 0xba3e1a9d - */ -interface IERC5727Metadata is IERC5727 { - /** - * @notice Get the name of the contract. - * @return The name of the contract - */ - function name() external view returns (string memory); - - /** - * @notice Get the symbol of the contract. - * @return The symbol of the contract - */ - function symbol() external view returns (string memory); - - /** - * @notice Get the URI of a token. - * @dev MUST revert if the `tokenId` token does not exist. - * @param tokenId The token whose URI is queried for - * @return The URI of the `tokenId` token - */ - function tokenURI(uint256 tokenId) external view returns (string memory); - - /** - * @notice Get the URI of the contract. - * @return The URI of the contract - */ - function contractURI() external view returns (string memory); - - /** - * @notice Get the URI of a slot. - * @dev MUST revert if the `slot` does not exist. - * @param slot The slot whose URI is queried for - * @return The URI of the `slot` - */ - function slotURI(uint256 slot) external view returns (string memory); -} -``` - -#### Governance - -This extension provides methods to manage the mint and revocation permissions through voting. It is useful if you want to rely on a group of voters to decide the issuance a particular SBT. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Governance Interface - * @dev This extension allows minting and revocation of tokens by community voting. - * @dev interfaceId = 0x3ba738d1 - */ -interface IERC5727Governance is IERC5727 { - /** - * @notice Get the voters of the contract. - * @return The array of the voters - */ - function voters() external view returns (address[] memory); - - /** - * @notice Approve to mint the token described by the `approvalRequestId` to `owner`. - * @dev MUST revert if the caller is not a voter. - * @param owner The owner which the token to mint to - * @param approvalRequestId The approval request describing the value and slot of the token to mint - */ - function approveMint(address owner, uint256 approvalRequestId) external; - - /** - * @notice Approve to revoke the `tokenId`. - * @dev MUST revert if the `tokenId` does not exist. - * @param tokenId The token to revert - */ - function approveRevoke(uint256 tokenId) external; - - /** - * @notice Create an approval request describing the `value` and `slot` of a token. - * @dev MUST revert when `value` is zero. - * @param value The value of the approval request to create - */ - function createApprovalRequest(uint256 value, uint256 slot) external returns (uint256 approvalRequestId); - - /** - * @notice Remove `approvalRequestId` approval request. - * @dev MUST revert if the caller is not the creator of the approval request. - * @param approvalRequestId The approval request to remove - */ - function removeApprovalRequest(uint256 approvalRequestId) external; - - /** - * @notice Add a new voter `newVoter`. - * @dev MUST revert if the caller is not an administrator. - * MUST revert if `newVoter` is already a voter. - * @param newVoter the new voter to add - */ - function addVoter(address newVoter) external; - - /** - * @notice Remove the `voter` from the contract. - * @dev MUST revert if the caller is not an administrator. - * MUST revert if `voter` is not a voter. - * @param voter the voter to remove - */ - function removeVoter(address voter) external; -} -``` - -#### Delegate - -This extension provides methods to delegate a one-time mint and revocation right to an operator. It is useful if you want to temporarily allow an operator to mint and revoke tokens on your behalf. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Delegate Interface - * @dev This extension allows delegation of (batch) minting and revocation of tokens to operator(s). - * @dev interfaceId = 0x3da384b4 - */ -interface IERC5727Delegate is IERC5727 { - /** - * @notice Delegate a one-time minting right to `operator` for `delegateRequestId` delegate request. - * @dev MUST revert if the caller does not have the right to delegate. - * @param operator The owner to which the minting right is delegated - * @param delegateRequestId The delegate request describing the owner, value and slot of the token to mint - */ - function mintDelegate(address operator, uint256 delegateRequestId) external; - - /** - * @notice Delegate one-time minting rights to `operators` for corresponding delegate request in `delegateRequestIds`. - * @dev MUST revert if the caller does not have the right to delegate. - * MUST revert if the length of `operators` and `delegateRequestIds` do not match. - * @param operators The owners to which the minting right is delegated - * @param delegateRequestIds The delegate requests describing the owner, value and slot of the tokens to mint - */ - function mintDelegateBatch( - address[] memory operators, - uint256[] memory delegateRequestIds - ) external; - - /** - * @notice Delegate a one-time revoking right to `operator` for `tokenId` token. - * @dev MUST revert if the caller does not have the right to delegate. - * @param operator The owner to which the revoking right is delegated - * @param tokenId The token to revoke - */ - function revokeDelegate(address operator, uint256 tokenId) external; - - /** - * @notice Delegate one-time minting rights to `operators` for corresponding token in `tokenIds`. - * @dev MUST revert if the caller does not have the right to delegate. - * MUST revert if the length of `operators` and `tokenIds` do not match. - * @param operators The owners to which the revoking right is delegated - * @param tokenIds The tokens to revoke - */ - function revokeDelegateBatch( - address[] memory operators, - uint256[] memory tokenIds - ) external; - - /** - * @notice Mint a token described by `delegateRequestId` delegate request as a delegate. - * @dev MUST revert if the caller is not delegated. - * @param delegateRequestId The delegate requests describing the owner, value and slot of the token to mint. - */ - function delegateMint(uint256 delegateRequestId) external; - - /** - * @notice Mint tokens described by `delegateRequestIds` delegate request as a delegate. - * @dev MUST revert if the caller is not delegated. - * @param delegateRequestIds The delegate requests describing the owner, value and slot of the tokens to mint. - */ - function delegateMintBatch(uint256[] memory delegateRequestIds) external; - - /** - * @notice Revoke a token as a delegate. - * @dev MUST revert if the caller is not delegated. - * @param tokenId The token to revoke. - */ - function delegateRevoke(uint256 tokenId) external; - - /** - * @notice Revoke multiple tokens as a delegate. - * @dev MUST revert if the caller is not delegated. - * @param tokenIds The tokens to revoke. - */ - function delegateRevokeBatch(uint256[] memory tokenIds) external; - - /** - * @notice Create a delegate request describing the `owner`, `value` and `slot` of a token. - * @param owner The owner of the delegate request. - * @param value The value of the delegate request. - * @param slot The slot of the delegate request. - * @return delegateRequestId The id of the delegate request - */ - function createDelegateRequest( - address owner, - uint256 value, - uint256 slot - ) external returns (uint256 delegateRequestId); - - /** - * @notice Remove a delegate request. - * @dev MUST revert if the delegate request does not exists. - * MUST revert if the caller is not the creator of the delegate request. - * @param delegateRequestId The delegate request to remove. - */ - function removeDelegateRequest(uint256 delegateRequestId) external; -} -``` - -#### Recovery - -This extension provides methods to recover tokens from a stale owner. It is recommended to use this extension so that users are able to retrieve their tokens from a compromised or old wallet in certain situations. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Recovery Interface - * @dev This extension allows recovering soulbound tokens from an address provided its signature. - * @dev interfaceId = 0x379f4e66 - */ -interface IERC5727Recovery is IERC5727 { - /** - * @notice Recover the tokens of `owner` with `signature`. - * @dev MUST revert if the signature is invalid. - * @param owner The owner whose tokens are recovered - * @param signature The signature signed by the `owner` - */ - function recover(address owner, bytes memory signature) external; -} -``` - -#### Expirable - -This extension provides methods to manage the expiration of tokens. It is useful if you want to expire/invalidate tokens after a certain period of time. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Expirable Interface - * @dev This extension allows soulbound tokens to be expired. - * @dev interfaceId = 0x2a8cf5aa - */ -interface IERC5727Expirable is IERC5727 { - /** - * @notice Get the expire date of a token. - * @dev MUST revert if the `tokenId` token does not exist. - * @param tokenId The token for which the expiry date is queried - * @return The expiry date of the token - */ - function expiryDate(uint256 tokenId) external view returns (uint256); - - /** - * @notice Get if a token is expired. - * @dev MUST revert if the `tokenId` token does not exist. - * @param tokenId The token for which the expired status is queried - * @return If the token is expired - */ - function isExpired(uint256 tokenId) external view returns (bool); - - /** - * @notice Set the expiry date of a token. - * @dev MUST revert if the `tokenId` token does not exist. - * MUST revert if the `date` is in the past. - * @param tokenId The token whose expiry date is set - * @param date The expire date to set - */ - function setExpiryDate(uint256 tokenId, uint256 date) external; - - /** - * @notice Set the expiry date of multiple tokens. - * @dev MUST revert if the `tokenIds` tokens does not exist. - * MUST revert if the `dates` is in the past. - * MUST revert if the length of `tokenIds` and `dates` do not match. - * @param tokenIds The tokens whose expiry dates are set - * @param dates The expire dates to set - */ - function setBatchExpiryDates( - uint256[] memory tokenIds, - uint256[] memory dates - ) external; -} -``` - -#### Shadow - -This extension provides methods to manage the visibility of tokens. It is useful if you want to hide tokens that you don't want to show to the public. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; - -/** - * @title ERC5727 Soulbound Token Shadow Interface - * @dev This extension allows restricting the visibility of specific soulbound tokens. - * @dev interfaceId = 0x3475cd68 - */ -interface IERC5727Shadow is IERC5727 { - /** - * @notice Shadow a token. - * @dev MUST revert if the `tokenId` token does not exists. - * @param tokenId The token to shadow - */ - function shadow(uint256 tokenId) external; - - /** - * @notice Reveal a token. - * @dev MUST revert if the `tokenId` token does not exists. - * @param tokenId The token to reveal - */ - function reveal(uint256 tokenId) external; -} -``` - -#### SlotEnumerable - -This extension provides methods to enumerate slots. A slot is used to group tokens that share similar utility and properties. - -```solidity -pragma solidity ^0.8.0; - -import "./IERC5727.sol"; -import "./IERC5727Enumerable.sol"; - -/** - * @title ERC5727 Soulbound Token Slot Enumerable Interface - * @dev This extension allows querying information about slots. - * @dev interfaceId = 0x3b741b9e - */ -interface IERC5727SlotEnumerable is IERC5727, IERC5727Enumerable { - /** - * @notice Get the total number of slots. - * @return The total number of slots. - */ - function slotCount() external view returns (uint256); - - /** - * @notice Get the slot with `index` among all the slots. - * @dev MUST revert if the `index` exceed the total number of slots. - * @param index The index of the slot queried for - * @return The slot is queried for - */ - function slotByIndex(uint256 index) external view returns (uint256); - - /** - * @notice Get the number of tokens in a slot. - * @dev MUST revert if the slot does not exist. - * @param slot The slot whose number of tokens is queried for - * @return The number of tokens in the `slot` - */ - function tokenSupplyInSlot(uint256 slot) external view returns (uint256); - - /** - * @notice Get the tokenId with `index` of the `slot`. - * @dev MUST revert if the `index` exceed the number of tokens in the `slot`. - * @param slot The slot whose token is queried for. - * @param index The index of the token queried for - * @return The token is queried for - */ - function tokenInSlotByIndex(uint256 slot, uint256 index) - external - view - returns (uint256); - - /** - * @notice Get the number of owners in a slot. - * @dev MUST revert if the slot does not exist. - * @param slot The slot whose number of owners is queried for - * @return The number of owners in the `slot` - */ - function ownersInSlot(uint256 slot) external view returns (uint256); - - /** - * @notice Check if a owner is in a slot. - * @dev MUST revert if the slot does not exist. - * @param owner The owner whose existence in the slot is queried for - * @param slot The slot whose existence of the owner is queried for - * @return True if the `owner` is in the `slot`, false otherwise - */ - function isOwnerInSlot( - address owner, - uint256 slot - ) external view returns (bool); - - /** - * @notice Get the owner with `index` of the `slot`. - * @dev MUST revert if the `index` exceed the number of owners in the `slot`. - * @param slot The slot whose owner is queried for. - * @param index The index of the owner queried for - * @return The owner is queried for - */ - function ownerInSlotByIndex( - uint256 slot, - uint256 index - ) external view returns (address); - - /** - * @notice Get the number of slots of a owner. - * @param owner The owner whose number of slots is queried for - * @return The number of slots of the `owner` - */ - function slotCountOfOwner(address owner) external view returns (uint256); - - /** - * @notice Get the slot with `index` of the `owner`. - * @dev MUST revert if the `index` exceed the number of slots of the `owner`. - * @param owner The owner whose slot is queried for. - * @param index The index of the slot queried for - * @return The slot is queried for - */ - function slotOfOwnerByIndex( - address owner, - uint256 index - ) external view returns (uint256); -} -``` - -## Rationale - -### Token storage model - -We adopt semi-fungible token storage models designed to support both fungible and non-fungible tokens, inspired by the semi-fungible token standard. We found that such a model is better suited to the representation of SBT than the model used in [EIP-1155](./eip-1155.md). - -Firstly, each slot can be used to represent different categories of SBTs. For instance, a DAO can have membership SBTs, role badges, scores, etc. in one SBT collection. - -Secondly, unlike [EIP-1155](./eip-1155.md), in which each unit of fungible tokens is exactly the same, our interface can help differentiate between similar tokens. This is justified by that credential scores obtained from different entities differ not only in value but also in their effects, validity periods, origins, etc. However, they still share the same slot as they all contribute to a person's credibility, membership, etc. - -### Recovery mechanism - -To prevent the loss of SBTs, we propose a recovery mechanism that allows users to recover their tokens by providing a signature signed by their owner address. This mechanism is inspired by [EIP-1271](./eip-1271.md). - -Since SBTs are bound to an address and are meant to represent the identity of the address, which cannot be split into fractions. Therefore, each recovery should be considered as a transfer of all the tokens of the owner. This is why we use the `recover` function instead of `transferFrom` or `safeTransferFrom`. - -### Token visibility control - -Our interface allows users to control the visibility of their tokens (shadowing and revealing). This is useful when a user wants to hide some of their tokens from the public, for example, when they want to keep their membership secret. Generally, the issuer and the owner of the token have access to the token by default and can control the visibility of the token. After the token is shadowed, information about the token (e.g. token URI, owner of the token) cannot be queried by the public. - -## Backwards Compatibility - -This EIP proposes a new token interface which is meant to be used standalone, and is not backwards compatible with [EIP-721](./eip-721.md), [EIP-1155](./eip-1155.md), [EIP-3525](./eip-3525.md) or any other token standards. However, the naming style of functions and arguments follows the convention of [EIP-721](./eip-721.md) and [EIP-3525](./eip-3525.md), so that developers can understand the intentions easily. - -This EIP is compatible with [EIP-165](./eip-165.md). - -## Test Cases - -Our sample implementation includes test cases written using Hardhat. - -## Reference Implementation - -You can find our sample implementation [here](../assets/eip-5727/contracts/ERC5727Example.sol). - -## Security Considerations - -This EIP does not involve the general transfer of tokens, and thus there will be no security issues related to token transfer generally. - -However, users should be aware of the security risks of using the recovery mechanism. If a user loses his/her private key, all his/her soulbound tokens will be exposed to potential theft. The attacker can create a signature and restore all SBTs of the victim. Therefore, users should always keep their private keys safe. We recommend developers implement a recovery mechanism that requires multiple signatures to restore SBTs. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5727.md diff --git a/EIPS/eip-5732.md b/EIPS/eip-5732.md index 0828f88c2a39e0..158f4fea1254b8 100644 --- a/EIPS/eip-5732.md +++ b/EIPS/eip-5732.md @@ -1,125 +1,7 @@ --- eip: 5732 -title: Commit Interface -description: A simple but general commit interface to support commit-reveal scheme. -author: Zainan Victor Zhou (@xinbenlv), Matt Stam (@mattstam) -discussions-to: https://ethereum-magicians.org/t/erc-5732-simple-commit-interface-to-support-commit-reveal-schemes/11115 -status: Final -type: Standards Track category: ERC -created: 2022-09-29 -requires: 165, 1271 +status: Moved --- -## Abstract - -A simple commit interface to support commit-reveal scheme which provides **only** a commit -method but no reveal method, allowing implementations to integrate this interface -with arbitrary reveal methods such as `vote` or `transfer`. - -## Motivation - -1. support commit-reveal privacy for applications such as voting. -2. make it harder for attackers for front-running, back-running or sandwich attacks. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Interfaces referenced in this specification are as follows: - -```solidity -pragma solidity >=0.7.0 <0.9.0; - -// The EIP-165 identifier of this interface is 0xf14fcbc8 -interface IERC_COMMIT_CORE { - function commit(bytes32 _commitment) payable external; -} - -pragma solidity >=0.7.0 <0.9.0; - -// The EIP-165 identifier of this interface is 0x67b2ec2c -interface IERC_COMMIT_GENERAL { - event Commit( - uint256 indexed _timePoint, - address indexed _from, - bytes32 indexed _commitment, - bytes _extraData); - function commitFrom( - address _from, - bytes32 _commitment, - bytes calldata _extraData) - payable external returns(uint256 timePoint); -} -``` - -1. A compliant contract MUST implement the `IERC_COMMIT_CORE` interface. -2. A compliant contract SHOULD implement the `IERC_COMMIT_GENERAL` interface. -3. A compliant contract that implements the `IERC_COMMIT_GENERAL` interface MUST accept `commit(_commitment)` as equivalent to `commitFrom(msg.sender, _commitment, [/*empty array*/])`. -4. The `timePoint` return value of `commitFrom` is RECOMMENDED to use `block.timestamp` or `block.number` or a number that indicates the ordering of different commitments. When `commitFrom` is being called. -5. A compliant contract that implements `IERC_COMMIT_GENERAL` MUST emit event `Commit` when a commitment is accepted and recorded. In the parameter of both `Commit` and the `commitFrom` method, the `_timePoint` is a time-point-representing value that represents ordering of commitments in which a latter commitment will always have a _greater or equal value_ than a former commitment, such as `block.timestamp` or `block.number` or other time scale chosen by implementing contracts. - -6. The `extraData` is reserved for future behavior extension. If the `_from` is different from the TX signer, it is RECOMMENDED that compliant contract SHOULD validate signature for `_from`. For EOAs this will be validating its ECDSA signatures on chain. For smart contract accounts, it is RECOMMENDED to use [EIP-1271](./eip-1271.md) to validate the signatures. - -7. One or more methods of a compliant contract MAY be used for reveal. - -But there MUST be a way to supply an extra field of `secret_salt`, so that committer can later open the `secret_salt` in the reveal TX that exposes the `secret_salt`. The size and location of `secret_salt` is intentionally unspecified in this EIP to maximize flexibility for integration. - -8. It is RECOMMENDED for compliant contracts to implement [EIP-165](./eip-165.md). - -## Rationale - -1. One design options is that we can attach a Commit Interface to any individual ERCs such as voting standards or token standards. We choose to have a simple and generalize commit interface so all ERCs can be extended to support commit-reveal without changing their basic method signatures. - -2. The key derived design decision we made is we will have a standardized `commit` method without a standardized `reveal` method, making room for customized reveal method or using `commit` with existing standard. - -3. We chose to have a simple one parameter method of `commit` in our Core interface to make it fully backward compatible with a few prior-adoptions e.g. ENS - -4. We also add a `commitFrom` to easy commitment being generated off-chain and submitted by some account on behalf by another account. - -## Backwards Compatibility - -This EIP is backward compatible with all existing ERCs method signature that has extraData. New EIPs can be designed with an extra field of "salt" to make it easier to support this EIP, but not required. - -The `IERC_COMMIT_CORE` is backward compatible with ENS implementations and other existing prior-art. - -## Reference Implementation - -### Commit with ENS Register as Reveal - -In ENS registering process, currently inside of `ETHRegistrarController` contract a commit function is being used to allow registerer fairly register a desire domain to avoid being front-run. - -Here is how ENS uses commitment in its registration logic: - -```solidity -function commit(bytes32 commitment) public { - require(commitments[commitment] + maxCommitmentAge < now); - commitments[commitment] = now; -} -``` - -With this EIP it can be updated to - -```solidity -function commit(bytes32 commitment, bytes calldata data) public { - require(commitments[commitment] + maxCommitmentAge < now); - commitments[commitment] = now; - emit Commit(...); -} -``` - -## Security Considerations - -1. Do not use the reference implementation in production. It is just for demonstration purposes. -2. The reveal transactions and parameters, especially `secret_salt`, MUST be kept secret before they are revealed. -3. The length of `secret_salt` must be cryptographically long enough and the random values used to generate `secret_salt` must be cryptographically safe. -4. Users must NEVER reuse a used `secret_salt`. It's recommended for client applications to warn users who attempt to do so. -5. Contract implementations should consider deleting the commitment of a given sender immediately to reduce the chances of a replay attack or re-entry attack. -6. Contract implementations may consider including the ordering of commitment received to add restrictions on the order of reveal transactions. -7. There is potential for replay attacks across different chainIds or chains resulting from forks. In these cases, the chainId must be included in the generation of commitment. For applications with a higher risk of replay attacks, implementors should consider battle-tested and cryptographically-secure solutions such as [EIP-712](./eip-712.md) to compose commitments before creating their own new solution. -8. Proper time gaps are suggested if the purpose is to avoid frontrunning attacks. -9. For compliant contract that requires the `_timePoint` from the next transaction to be _strictly greater_ than that of any previous transaction, `block.timestamp` and `block.number` are not reliable as two transactions could co-exist in the same block resulting in the same `_timePoint` value. In such case, extra measures to enforce this strict monotonicity are required, such as the use of a separate sate variable in the contract to keep track of number of commits it receives, or to reject any second/other TX that shares the same `block.timestamp` or `block.number`. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5732.md diff --git a/EIPS/eip-5744.md b/EIPS/eip-5744.md index 19431e24941df5..9e7fdcb7185fbe 100644 --- a/EIPS/eip-5744.md +++ b/EIPS/eip-5744.md @@ -1,93 +1,7 @@ --- eip: 5744 -title: Latent Fungible Token -description: An interface for tokens that become fungible after a period of time. -author: Cozy Finance (@cozyfinance), Tony Sheng (@tonysheng), Matt Solomon (@mds1), David Laprade (@davidlaprade), Payom Dousti (@payomdousti), Chad Fleming (@chad-js), Franz Chen (@Dendrimer) -discussions-to: https://ethereum-magicians.org/t/eip-5744-latent-fungible-token/11111 -status: Draft -type: Standards Track category: ERC -created: 2022-09-29 -requires: 20, 2612 +status: Moved --- -## Abstract - -The following standard is an extension of [EIP-20](./eip-20.md) that enables tokens to become fungible after some initial non-fungible period. -Once minted, tokens are non-fungible until they reach maturity. -At maturity, they become fungible and can be transferred, traded, and used in any way that a standard EIP-20 token can be used. - -## Motivation - -Example use cases include: - -- Receipt tokens that do not become active until a certain date or condition is met. For example, this can be used to enforce minimum deposit durations in lending protocols. -- Vesting tokens that cannot be transferred or used until the vesting period has elapsed. - -## Specification - -All latent fungible tokens MUST implement EIP-20 to represent the token. -The `balanceOf` and `totalSupply` return quantities for all tokens, not just the matured, fungible tokens. -A new method called `balanceOfMatured` MUST be added to the ABI. -This method returns the balance of matured tokens for a given address: - -```solidity -function balanceOfMatured(address user) external view returns (uint256); -``` - -An additional method called `getMints` MUST be added, which returns an array of all mint metadata for a given address: - -```solidity -struct MintMetadata { - // Amount of tokens minted. - uint256 amount; - // Timestamp of the mint, in seconds. - uint256 time; - // Delay in seconds until these tokens mature and become fungible. When the - // delay is not known (e.g. if it's dependent on other factors aside from - // simply elapsed time), this value must be `type(uint256).max`. - uint256 delay; -} - -function getMints(address user) external view returns (MintMetadata[] memory); -``` - -Note that the implementation does not require that each of the above metadata parameters are stored as a `uint256`, just that they are returned as `uint256`. - -An additional method called `mints` MAY be added. -This method returns the metadata for a mint based on its ID: - -```solidity -function mints(address user, uint256 id) external view returns (MintMetadata memory); -``` - -The ID is not prescriptive—it may be an index in an array, or may be generated by other means. - -The `transfer` and `transferFrom` methods MAY be modified to revert when transferring tokens that have not matured. -Similarly, any methods that burn tokens MAY be modified to revert when burning tokens that have not matured. - -All latent fungible tokens MUST implement EIP-20’s optional metadata extensions. -The `name` and `symbol` functions MUST reflect the underlying token’s `name` and `symbol` in some way. - -## Rationale - -The `mints` method is optional because the ID is optional. In some use cases such as vesting where a user may have a maximum of one mint, an ID is not required. - -Similarly, vesting use cases may want to enforce non-transferrable tokens until maturity, whereas lending receipt tokens with a minimum deposit duration may want to support transfers at all times. - -It is possible that the number of mints held by a user is so large that it is impractical to return all of them in a single `eth_call`. -This is unlikely so it was not included in the spec. -If this is likely for a given use case, the implementer may choose to implement an alternative method that returns a subset of the mints, such as `getMints(address user, uint256 startId, uint256 endId)`. -However, if IDs are not sequential, a different signature may be required, and therefore this was not included in the specification. - -## Backwards Compatibility - -This proposal is fully backward compatible with the EIP-20 standard and has no known compatibility issues with other standards. - -## Security Considerations - -Iterating over large arrays of mints is not recommended, as this is very expensive and may cause the protocol, or just a user's interactions with it, to be stuck if this exceeds the block gas limit and reverts. There are some ways to mitigate this, with specifics dependent on the implementation. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5744.md diff --git a/EIPS/eip-5749.md b/EIPS/eip-5749.md index d151ffa9659965..b2b01d3d7e7b30 100644 --- a/EIPS/eip-5749.md +++ b/EIPS/eip-5749.md @@ -2,10 +2,9 @@ eip: 5749 title: The 'window.evmproviders' object description: Add 'window.evmproviders' and suggest the eventual removal of 'window.ethereum' -author: Kosala Hemachandra (@kvhnuke), Brett Kolodny (@brettkolodny) +author: Kosala Hemachandra (@kvhnuke) discussions-to: https://ethereum-magicians.org/t/eip-5749-deprecate-window-ethereum/11195 -status: Last Call -last-call-deadline: 2023-02-20 +status: Final type: Standards Track category: Interface created: 2022-10-04 @@ -31,8 +30,9 @@ At present, `window.ethereum` is the prevailing method by which Ethereum-compati - Enkrypt - Trust wallet - Rainbow + -Replacing `window.ethereum` with `window.evmproviders` will allow solutions such as web3modal and web3onboard to display all injected wallets the user has installed. This will simpify the UX and remove race conditions between wallet providers in case multiple wallets are installed. Over time, as `window.evmproviders` supplants the current standard and removes barriers to choice, we can hope to see a wallet landscape more reflective of user preference. +Replacing `window.ethereum` with `window.evmproviders` will allow solutions such as web3modal and web3onboard to display all injected wallets the user has installed. This will simplify the UX and remove race conditions between wallet providers in case multiple wallets are installed. Over time, as `window.evmproviders` supplants the current standard and removes barriers to choice, we can hope to see a wallet landscape more reflective of user preference. ## Specification diff --git a/EIPS/eip-5750.md b/EIPS/eip-5750.md index c570673aac4347..f32ca6d8a3d934 100644 --- a/EIPS/eip-5750.md +++ b/EIPS/eip-5750.md @@ -1,166 +1,7 @@ --- eip: 5750 -title: General Extensibility for Method Behaviors -description: Designating last param of dynamically sized bytes to be used for behavior extensions of methods. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-5750-method-with-extra-data/11176 -status: Final -type: Standards Track category: ERC -created: 2022-10-04 -requires: 165 +status: Moved --- -## Abstract - -This EIP standardizes the passing of unstructured call data to functions to enable future extensibility. - -## Motivation - -The purpose of having extra data in a method is to allow further extensions to existing method interfaces. - -It is it useful to make methods extendable. Any methods complying with this EIP, such as overloaded `transfer` and `vote` could use string reasons as the extra data. Existing EIPs that have exported methods compliant with this EIP can be extended for behaviors such as using the extra data to prove endorsement, as a salt, as a nonce, or as a commitment for a reveal/commit scheme. Finally, data can be passed forward to callbacks. - -There are two ways to achieve extensibility for existing functions. Each comes with their set of challenges: - -1. Add a new method - - * What will the method name be? - * What will the parameters be? - * How many use-cases does a given method signature support? - * Does this support off-chain signatures? - -2. Use one or more existing parameters, or add one or more new ones - - * Should existing parameters be repurposed, or should more be added? - * How many parameters should be used? - * What are their sizes and types? - -Standardizing how methods can be extended helps to answer these questions. - -Finally, this EIP aims to achieve maximum backward and future compatibility. Many EIPs already partially support this EIP, such as [EIP-721](./eip-721.md) and [EIP-1155](./eip-1155.md). This EIP supports many use cases, from commit-reveal schemes ([EIP-5732](./eip-5732.md)), to adding digital signatures alongside with a method call. Other implementers and EIPs should be able to depend on the compatibility granted by this EIP so that all compliant method interfaces are eligible for future new behaviors. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -When used in this EIP, the term `bytes` MUST be interpreted as the dynamically-sized byte array in Solidity data types. - -1. Unlike many other ERCs which is compliant at the `contract` level, this ERC's specification specify compliance at `method` level. - -2. Any method with a bytes as this method's last parameter is an _eligible_ method. It looks like this `function methodName(type1 value1, type2 value2, ... bytes data)`. - -3. A _compliant_ method MUST be an _eligible_ method and MUST also designate that last `bytes` field in its method parameter for behaviors extensions. - -4. If an _eligible_ method has an overloaded sibling method that -has the exact same method name and exact same preceding parameters -except for not having the last `bytes` parameter, the behavior -of the compliant method MUST be identical to -its overloaded sibling method when last `bytes` is an empty array. - -### Examples of compliant and non-compliant methods - -1. Here is a compliant method `methodName1` in a `Foo` contract - -```solidity -contract Foo { - // @dev This method allows extension behavior via `_data` field; - function methodName1(uint256 _param1, address _param2, bytes calldata _data); - function firstNonRelatedMethod(uint256 someValue); - function secondNonRelatedMethod(uint256 someValue); -} -``` - -2. Here is a compliant method `methodName2` in a `Bar` contract which is an overloaded method for another `methodName2`. - - -```solidity -contract Foo { - // @dev This is a sibling method to `methodName2(uint256 _param1, address _param2, bytes calldata _data);` - function methodName2(uint256 _param1, address _param2); - - // @dev This method allows extension behavior via `_data` field; - // When passed in an empty array for `_data` field, this method - // MUST behave IDENTICAL to - // its overloaded sibling `methodName2(uint256 _param1, address _param2);` - function methodName2(uint256 _param1, address _param2, bytes calldata _data); - - function firstNonRelatedMethod(uint256 someValue); - function secondNonRelatedMethod(uint256 someValue); -} -``` - -3. Here is a non-compliant method `methodName1` because it do not allow extending behavior - -```solidity -contract Foo { - // @dev This method DO NOT allow extension behavior via `_data` field; - function methodName1(uint256 _param1, address _param2, bytes calldata _data); - function firstNonRelatedMethod(uint256 someValue); - function secondNonRelatedMethod(uint256 someValue); -} -``` - -4. Here is a non-compliant method -`methodName2(uint256 _param1, address _param2, bytes calldata _data);` -because it behaves differently -to its overloaded sibling method -`methodName2(uint256 _param1, address _param2);` when `_data` is empty array. - -```solidity -contract Foo { - // @dev This is a sibling method to `methodName2(uint256 _param1, address _param2, bytes calldata _data);` - function methodName2(uint256 _param1, address _param2); - - // @dev This method allows extension behavior via `_data` field; - // When passed in an empty array for `_data` field, this method - // behave DIFFERENTLY to - // its overloaded sibling `methodName2(uint256 _param1, address _param2);` - function methodName2(uint256 _param1, address _param2, bytes calldata _data); - - function firstNonRelatedMethod(uint256 someValue); - function secondNonRelatedMethod(uint256 someValue); -} -``` - -## Rationale - -1. Using the dynamically-sized `bytes` type allows for maximum flexibility by enabling payloads of arbitrary types. -2. Having the bytes specified as the last parameter makes this EIP compatible with the calldata layout of solidity. - -## Backwards Compatibility - -Many existing EIPs already have compliant methods as part of their specification. All contracts compliant with those EIPs are either fully or partially compliant with this EIP. - -Here is an incomplete list: - -* In [EIP-721](./eip-721.md), the following method is already compliant: - * `function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;` is already compliant -* In [EIP-1155](./eip-1155.md), the following methods are already compliant - * `function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;` - * `function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;` -* In [EIP-777](./eip-777.md), the following methods are already compliant - * `function burn(uint256 amount, bytes calldata data) external;` - * `function send(address to, uint256 amount, bytes calldata data) external;` - -However, not all functions that have a `bytes` as the last parameter are compliant. The following functions are not compliant without an overload since their last parameter is involved in functionality: - -* In [EIP-2535](./eip-2535.md), the following methods is not compliant: - * `function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata) external;` - * **Either** of the following can be done to create a compliance. - 1. An overload MUST be created: `function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata, bytes calldata _data) external;` which adds a new `_data` after all parameters of original method. - 2. The use of `bytes memory _calldata` MUST be relaxed to allow for extending behaviors. -* In [EIP-1271](./eip-1271.md), the following method is not compliant: - * `function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue);` - * **Either** of the following can be done to create a compliance: - 1. An new overload MUST be created: `function isValidSignature(bytes32 _hash, bytes memory _signature, bytes calldata _data) public view returns (bytes4 magicValue);` which adds a new `_data` after all parameters of original method. - 2. The use of `bytes memory _signature` MUST be relaxed to allow for extending behaviors. - -## Security Considerations - -1. If using the extra data for extended behavior, such as supplying signature for onchain verification, or supplying commitments in a commit-reveal scheme, best practices should be followed for those particular extended behaviors. -2. Compliant contracts must also take into consideration that the data parameter will be publicly revealed when submitted into the mempool or included in a block, so one must consider the risk of replay and transaction ordering attacks. **Unencrypted personally identifiable information must never be included in the data parameter.** - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5750.md diff --git a/EIPS/eip-5753.md b/EIPS/eip-5753.md index b79986b1aa45a8..95e84334346758 100644 --- a/EIPS/eip-5753.md +++ b/EIPS/eip-5753.md @@ -1,255 +1,7 @@ --- eip: 5753 -title: Lockable Extension for EIP-721 -description: Interface for disabling token transfers (locking) and re-enabling them (unlocking). -author: Filipp Makarov (@filmakarov) -discussions-to: https://ethereum-magicians.org/t/lockable-nfts-extension/8800 -status: Draft -type: Standards Track category: ERC -created: 2022-10-05 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It introduces lockable NFTs. The locked asset can be used in any way except by selling and/or transferring it. The owner or operator can lock the token. When a token is locked, the unlocker address (an EOA or a contract) is set. Only the unlocker is able to `unlock` the token. - -## Motivation - -With NFTs, digital objects become digital goods, which are verifiably ownable, easily tradable, and immutably stored on the blockchain. That's why it's very important to continuously improve UX for non-fungible tokens, not just inherit it from one of the fungible tokens. - -In DeFi there is an UX pattern when you lock your tokens on a service smart contract. For example, if you want to borrow some $DAI, you have to provide some $ETH as collateral for a loan. During the loan period this $ETH is being locked into the lending service contract. Such a pattern works for $ETH and other fungible tokens. - -However, it should be different for NFTs because NFTs have plenty of use cases that require the NFT to stay in the holder's wallet even when it is used as collateral for a loan. You may want to keep using your NFT as a verified PFP on Twitter, or use it to authorize a Discord server through collab.land. You may want to use your NFT in a P2E game. And you should be able to do all of this even during the lending period, just like you are able to live in your house even if it is mortgaged. - -The following use cases are enabled for lockable NFTs: - -- **NFT-collateralised loans** Use your NFT as collateral for a loan without locking it on the lending protocol contract. Lock it on your wallet instead and continue enjoying all the utility of your NFT. -- **No collateral rentals of NFTs** Borrow NFT for a fee, without a need for huge collateral. You can use NFT, but not transfer it, so the lender is safe. The borrowing service contract automatically transfers NFT back to the lender as soon as the borrowing period expires. -- **Primary sales** Mint NFT for only the part of the price and pay the rest when you are satisfied with how the collection evolves. -- **Secondary sales** Buy and sell your NFT by installments. Buyer gets locked NFT and immediately starts using it. At the same time he/she is not able to sell the NFT until all the installments are paid. If full payment is not received, NFT goes back to the seller together with a fee. -- **S is for Safety** Use your exclusive blue chip NFTs safely and conveniently. The most convenient way to use NFT is together with MetaMask. However, MetaMask is vulnerable to various bugs and attacks. With `Lockable` extension you can lock your NFT and declare your safe cold wallet as an unlocker. Thus, you can still keep your NFT on MetaMask and use it conveniently. Even if a hacker gets access to your MetaMask, they won’t be able to transfer your NFT without access to the cold wallet. That’s what makes `Lockable` NFTs safe. -- **Metaverse ready** Locking NFT tickets can be useful during huge Metaverse events. That will prevent users, who already logged in with an NFT, from selling it or transferring it to another user. Thus we avoid double usage of one ticket. -- **Non-custodial staking** There are different approaches to non-custodial staking proposed by communities like CyberKongz, Moonbirds and other. Approach suggested in this impementation supposes that the token can only be staked in one place, not several palces at a time (it is like you can not deposit money in two bank accounts simultaneously). Also it doesn't require any additional code and is available with just locking feature. -Another approach to the same concept is using locking to provide proof of HODL. You can lock your NFTs from selling as a manifestation of loyalty to the community and start earning rewards for that. It is better version of the rewards mechanism, that was originally introduced by The Hashmasks and their $NCT token. -- **Safe and convenient co-ownership and co-usage** Extension of safe co-ownership and co-usage. For example, you want to purchase an expensive NFT asset together with friends, but it is not handy to use it with multisig, so you can safely rotate and use it between wallets. The NFT will be stored on one of the co-owners' wallet and he will be able to use it in any way (except transfers) without requiring multi-approval. Transfers will require multi-approval. - - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -EIP-721 compliant contracts MAY implement this EIP to provide standard methods of locking and unlocking the token at its current owner address. -If the token is locked, the `getLocked` function MUST return an address that is able to unlock the token. -For tokens that are not locked, the `getLocked` function MUST return `address(0)`. -The user MAY permanently lock the token by calling `lock(address(1), tokenId)`. - -When the token is locked, all the [EIP-721](./eip-721.md) transfer functions MUST revert, except if the transaction has been initiated by an unlocker. -When the token is locked, the [EIP-721](./eip-721.md) `approve` method MUST revert for this token. -When the token is locked, the [EIP-721](./eip-721.md) `getApproved` method SHOULD return `unlocker` address for this token so the unlocker is able to transfer this token. -When the token is locked, the `lock` method MUST revert for this token, even when it is called with the same `unlocker` as argument. -When the locked token is transferred by an unlocker, the token MUST be unlocked after the transfer. - -Marketplaces should call `getLocked` method of an EIP-721 Lockable token contract to learn whether a token with a specified tokenId is locked or not. Locked tokens SHOULD NOT be available for listings. Locked tokens can not be sold. Thus, marketplaces SHOULD hide the listing for the tokens that has been locked, because such orders can not be fulfilled. - -### Contract Interface - -```solidity -pragma solidity >=0.8.0; - -/// @dev Interface for the Lockable extension - -interface ILockable { - - /** - * @dev Emitted when `id` token is locked, and `unlocker` is stated as unlocking wallet. - */ - event Lock (address indexed unlocker, uint256 indexed id); - - /** - * @dev Emitted when `id` token is unlocked. - */ - event Unlock (uint256 indexed id); - - /** - * @dev Locks the `id` token and gives the `unlocker` address permission to unlock. - */ - function lock(address unlocker, uint256 id) external; - - /** - * @dev Unlocks the `id` token. - */ - function unlock(uint256 id) external; - - /** - * @dev Returns the wallet, that is stated as unlocking wallet for the `tokenId` token. - * If address(0) returned, that means token is not locked. Any other result means token is locked. - */ - function getLocked(uint256 tokenId) external view returns (address); - -} -``` - -The `supportsInterface` method MUST return `true` when called with `0x72b68110`. - -## Rationale - -This approach proposes a solution that is designed to be as minimal as possible. It only allows to lock the item (stating who will be able to unlock it) and unlock it when needed if a user has permission to do it. - -At the same time, it is a generalized implementation. It allows for a lot of extensibility and any of the potential use cases (or all of them), mentioned in the Motivation section. - -When there is a need to grant temporary and/or redeemable rights for the token (rentals, purchase with instalments) this EIP involves the real transfer of the token to the temporary user's wallet, not just assigning a role. -This choice was made to increase compatibility with all the existing NFT eco-system tools and dApps, such as Collab.land. Otherwise, it would require from all of such dApps implementing additional interfaces and logic. - -Naming and reference implementation for the functions and storage entities mimics that of Approval flow for [EIP-721] in order to be intuitive. - -## Backwards Compatibility - -This standard is compatible with current [EIP-721](./eip-721.md) standards. - -## Reference Implementation - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity >=0.8.0; - -import '../ILockable.sol'; -import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; - -/// @title Lockable Extension for ERC721 - -abstract contract ERC721Lockable is ERC721, ILockable { - - /*/////////////////////////////////////////////////////////////// - LOCKABLE EXTENSION STORAGE - //////////////////////////////////////////////////////////////*/ - - mapping(uint256 => address) internal unlockers; - - /*/////////////////////////////////////////////////////////////// - LOCKABLE LOGIC - //////////////////////////////////////////////////////////////*/ - - /** - * @dev Public function to lock the token. Verifies if the msg.sender is the owner - * or approved party. - */ - - function lock(address unlocker, uint256 id) public virtual { - address tokenOwner = ownerOf(id); - require(msg.sender == tokenOwner || isApprovedForAll(tokenOwner, msg.sender) - , "NOT_AUTHORIZED"); - require(unlockers[id] == address(0), "ALREADY_LOCKED"); - unlockers[id] = unlocker; - _approve(unlocker, id); - } - - /** - * @dev Public function to unlock the token. Only the unlocker (stated at the time of locking) can unlock - */ - function unlock(uint256 id) public virtual { - require(msg.sender == unlockers[id], "NOT_UNLOCKER"); - unlockers[id] = address(0); - } - - /** - * @dev Returns the unlocker for the tokenId - * address(0) means token is not locked - * reverts if token does not exist - */ - function getLocked(uint256 tokenId) public virtual view returns (address) { - require(_exists(tokenId), "Lockable: locking query for nonexistent token"); - return unlockers[tokenId]; - } - - /** - * @dev Locks the token - */ - function _lock(address unlocker, uint256 id) internal virtual { - unlockers[id] = unlocker; - } - - /** - * @dev Unlocks the token - */ - function _unlock(uint256 id) internal virtual { - unlockers[id] = address(0); - } - - /*/////////////////////////////////////////////////////////////// - OVERRIDES - //////////////////////////////////////////////////////////////*/ - - function approve(address to, uint256 tokenId) public virtual override { - require (getLocked(tokenId) == address(0), "Can not approve locked token"); - super.approve(to, tokenId); - } - - function _beforeTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override { - // if it is a Transfer or Burn - if (from != address(0)) { - // token should not be locked or msg.sender should be unlocker to do that - require(getLocked(tokenId) == address(0) || msg.sender == getLocked(tokenId), "LOCKED"); - } - } - - function _afterTokenTransfer( - address from, - address to, - uint256 tokenId - ) internal virtual override { - // if it is a Transfer or Burn, we always deal with one token, that is startTokenId - if (from != address(0)) { - // clear locks - delete unlockers[tokenId]; - } - } - - /** - * @dev Optional override, if to clear approvals while the tken is locked - */ - function getApproved(uint256 tokenId) public view virtual override returns (address) { - if (getLocked(tokenId) != address(0)) { - return address(0); - } - return super.getApproved(tokenId); - } - - /*/////////////////////////////////////////////////////////////// - ERC165 LOGIC - //////////////////////////////////////////////////////////////*/ - - function supportsInterface(bytes4 interfaceId) - public - view - virtual - override - returns (bool) - { - return - interfaceId == type(IERC721Lockable).interfaceId || - super.supportsInterface(interfaceId); - } - -} -``` - -## Security Considerations - -There are no security considerations related directly to the implementation of this standard for the contract that manages [EIP-721](./eip-721.md) tokens. - -### Considerations for the contracts that work with lockable tokens - -- Make sure that every contract that is stated as `unlocker` can actually unlock the token in all cases. -- There are use cases, that involve transferring the token to a temporary owner and then lock it. For example, NFT rentals. Smart contracts that manage such services should always use `transferFrom` instead of `safeTransferFrom` to avoid re-entrancies. -- There are no MEV considerations regarding lockable tokens as only authorized parties are allowed to lock and unlock. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5753.md diff --git a/EIPS/eip-5773.md b/EIPS/eip-5773.md index 43918b3f44db52..90311d5f30e254 100644 --- a/EIPS/eip-5773.md +++ b/EIPS/eip-5773.md @@ -1,495 +1,7 @@ --- eip: 5773 -title: Context-Dependent Multi-Asset Tokens -description: An interface for Multi-Asset tokens with context dependent asset type output controlled by owner's preference. -author: Bruno Škvorc (@Swader), Cicada (@CicadaNCR), Steven Pineda (@steven2308), Stevan Bogosavljevic (@stevyhacker), Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/multiresource-tokens/11326 -status: Review -type: Standards Track category: ERC -created: 2022-10-10 -requires: 165, 721 +status: Moved --- -## Abstract - -The Multi-Asset NFT standard allows for the construction of a new primitive: context-dependent output of information per single NFT. - -The context-dependent output of information means that the asset in an appropriate format is displayed based on how the token is being accessed. I.e. if the token is being opened in an e-book reader, the PDF asset is displayed, if the token is opened in the marketplace, the PNG or the SVG asset is displayed, if the token is accessed from within a game, the 3D model asset is accessed and if the token is accessed by the (Internet of Things) IoT hub, the asset providing the neseccary addressing and specification information is accessed. - -An NFT can have multiple assets (outputs), which can be any kind of file to be served to the consumer, and orders them by priority. They do not have to match in mimetype or tokenURI, nor do they depend on one another. Assets are not standalone entities, but should be thought of as “namespaced tokenURIs” that can be ordered at will by the NFT owner, but only modified, updated, added, or removed if agreed on by both the owner of the token and the issuer of the token. - -## Motivation - -With NFTs being a widespread form of tokens in the Ethereum ecosystem and being used for a variety of use cases, it is time to standardize additional utility for them. Having multiple assets associated with a single NFT allows for greater utility, usability and forward compatibility. - -In the four years since [EIP-721](./eip-721.md) was published, the need for additional functionality has resulted in countless extensions. This EIP improves upon EIP-721 in the following areas: - -- [Cross-metaverse compatibility](#cross-metaverse-compatibility) -- [Multi-media output](#multi-media-output) -- [Media redundancy](#media-redundancy) -- [NFT evolution](#nft-evolution) - -### Cross-metaverse compatibility - -At the time of writing this proposal, the metaverse is still a fledgling, not full defined, term. No matter how the definition of metaverse evolves, the proposal can support any number of different implementations. - -Cross-metaverse compatibility could also be referred to as cross-engine compatibility. An example of this is where a cosmetic item for game A is not available in game B because the frameworks are incompatible. - -Such NFT can be given further utility by means of new additional assets: more games, more cosmetic items, appended to the same NFT. Thus, a game cosmetic item as an NFT becomes an ever-evolving NFT of infinite utility. - -The following is a more concrete example. One asset is a cosmetic item for game A, a file containing the cosmetic assets. Another is a cosmetic asset file for game B. A third is a generic asset intended to be shown in catalogs, marketplaces, portfolio trackers, or other generalized NFT viewers, containing a representation, stylized thumbnail, and animated demo/trailer of the cosmetic item. - -This EIP adds a layer of abstraction, allowing game developers to directly pull asset data from a user's NFTs instead of hard-coding it. - -### Multi-media output - -An NFT of an eBook can be represented as a PDF, MP3, or some other format, depending on what software loads it. If loaded into an eBook reader, a PDF should be displayed, and if loaded into an audiobook application, the MP3 representation should be used. Other metadata could be present in the NFT (perhaps the book's cover image) for identification on various marketplaces, Search Engine Result Pages (SERPs), or portfolio trackers. - -### Media redundancy - -Many NFTs are minted hastily without best practices in mind - specifically, many NFTs are minted with metadata centralized on a server somewhere or, in some cases, a hardcoded IPFS gateway which can also go down, instead of just an IPFS hash. - -By adding the same metadata file as different assets, e.g., one asset of a metadata and its linked image on Arweave, one asset of this same combination on Sia, another of the same combination on IPFS, etc., the resilience of the metadata and its referenced information increases exponentially as the chances of all the protocols going down at once become less likely. - -### NFT evolution - -Many NFTs, particularly game related ones, require evolution. This is especially the case in modern metaverses where no metaverse is actually a metaverse - it is just a multiplayer game hosted on someone's server which replaces username/password logins with reading an account's NFT balance. - -When the server goes down or the game shuts down, the player ends up with nothing (loss of experience) or something unrelated (assets or accessories unrelated to the game experience, spamming the wallet, incompatible with other “verses” - see [cross-metaverse](#cross-metaverse-compatibility) compatibility above). - -With Multi-Asset NFTs, a minter or another pre-approved entity is allowed to suggest a new asset to the NFT owner who can then accept it or reject it. The asset can even target an existing asset which is to be replaced. - -Replacing an asset could, to some extent, be similar to replacing an EIP-721 token's URI. When an asset is replaced a clear line of traceability remains; the old asset is still reachable and verifiable. Replacing an asset's metadata URI obscures this lineage. It also gives more trust to the token owner if the issuer cannot replace the asset of the NFT at will. The propose-accept asset replacement mechanic of this proposal provides this assurance. - -This allows level-up mechanics where, once enough experience has been collected, a user can accept the level-up. The level-up consists of a new asset being added to the NFT, and once accepted, this new asset replaces the old one. - -As a concrete example, think of Pokemon™️ evolving - once enough experience has been attained, a trainer can choose to evolve their monster. With Multi-Asset NFTs, it is not necessary to have centralized control over metadata to replace it, nor is it necessary to airdrop another NFT into the user's wallet - instead, a new Raichu asset is minted onto Pikachu, and if accepted, the Pikachu asset is gone, replaced by Raichu, which now has its own attributes, values, etc. - -Alternative example of this, could be version control of an IoT device's firmware. An asset could represent its current firmware and once an update becomes available, the current asset could be replaced with the one containing the updated firmware. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// @title EIP-5773 Context-Dependent Multi-Asset Tokens -/// @dev See https://eips.ethereum.org/EIPS/eip-5773 -/// @dev Note: the ERC-165 identifier for this interface is 0xd1526708. - -pragma solidity ^0.8.16; - -interface IMultiAsset { - /** - * @notice Used to notify listeners that an asset object is initialised at `assetId`. - * @param assetId ID of the asset that was initialised - */ - event AssetSet(uint64 assetId); - - /** - * @notice Used to notify listeners that an asset object at `assetId` is added to token's pending asset - * array. - * @param tokenId ID of the token that received a new pending asset - * @param assetId ID of the asset that has been added to the token's pending assets array - * @param replacesId ID of the asset that would be replaced - */ - event AssetAddedToToken( - uint256 indexed tokenId, - uint64 indexed assetId, - uint64 indexed replacesId - ); - - /** - * @notice Used to notify listeners that an asset object at `assetId` is accepted by the token and migrated - * from token's pending assets array to active assets array of the token. - * @param tokenId ID of the token that had a new asset accepted - * @param assetId ID of the asset that was accepted - * @param replacesId ID of the asset that was replaced - */ - event AssetAccepted( - uint256 indexed tokenId, - uint64 indexed assetId, - uint64 indexed replacesId - ); - - /** - * @notice Used to notify listeners that an asset object at `assetId` is rejected from token and is dropped - * from the pending assets array of the token. - * @param tokenId ID of the token that had an asset rejected - * @param assetId ID of the asset that was rejected - */ - event AssetRejected(uint256 indexed tokenId, uint64 indexed assetId); - - /** - * @notice Used to notify listeners that token's priority array is reordered. - * @param tokenId ID of the token that had the asset priority array updated - */ - event AssetPrioritySet(uint256 indexed tokenId); - - /** - * @notice Used to notify listeners that owner has granted an approval to the user to manage the assets of a - * given token. - * @dev Approvals must be cleared on transfer - * @param owner Address of the account that has granted the approval for all token's assets - * @param approved Address of the account that has been granted approval to manage the token's assets - * @param tokenId ID of the token on which the approval was granted - */ - event ApprovalForAssets( - address indexed owner, - address indexed approved, - uint256 indexed tokenId - ); - - /** - * @notice Used to notify listeners that owner has granted approval to the user to manage assets of all of their - * tokens. - * @param owner Address of the account that has granted the approval for all assets on all of their tokens - * @param operator Address of the account that has been granted the approval to manage the token's assets on all of the - * tokens - * @param approved Boolean value signifying whether the permission has been granted (`true`) or revoked (`false`) - */ - event ApprovalForAllForAssets( - address indexed owner, - address indexed operator, - bool approved - ); - - /** - * @notice Accepts an asset at from the pending array of given token. - * @dev Migrates the asset from the token's pending asset array to the token's active asset array. - * @dev Active assets cannot be removed by anyone, but can be replaced by a new asset. - * @dev Requirements: - * - * - The caller must own the token or be approved to manage the token's assets - * - `tokenId` must exist. - * - `index` must be in range of the length of the pending asset array. - * @dev Emits an {AssetAccepted} event. - * @param tokenId ID of the token for which to accept the pending asset - * @param index Index of the asset in the pending array to accept - * @param assetId Id of the asset expected to be in the index - */ - function acceptAsset( - uint256 tokenId, - uint256 index, - uint64 assetId - ) external; - - /** - * @notice Rejects an asset from the pending array of given token. - * @dev Removes the asset from the token's pending asset array. - * @dev Requirements: - * - * - The caller must own the token or be approved to manage the token's assets - * - `tokenId` must exist. - * - `index` must be in range of the length of the pending asset array. - * @dev Emits a {AssetRejected} event. - * @param tokenId ID of the token that the asset is being rejected from - * @param index Index of the asset in the pending array to be rejected - * @param assetId Id of the asset expected to be in the index - */ - function rejectAsset( - uint256 tokenId, - uint256 index, - uint64 assetId - ) external; - - /** - * @notice Rejects all assets from the pending array of a given token. - * @dev Effectively deletes the pending array. - * @dev Requirements: - * - * - The caller must own the token or be approved to manage the token's assets - * - `tokenId` must exist. - * @dev Emits a {AssetRejected} event with assetId = 0. - * @param tokenId ID of the token of which to clear the pending array - * @param maxRejections to prevent from rejecting assets which arrive just before this operation. - */ - function rejectAllAssets(uint256 tokenId, uint256 maxRejections) external; - - /** - * @notice Sets a new priority array for a given token. - * @dev The priority array is a non-sequential list of `uint16`s, where the lowest value is considered highest - * priority. - * @dev Value `0` of a priority is a special case equivalent to uninitialised. - * @dev Requirements: - * - * - The caller must own the token or be approved to manage the token's assets - * - `tokenId` must exist. - * - The length of `priorities` must be equal the length of the active assets array. - * @dev Emits a {AssetPrioritySet} event. - * @param tokenId ID of the token to set the priorities for - * @param priorities An array of priorities of active assets. The succession of items in the priorities array - * matches that of the succession of items in the active array - */ - function setPriority(uint256 tokenId, uint16[] calldata priorities) - external; - - /** - * @notice Used to retrieve IDs of the active assets of given token. - * @dev Asset data is stored by reference, in order to access the data corresponding to the ID, call - * `getAssetMetadata(tokenId, assetId)`. - * @dev You can safely get 10k - * @param tokenId ID of the token to retrieve the IDs of the active assets - * @return uint64[] An array of active asset IDs of the given token - */ - function getActiveAssets(uint256 tokenId) - external - view - returns (uint64[] memory); - - /** - * @notice Used to retrieve IDs of the pending assets of given token. - * @dev Asset data is stored by reference, in order to access the data corresponding to the ID, call - * `getAssetMetadata(tokenId, assetId)`. - * @param tokenId ID of the token to retrieve the IDs of the pending assets - * @return uint64[] An array of pending asset IDs of the given token - */ - function getPendingAssets(uint256 tokenId) - external - view - returns (uint64[] memory); - - /** - * @notice Used to retrieve the priorities of the active assets of a given token. - * @dev Asset priorities are a non-sequential array of uint16 values with an array size equal to active asset - * priorites. - * @param tokenId ID of the token for which to retrieve the priorities of the active assets - * @return uint16[] An array of priorities of the active assets of the given token - */ - function getActiveAssetPriorities(uint256 tokenId) - external - view - returns (uint16[] memory); - - /** - * @notice Used to retrieve the asset that will be replaced if a given asset from the token's pending array - * is accepted. - * @dev Asset data is stored by reference, in order to access the data corresponding to the ID, call - * `getAssetMetadata(tokenId, assetId)`. - * @param tokenId ID of the token to check - * @param newAssetId ID of the pending asset which will be accepted - * @return uint64 ID of the asset which will be replaced - */ - function getAssetReplacements(uint256 tokenId, uint64 newAssetId) - external - view - returns (uint64); - - /** - * @notice Used to fetch the asset metadata of the specified token's active asset with the given index. - * @dev Can be overriden to implement enumerate, fallback or other custom logic. - * @param tokenId ID of the token from which to retrieve the asset metadata - * @param assetId Asset Id, must be in the active assets array - * @return string The metadata of the asset belonging to the specified index in the token's active assets - * array - */ - function getAssetMetadata(uint256 tokenId, uint64 assetId) - external - view - returns (string memory); - - /** - * @notice Used to grant permission to the user to manage token's assets. - * @dev This differs from transfer approvals, as approvals are not cleared when the approved party accepts or - * rejects an asset, or sets asset priorities. This approval is cleared on token transfer. - * @dev Only a single account can be approved at a time, so approving the `0x0` address clears previous approvals. - * @dev Requirements: - * - * - The caller must own the token or be an approved operator. - * - `tokenId` must exist. - * @dev Emits an {ApprovalForAssets} event. - * @param to Address of the account to grant the approval to - * @param tokenId ID of the token for which the approval to manage the assets is granted - */ - function approveForAssets(address to, uint256 tokenId) external; - - /** - * @notice Used to retrieve the address of the account approved to manage assets of a given token. - * @dev Requirements: - * - * - `tokenId` must exist. - * @param tokenId ID of the token for which to retrieve the approved address - * @return address Address of the account that is approved to manage the specified token's assets - */ - function getApprovedForAssets(uint256 tokenId) - external - view - returns (address); - - /** - * @notice Used to add or remove an operator of assets for the caller. - * @dev Operators can call {acceptAsset}, {rejectAsset}, {rejectAllAssets} or {setPriority} for any token - * owned by the caller. - * @dev Requirements: - * - * - The `operator` cannot be the caller. - * @dev Emits an {ApprovalForAllForAssets} event. - * @param operator Address of the account to which the operator role is granted or revoked from - * @param approved The boolean value indicating whether the operator role is being granted (`true`) or revoked - * (`false`) - */ - function setApprovalForAllForAssets(address operator, bool approved) - external; - - /** - * @notice Used to check whether the address has been granted the operator role by a given address or not. - * @dev See {setApprovalForAllForAssets}. - * @param owner Address of the account that we are checking for whether it has granted the operator role - * @param operator Address of the account that we are checking whether it has the operator role or not - * @return bool The boolean value indicating whether the account we are checking has been granted the operator role - */ - function isApprovedForAllForAssets(address owner, address operator) - external - view - returns (bool); -} -``` - -The `getAssetMetadata` function returns the asset's metadata URI. The metadata, to which the metadata URI of the asset points, MAY contain a JSON response with the following fields: - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the name of the asset associated with the asset" - }, - "description": { - "type": "string", - "description": "Identifies the general notes, abstracts, or summaries about the contents of the asset" - }, - "type": { - "type": "string", - "description": "Identifies the definition of the type of content of the asset" - }, - "locale": { - "type": "string", - "description": "Identifies metadata locale in ISO 639-1 format for translations and localisation of the asset" - }, - "license": { - "type": "string", - "description": "Identifies the license attached to the asset" - }, - "licenseUri": { - "type": "string", - "description": "Identifies the URI to the license statement of the license attached to the asset" - }, - "mediaUri": { - "type": "string", - "description": "Identifies the URI of the main media file associated with the asset" - }, - "thumbnailUri": { - "type": "string", - "description": "Identifies the URI of the thumbnail image associated with the asset to be used for preview of the asset in the wallets and client applications (the recommended maximum size is 350x350 px)" - }, - "externalUri": { - "type": "string", - "description": "Identifies the URI to the additional information about the subject or content of the asset" - }, - "properties": { - "type": "object", - "properties": "Identifies the optional custom attributes of the asset" - } - } -} -``` - -While this is the suggested JSON schema for the asset metadata, it is not enforced and MAY be structured completely differently based on implementer's preference. - -The optional properties of the metadata JSON MAY include the following fields, or it MAY incorporate any number of custom fields, but MAY also not be included in the schema at all: - -```json - "properties": { - "rarity": { - "type": "string", - "value": "epic" - }, - "color": { - "type": "string", - "value": "red" - }, - "height": { - "type": "float", - "value": 192.4 - }, - "tags": { - "type": "array", - "value": ["music", "2020", "best"] - } - } -``` - -## Rationale - -Designing the proposal, we considered the following questions: - -1. **Should we use Asset or Resource when referring to the structure that comprises the token?**\ -The original idea was to call the proposal Multi-Resource, but while this denoted the broadness of the structures that could be held by a single token, the term *asset* represents it better.\ -An asset is defined as something that is owned by a person, company, or organization, such as money, property, or land. This is the best representation of what an asset of this proposal can be. An asset in this proposal can be a multimedia file, technical information, a land deed, or anything that the implementer has decided to be an asset of the token they are implementing. -2. **Why are [EIP-712](./eip-712.md) permit-style signatures to manage approvals not used?**\ -For consistency. This proposal extends EIP-721 which already uses 1 transaction for approving operations with tokens. It would be inconsistent to have this and also support signing messages for operations with assets. -3. **Why use indexes?**\ -To reduce the gas consumption. If the asset ID was used to find which asset to accept or reject, iteration over arrays would be required and the cost of the operation would depend on the size of the active or pending assets arrays. With the index, the cost is fixed. A list of active and pending assets arrays per token need to be maintained, since methods to get them are part of the proposed interface.\ -To avoid race conditions in which the index of an asset changes, the expected asset ID is included in operations requiring asset index, to verify that the asset being accessed using the index is the expected asset.\ -Implementation that would internally keep track of indices using mapping was attempted. The average cost of adding an asset to a token increased by over 25%, costs of accepting and rejecting assets also increased 4.6% and 7.1% respectively. We concluded that it is not necessary for this proposal and can be implemented as an extension for use cases willing to accept this cost. In the sample implementation provided, there are several hooks which make this possible. -4. **Why is a method to get all the assets not included?**\ -Getting all assets might not be an operation necessary for all implementers. Additionally, it can be added either as an extension, doable with hooks, or can be emulated using an indexer. -5. **Why is pagination not included?**\ -Asset IDs use `uint64`, testing has confirmed that the limit of IDs you can read before reaching the gas limit is around 30.000. This is not expected to be a common use case so it is not a part of the interface. However, an implementer can create an extension for this use case if needed. -6. **How does this proposal differ from the other proposals trying to address a similar problem?**\ -After reviewing them, we concluded that each contains at least one of these limitations: - - Using a single URI which is replaced as new assets are needed, this introduces a trust issue for the token owner. - - Focusing only on a type of asset, while this proposal is asset type agnostic. - - Having a different token for each new use case, this means that the token is not forward-compatible. - -### Multi-Asset Storage Schema - -Assets are stored within a token as an array of `uint64` identifiers. - -In order to reduce redundant on-chain string storage, multi asset tokens store assets by reference via inner storage. An asset entry on the storage is stored via a `uint64` mapping to asset data. - -An asset array is an array of these `uint64` asset ID references. - -Such a structure allows that, a generic asset can be added to the storage one time, and a reference to it can be added to the token contract as many times as we desire. Implementers can then use string concatenation to procedurally generate a link to a content-addressed archive based on the base *SRC* in the asset and the *token ID*. Storing the asset in a new token will only take 16 bytes of storage in the asset array per token for recurrent as well as `tokenId` dependent assets. - -Structuring token's assets in such a way allows for URIs to be derived programmatically through concatenation, especially when they differ only by `tokenId`. - -### Propose-Commit pattern for asset addition - -Adding assets to an existing token MUST be done in the form of a propose-commit pattern to allow for limited mutability by a 3rd party. When adding an asset to a token, it is first placed in the *"Pending"* array, and MUST be migrated to the *"Active"* array by the token's owner. The *"Pending"* assets array SHOULD be limited to 128 slots to prevent spam and griefing. - -### Asset management - -Several functions for asset management are included. In addition to permissioned migration from "Pending" to "Active", the owner of a token MAY also drop assets from both the active and the pending array -- an emergency function to clear all entries from the pending array MUST also be included. - -## Backwards Compatibility - -The MultiAsset token standard has been made compatible with [EIP-721](./eip-721.md) in order to take advantage of the robust tooling available for implementations of EIP-721 and to ensure compatibility with existing EIP-721 infrastructure. - -## Test Cases - -Tests are included in [`multiasset.ts`](../assets/eip-5773/test/multiasset.ts). - -To run them in terminal, you can use the following commands: - -``` -cd ../assets/eip-5773 -npm install -npx hardhat test -``` - -## Reference Implementation - -See [`MultiAssetToken.sol`](../assets/eip-5773/contracts/MultiAssetToken.sol). - -## Security Considerations - -The same security considerations as with [EIP-721](./eip-721.md) apply: hidden logic may be present in any of the functions, including burn, add asset, accept asset, and more. - -Caution is advised when dealing with non-audited contracts. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5773.md diff --git a/EIPS/eip-5791.md b/EIPS/eip-5791.md index 0b1048104cbe94..8595df44d85862 100644 --- a/EIPS/eip-5791.md +++ b/EIPS/eip-5791.md @@ -1,165 +1,7 @@ --- eip: 5791 -title: Physical Backed Tokens -description: Minimal interface for linking ownership of EIP-721 NFTs to a physical chip -author: 2pmflow (@2pmflow), locationtba (@locationtba), Cameron Robertson (@ccamrobertson), cygaar (@cygaar) -discussions-to: https://ethereum-magicians.org/t/physical-backed-tokens/11350 -status: Draft -type: Standards Track category: ERC -created: 2022-10-17 -requires: 191, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It proposes a minimal interface for a [EIP-721](./eip-721.md) NFT to be "physically backed" and owned by whoever owns the NFT's physical counterpart. - -## Motivation - -NFT collectors enjoy collecting digital assets and sharing them with others online. However, there is currently no such standard for showcasing physical assets as NFTs with verified authenticity and ownership. Existing solutions are fragmented and tend to be susceptible to at least one of the following: - -- The ownership of the physical item and the ownership of the NFT are decoupled. - -- Verifying the authenticity of the physical item requires action from a trusted 3rd party (e.g. StockX). - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Requirements - -This approach requires that the physical item must have a chip attached to it that fulfills the following requirements: - -- The chip can securely generate and store an ECDSA secp256k1 asymmetric key pair; -- The chip can sign messages using the private key of the previously-generated asymmetric key pair; -- The chip exposes the public key; and -- The private key cannot be extracted - -The approach also requires that the contract uses an account-bound implementation of [EIP-721](./eip-721.md) (where all [EIP-721](./eip-721.md) functions that transfer must throw, e.g. the "read only NFT registry" implementation referenced in [EIP-721](./eip-721.md)). This ensures that ownership of the physical item is required to initiate transfers and manage ownership of the NFT, through a new function introduced in this interface described below. - -### Approach - -Each NFT is conceptually linked to a physical chip. - -When the NFT is minted, it must also emit an event that includes the corresponding chip address (20-byte address derived from the chip's public key). This lets downstream indexers know which chip addresses are mapped to which tokens for the NFT collection. The NFT cannot be minted without its token id being linked to a specific chip. - -The interface includes a function called `transferTokenWithChip` that transfers the NFT to the function caller if a valid signature signed by the chip is passed in. A valid signature must follow the schemes set forth in [EIP-191](./eip-191.md) and [EIP-2](./eip-2.md) (s-value restrictions), where the data to sign consists of the target recipient address (the function caller) and a recent blockhash (the level of recency is up to the implementation). - -The interface also includes other functions that let anyone validate whether the chip in the physical item is backing an existing NFT in the collection. - -### Interface - -```solidity - -interface IERC5791 { - /// @notice Returns the token id for a given chip address. - /// @dev Throws if there is no existing token for the chip in the collection. - /// @param chipAddress The address for the chip embedded in the physical item (computed from the chip's public key). - /// @return The token id for the passed in chip address. - function tokenIdFor(address chipAddress) external view returns (uint256); - - /// @notice Returns true if the chip for the specified token id is the signer of the signature of the payload. - /// @dev Throws if tokenId does not exist in the collection. - /// @param tokenId The token id. - /// @param payload Arbitrary data that is signed by the chip to produce the signature param. - /// @param signature Chip's signature of the passed-in payload. - /// @return Whether the signature of the payload was signed by the chip linked to the token id. - function isChipSignatureForToken(uint256 tokenId, bytes calldata payload, bytes calldata signature) - external - view - returns (bool); - - /// @notice Transfers the token into the message sender's wallet. - /// @param signatureFromChip An EIP-191 signature of (msgSender, blockhash), where blockhash is the block hash for blockNumberUsedInSig. - /// @param blockNumberUsedInSig The block number linked to the blockhash signed in signatureFromChip. Should be a recent block number. - /// @param useSafeTransferFrom Whether EIP-721's safeTransferFrom should be used in the implementation, instead of transferFrom. - /// - /// @dev The implementation should check that block number be reasonably recent to avoid replay attacks of stale signatures. - /// The implementation should also verify that the address signed in the signature matches msgSender. - /// If the address recovered from the signature matches a chip address that's bound to an existing token, the token should be transferred to msgSender. - /// If there is no existing token linked to the chip, the function should error. - function transferTokenWithChip( - bytes calldata signatureFromChip, - uint256 blockNumberUsedInSig, - bool useSafeTransferFrom - ) external; - - /// @notice Calls transferTokenWithChip as defined above, with useSafeTransferFrom set to false. - function transferTokenWithChip(bytes calldata signatureFromChip, uint256 blockNumberUsedInSig) external; - - /// @notice Emitted when a token is minted - event PBTMint(uint256 indexed tokenId, address indexed chipAddress); - - /// @notice Emitted when a token is mapped to a different chip. - /// Chip replacements may be useful in certain scenarios (e.g. chip defect). - event PBTChipRemapping(uint256 indexed tokenId, address indexed oldChipAddress, address indexed newChipAddress); -} - -``` - -To aid recognition that an [EIP-721](./eip-721.md) token implements physical binding via this EIP: upon calling [EIP-165](./eip-165.md)’s `function supportsInterface(bytes4 interfaceID) external view returns (bool)` with `interfaceID=0x4901df9f`, a contract implementing this EIP must return true. - -The mint interface is up to the implementation. The minted NFT's owner should be the owner of the physical chip (this authentication could be implemented using the signature scheme defined for `transferTokenWithChip`). - -## Rationale - -This solution's intent is to be the simplest possible path towards linking physical items to digital NFTs without a centralized authority. - -The interface includes a `transferTokenWithChip` function that's opinionated with respect to the signature scheme, in order to enable a downstream aggregator-like product that supports transfers of any NFTs that implement this EIP in the future. - -### Out of Scope - -The following are some peripheral problems that are intentionally not within the scope of this EIP: - -- trusting that a specific NFT collection's chip addresses actually map to physical chips embedded in items, instead of arbitrary EOAs -- ensuring that the chip does not deterioriate or get damaged -- ensuring that the chip stays attached to the physical item -- etc. - -Work is being done on these challenges in parallel. - -Mapping token ids to chip addresses is also out of scope. This can be done in multiple ways, e.g. by having the contract owner preset this mapping pre-mint, or by having a `(tokenId, chipAddress)` tuple passed into a mint function that's pre-signed by an address trusted by the contract, or by doing a lookup in a trusted registry, or by assigning token ids at mint time first come first served, etc. - -Additionally, it's possible for the owner of the physical item to transfer the NFT to a wallet owned by somebody else (by sending a chip signature to that other person for use). We still consider the NFT physical backed, as ownership management is tied to the physical item. This can be interpreted as the item's owner temporarily lending the item to somebody else, since (1) the item's owner must be involved for this to happen as the one signing with the chip, and (2) the item's owner can reclaim ownership of the NFT at any time. - -## Backwards Compatibility - -This proposal is backward compatible with [EIP-721](./eip-721.md) on an API level. As mentioned above, for the token to be physical-backed, the contract must use a account-bound implementation of [EIP-721](./eip-721.md) (all [EIP-721](./eip-721.md) functions that transfer must throw) so that transfers go through the new function introduced here, which requires a chip signature. - -## Reference Implementation - -The following is a snippet on how to recover a chip address from a signature. - -```solidity -import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; - -function getChipAddressFromChipSignature( - bytes calldata signatureFromChip, - uint256 blockNumberUsedInSig -) internal returns (TokenData memory) { - if (block.number <= blockNumberUsedInSig) { - revert InvalidBlockNumber(); - } - unchecked { - if (block.number - blockNumberUsedInSig > getMaxBlockhashValidWindow()) { - revert BlockNumberTooOld(); - } - } - bytes32 blockHash = blockhash(blockNumberUsedInSig); - bytes32 signedHash = keccak256(abi.encodePacked(_msgSender(), blockHash)) - .toEthSignedMessageHash(); - address chipAddr = signedHash.recover(signatureFromChip); -} - -``` - -## Security Considerations - -The [EIP-191](./eip-191.md) signature passed to `transferTokenWithChip` requires the function caller's address in its signed data so that the signature cannot be used in a replay attack. It also requires a recent blockhash so that a malicious chip owner cannot pre-generate signatures to use after a short time window (e.g. after the owner of the physical item changes). - -Additionally, the level of trust that one has for whether the token is physically-backed is dependent on the security of the physical chip, which is out of scope for this EIP as mentioned above. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5791.md diff --git a/EIPS/eip-5792.md b/EIPS/eip-5792.md index 10623574909157..d850cc1c2029dd 100644 --- a/EIPS/eip-5792.md +++ b/EIPS/eip-5792.md @@ -1,10 +1,11 @@ --- eip: 5792 -title: Wallet Function Call API -description: Adds JSON-RPC methods for sending multiple function calls from the user's wallet, and checking their status -author: Moody Salem (@moodysalem) +title: Wallet Call API +description: Adds JSON-RPC methods for sending multiple calls from the user's wallet, and checking their status +author: Moody Salem (@moodysalem), Lukas Rosario (@lukasrosario), Wilson Cusack (@wilsoncusack), Dror Tirosh (@drortirosh), Jake Moxey (@jxom), Derek Rein (@arein) discussions-to: https://ethereum-magicians.org/t/eip-5792-wallet-abstract-transaction-send-api/11374 -status: Draft +status: Last Call +last-call-deadline: 2024-06-26 type: Standards Track category: Interface created: 2022-10-17 @@ -12,258 +13,179 @@ created: 2022-10-17 ## Abstract -Defines new JSON-RPC methods for dapps to send batches of function calls from a user's wallet, as well as check -on the status of those calls. The new methods are more abstract in regard to the underlying transactions than the -existing transaction sending APIs to allow for differences between wallet implementations, e.g. -smart contract wallets utilizing [EIP-4337](./eip-4337.md) or EOA wallets that support bundled transactions -via [EIP-3074](./eip-3074.md). Dapps may use this more abstract interface to support different kinds of wallets without -additional effort, as well as provide a better UX for sending bundles of function calls ( -e.g. [EIP-20](./eip-20.md) `#approve` followed by a contract call). +Defines new JSON-RPC methods which enable apps to ask a wallet to process a batch of onchain write calls and to check on the status of those calls. +Applications can specify that these onchain calls be executed taking advantage of specific capabilities previously expressed by the wallet; an additional, a novel wallet RPC is defined to enable apps to query the wallet for those capabilities. ## Motivation -The current methods used to send transactions from the user wallet and check their status are `eth_sendTransaction` -and `eth_getTransactionReceipt`. - -These methods are keyed on the hash of the on-chain transaction, i.e. `eth_sendTransaction` returns an transaction hash -computed from the transaction parameters, and `eth_getTransactionReceipt` takes as one argument the transaction hash. -When the transaction hash changes, for example when a user speeds up the transaction in their wallet, the transaction -hash that the dapp is aware of becomes irrelevant. There is no communication delivered to the dapp of the change in -transaction hash, and no way to connect the old transaction hash to the new one, except by the user account and -transaction nonce. It is not trivial for the dapp to find all signed transactions for a given nonce and account, -especially for smart contract accounts which usually store the nonce in a contract storage slot. This happens more -frequently with smart contract wallets, which usually use a third party relaying service and automatically re-broadcast -transactions with higher gas prices. - -These methods also do not support sending multiple function calls related to a single action. For example, when swapping -on Uniswap, the user must often call [EIP-20](./eip-20.md) `#approve` before calling the Uniswap router contract to -swap. The dapp has to manage a complex multi-step asynchronous workflow to guide the user through sending a single swap. -The ideal UX would be to bundle the approve call with the swap call, and abstract the underlying approve function call -from the user. - -The current interface also does not work well for account abstracted wallets (e.g. [EIP-4337](./eip-4337.md) -or [EIP-3074](./eip-3074.md)), which often involve a relaying service to sign and broadcast the transaction that -triggers the function calls from the user's wallet. In these cases the actual transaction hash may not be known at the -time of user signing, but must still be returned by `eth_sendTransaction`. The transaction hash returned -by `eth_sendTransaction` in these cases is unlikely to be relevant to the transaction hash of the included transaction. -The existing interface also provides no way to delay the resolution of the transaction hash, since it is used as the key -of the transaction tracked by the dapp. Dapps often link to the block explorer for the returned transaction hash, but in -these cases the transaction hash is wrong and the link will not work. - -Dapps need a better interface for sending batches of function calls from the user's wallet so they can interact with -wallets without considering the differences between wallet implementations. These methods are backwards compatible with -existing EOA wallets. EOA wallets may send bundles of function calls as individual transactions. The goal of the new -interface is to be a more stable and flexible interface that enables a better user experience, while wallet -implementations evolve over time. +The current methods used to send transactions from the user wallet and check their status are `eth_sendTransaction` and `eth_getTransactionReceipt`. + +The current methods used to send transactions from the user wallet and check their status do not meet modern developer demands and cannot accommodate new transaction formats. Even the name–- `eth_sendTransaction`-– is an artifact of a time when nodes served as wallets. + +Today, developers want to send multiple calls batched together in a single RPC call, which many smart accounts can, in turn, execute atomically in a single transaction. Developers also want to make use of features afforded by new transaction formats, like paymasters in [ERC-4337](./eip-4337.md) transactions. `eth_sendTransaction` offers no way to do these things. + +In updating to a new set of `wallet_` RPCs, our main goals are to enforce a clean separation of wallet and app concerns, enable developers to make use of things like paymasters and batch transactions, and to create a clear way for more safely discoverable features to be added over time with minimal coordination. ## Specification -Three new JSON-RPC methods are added. Dapps may begin using these methods immediately, falling back -to `eth_sendTransaction` and `eth_getTransactionReceipt` when they are not available. +Four new JSON-RPC methods are added: three are for handling batches of onchain calls, and one is for querying support for wallet capabilities, such as to make better use of the three batching methods. +Apps may begin using these first three methods immediately, falling back to `eth_sendTransaction` and `eth_getTransactionReceipt` when they are not available. + +We also define one capability expression for use with the fourth method, which further enables a wallet to promise atomicity of the execution of calls passed and managed by the first three methods. + +### `wallet_sendCalls` -### `wallet_sendFunctionCallBundle` +Requests that a wallet submits a batch of calls. `from` and `chainId` are top-level properties rather than per-call properties because all calls should be sent from the same sender and on the same chain, identified by [EIP-155](./eip-155.md) integers expressed in hexadecimal notation. The items in the `calls` field are only those that are shared by all transaction types. Any other fields that a wallet may need to submit a transaction should be handled by the wallet. -Requests that the wallet deliver a group of function calls on-chain from the user's wallet. +The capabilities field is how an app can communicate with a wallet about capabilities a wallet supports. For example, this is where an app can specify a paymaster service URL from which an [ERC-4337](./eip-4337.md) wallet can request a `paymasterAndData` input for a user operation. The wallet: -- MUST send these calls in the order specified in the request. -- MUST send the calls on the request chain ID. -- MUST stop executing the calls if any call fails -- MUST NOT send any calls from the request if the user rejects the request -- MAY revert all calls if any call fails -- MAY send all the function calls as part of one transaction or multiple transactions, depending on wallet capability. -- MAY reject the request if the request chain ID does not match the currently selected chain ID. -- MAY reject the request if the `from` address does not match the enabled account. -- MAY reject the request if one or more calls in the bundle is expected to fail, when simulated sequentially - -#### `wallet_sendFunctionCallBundle` OpenRPC Specification - -```yaml -- name: wallet_sendFunctionCallBundle - summary: Sends a bundle of function calls from the user wallet - params: - - name: Function calls - required: true - schema: - type: object - title: Send function call bundle request - required: - - chainId - - from - - calls - properties: - chainId: - title: chainId - description: Chain ID that these calls should be sent on - $ref: '#/components/schemas/uint' - from: - title: from address - description: The address from which the function calls should be sent - $ref: '#/components/schemas/address' - calls: - title: calls to make - description: The calls that the wallet should make from the user's address - type: array - minItems: 1 - items: - title: function call - description: A single function call - type: object - required: - - gas - - data - to: - title: to address - description: The address that is being called - $ref: '#/components/schemas/address' - gas: - title: gas limit - description: The gas limit for this particular call - $ref: '#/components/schemas/uint' - value: - title: value - description: How much value to send with the call - $ref: '#/components/schemas/uint' - data: - title: data - description: The data to send with the function call - $ref: '#/components/schemas/bytes' - result: - name: Bundle identifier - schema: - type: string - maxLength: 66 + +* MUST send these calls in the order specified in the request +* MUST send the calls on the same chain identified by the request's `chainId` property +* MUST NOT send any calls from the request if the user rejects the request +* MAY revert all calls if any call fails +* MAY send all the function calls as part of one transaction or multiple transactions, depending on wallet capability +* SHOULD stop executing the calls if any call fails +* MAY reject the request if the request chain ID does not match the currently selected chain ID +* MAY reject the request if the from address does not match the enabled account +* MAY reject the request if one or more calls in the batch is expected to fail, when simulated sequentially + +#### `wallet_sendCalls` RPC Specification + +```typescript +type SendCallsParams = { + version: string; + chainId: `0x${string}`; // Hex chain id + from: `0x${string}`; + calls: { + to?: `0x${string}` | undefined; + data?: `0x${string}` | undefined; + value?: `0x${string}` | undefined; // Hex value + }[]; + capabilities?: Record | undefined; +}; + +type SendCallsResult = string; ``` -##### `wallet_sendFunctionCallBundle` Example Parameters +##### `wallet_sendCalls` Example Parameters ```json [ { - "chainId": 1, + "version": "1.0", + "chainId": "0x01", "from": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "calls": [ { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", - "gas": "0x76c0", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }, { "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", - "gas": "0xdefa", "value": "0x182183", "data": "0xfbadbaf01" } - ] + ], + "capabilities": { + // Illustrative + "paymasterService": { + "url": "https://..." + } + } } ] ``` -##### `wallet_sendFunctionCallBundle` Example Return Value +##### `wallet_sendCalls` Example Return Value -The identifier may be the hash of the call bundle, e.g.: +The identifier can be any string. The only requirement is that for a given session, users should be able to call `wallet_getCallsStatus` with this value and expect a call-batch status to be returned. ```json "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" ``` -The identifier may be a numeric identifier represented as a hex string, e.g.: +### `wallet_getCallsStatus` + +Returns the status of a call batch that was sent via `wallet_sendCalls`. The identifier of the transaction is the value returned from the `wallet_sendCalls` RPC. Note that this method only returns a subset of the fields that `eth_getTransactionReceipt` returns, excluding any fields that may differ across wallet implementations. + +* If a wallet does not execute multiple calls atomically (i.e. in multiple transactions), the receipts in the `receipts` field MUST be in order of the calls sent. +* If a wallet executes multiple calls atomically (i.e. in a single transaction), `wallet_getCallsStatus` MUST return a single receipt, corresponding to the transaction in which the calls were included. +* The `logs` in the receipt objects MUST only include logs relevant to the calls submitted using `wallet_sendCalls`. For example, in the case of a transaction submitted onchain by an [ERC-4337](./eip-4337.md) bundler, the logs must only include those relevant to the user operation constructed using the calls submitted via `wallet_sendCalls`. I.e. the logs should not include those from other unrelated user operations submitted in the same bundle. + +#### `wallet_getCallsStatus` RPC Specification + +```typescript +type GetCallsParams = string; + +type GetCallsResult = { + status: 'PENDING' | 'CONFIRMED'; + receipts?: { + logs: { + address: `0x${string}`; + data: `0x${string}`; + topics: `0x${string}`[]; + }[]; + status: `0x${string}`; // Hex 1 or 0 for success or failure, respectively + blockHash: `0x${string}`; + blockNumber: `0x${string}`; + gasUsed: `0x${string}`; + transactionHash: `0x${string}`; + }[]; +}; +``` + +##### `wallet_getCallsStatus` Example Parameters + +As with the return value of `wallet_sendCalls`, the batch identifier may be any string. ```json -"0x01" +[ + "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" +] ``` -The identifier may be a base64 encoded string: +##### `wallet_getCallsStatus` Example Return Value ```json -"aGVsbG8gd29ybGQ=" +{ + "status": "CONFIRMED", + "receipts": [ + { + "logs": [ + { + "address": "0xa922b54716264130634d6ff183747a8ead91a40b", + "topics": [ + "0x5a2a90727cc9d000dd060b1132a5c977c9702bb3a52afe360c9c22f0e9451a68" + ], + "data": "0xabcd" + } + ], + "status": "0x1", + "blockHash": "0xf19bbafd9fd0124ec110b848e8de4ab4f62bf60c189524e54213285e7f540d4a", + "blockNumber": "0xabcd", + "gasUsed": "0xdef", + "transactionHash": "0x9b7bb827c2e5e3c1a0a44dc53e573aa0b3af3bd1f9f5ed03071b100bb039eaff" + } + ] +} ``` -### `wallet_getBundleStatus` - -Returns the status of a bundle that was sent via `wallet_sendFunctionCallBundle`. The identifier of the bundle is the -value returned from the `wallet_sendFunctionCallBundle` RPC. Note this method only returns a subset of fields -that `eth_getTransactionReceipt` returns, excluding any fields that may differ across wallet implementations. - -#### `wallet_getBundleStatus` OpenRPC Specification - -```yaml -- name: wallet_getBundleStatus - summary: Sends a bundle of function calls from the user wallet - params: - - name: Bundle identifier - required: true - schema: - type: string - title: Bundle identifier - result: - name: Call status - schema: - type: object - properties: - calls: - type: array - items: - title: call status - description: Status of the call at the given index - type: object - status: - title: The current status of the call - enum: - - CONFIRMED - - PENDING - receipt: - type: object - required: - - success - - blockHash - - blockNumber - - blockTimestamp - - gasUsed - - transactionHash - properties: - logs: - type: array - items: - title: Log object - type: object - properties: - address: - $ref: '#/components/schemas/address' - data: - title: data - $ref: '#/components/schemas/bytes' - topics: - title: topics - type: array - items: - $ref: '#/components/schemas/bytes32' - success: - type: boolean - title: Whether the call succeeded - blockHash: - title: The hash of the block in which the call was included - $ref: '#/components/schemas/bytes32' - blockNumber: - title: The number of the block in which the call was included - $ref: '#/components/schemas/uint' - blockTimestamp: - title: The timestamp of the block in which the call was included - $ref: '#/components/schemas/uint' - gasUsed: - title: How much gas the call actually used - $ref: '#/components/schemas/uint' - transactionHash: - title: The hash of the transaction in which the call was made - $ref: '#/components/schemas/bytes32' -``` +### `wallet_showCallsStatus` + +Requests that a wallet shows information about a given call bundle that was sent with `wallet_sendCalls`. Note that this method does not return anything. -##### `wallet_getBundleStatus` Example Parameters +#### `wallet_showCallsStatus` RPC Specification -As with the return value of `wallet_sendFunctionCallBundle`, the bundle identifier may be any string of max length `66`. +```typescript +type ShowCallsParams = string; // Call bundle identifier returned by wallet_sendCalls +``` + +##### `wallet_showCallsStatus` Example Parameters -It may be the hash of the call bundle: +This method accepts a call bundle identifier returned by a `wallet_sendCalls` call. ```json [ @@ -271,120 +193,122 @@ It may be the hash of the call bundle: ] ``` -It may contain a numeric identifier as a hex string: +### `wallet_getCapabilities` -```json -[ - "0x01" -] +This RPC allows an application to request capabilities from a wallet (e.g. batch transactions, paymaster communication), without distinct discovery and permission requests. For more on the difference between requesting capabilities and discoverying features, see the ["Privacy Considerations" section](#privacy-considerations). + +This method SHOULD return an error if the user has not already authorized a connection between the application and the requested address. + +We expect the community to align on the definition of additional capabilities in separate ERCs over time. + +Note that in addition to, or instead of, querying the wallet directly for capabilities, the same capability objects MAY be exposed out-of-band, such as in a `sessionProperty.capabilities` object persisted in a CAIP-25-conformant wallet provider interface, or in a well-known location (such as a URL derived from an [EIP-6963](./eip-6963.md) `rdns` identifier). Provider abstractions MAY also cache capabilities from previous requests or otherwise inject them from out-of-band to facilitate better user experience. +If any of these supplemental expressions of capabilities are contradicted by capabilities expressed in live wallet RPC responses, these latter values SHOULD be taken as the canonical and current expression of capabilities. + +#### `wallet_getCapabilities` RPC Specification + +Capabilities are returned in key/value pairs, with the key naming a capability and a value conforming to a shape defined for that name, in an object keyed to the relevant [EIP-155](./eip-155.md) `chainId` expressed in hexadecimal notation. +Capabilities are nested in per-chain objects because wallets may support different capabilities across multiple chains authorized in a given session. + +```typescript +type GetCapabilitiesParams = [`0x${string}`]; // Wallet address + +type GetCapabilitiesResult = Record<`0x${string}`, >; // Hex chain id ``` -It may be a base64 encoded string: +##### `wallet_getCapabilities` Example Parameters ```json -[ - "aGVsbG8gd29ybGQ=" -] +["0xd46e8dd67c5d32be8058bb8eb970870f07244567"] ``` -##### `wallet_getBundleStatus` Example Return Value +##### `wallet_getCapabilities` Example Return Value + +The capabilities below are for illustrative purposes. ```json { - "calls": [ - { - "status": "CONFIRMED", - "receipt": { - "logs": [ - { - "address": "0xa922b54716264130634d6ff183747a8ead91a40b", - "topics": [ - "0x5a2a90727cc9d000dd060b1132a5c977c9702bb3a52afe360c9c22f0e9451a68" - ], - "data": "0xabcd" - } - ], - "success": true, - "blockHash": "0xf19bbafd9fd0124ec110b848e8de4ab4f62bf60c189524e54213285e7f540d4a", - "blockNumber": "0xabcd", - "blockTimestamp": "0xabcdef", - "gasUsed": "0xdef", - "transactionHash": "0x9b7bb827c2e5e3c1a0a44dc53e573aa0b3af3bd1f9f5ed03071b100bb039eaff" - } + "0x2105": { + "paymasterService": { + "supported": true }, - { - "status": "PENDING" + "sessionKeys": { + "supported": true } - ] + }, + "0x14A34": { + "paymasterService": { + "supported": true + } + } } ``` -### `wallet_showBundleStatus` - -Requests that the wallet present UI showing the status of the given bundle. This allows dapps to delegate the -display of the function call status to the wallet, which can most accurately render the current status of the bundle. -This RPC is intended to replace the typical user experience of a dapp linking to a block explorer for a given -transaction hash. - -- The wallet MAY ignore the request, for example if the wallet is busy with other user actions. -- The wallet MAY direct the user to a third party block explorer for more information. - -#### `wallet_showBundleStatus` OpenRPC Specification - -```yaml -- name: wallet_showBundleStatus - summary: Requests that the wallet show the status of the bundle with the given identifier - params: - - name: Bundle identifier - required: true - schema: - type: string - maxLength: 66 - result: - name: Empty - schema: - type: "null" -``` +### `atomicBatch` Capability -##### `wallet_showBundleStatus` Example Parameters +Like the illustrative examples given above and other capabilities to be defined in future EIPs, the capability to execute calls delivered via the above-defined methods in a single transaction can be attested by the wallet in boolean form. -```json -[ - "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331" -] +If a wallet has affirmatively expressed this `atomicBatch` capability to a calling application, it MUST submit calls submitted with `wallet_sendCalls` as part of a single transaction. + +#### `atomicBatch` Capability Specification + +```typescript +type AtomicBatchCapability = { + supported: true; +}; ``` -##### `wallet_showBundleStatus` Example Return Value +The only valid JSON-RPC values for this capability's only member, `supported`, are `true` or `false`; if a returned value for `supported` is typed as a string or number, it SHOULD be considered malformed. + +For each chain on which a wallet can submit multiple calls atomically, the wallet SHOULD include an `atomicBatch` capability with a `supported` field equal to `true`. + +#### `wallet_getCapabilities` Example Return Value including `atomicBatch` ```json -null +{ + "0x2105": { + "atomicBatch": { + "supported": true + }, + }, + "0x14A34": { + "atomicBatch": { + "supported": true + } + } +} ``` ## Rationale -Account abstracted wallets, either via [EIP-3074](./eip-3074.md) or [EIP-4337](./eip-4337.md) or other specifications, -have more capabilities than regular EOA accounts. +### On Naming + +We considered modifying `eth_sendTransaction` to add support for these new capabilities, but the method is ultimately an artifact of when nodes were used to sign transactions. We decided it is better to move forward with `wallet_`-namespaced methods that better describe what they are used for. -The `eth_sendTransaction` and `eth_getTransactionReceipt` methods limit the quality of in-dapp transaction -construction and status tracking. It's possible for dapps to stop tracking transactions altogether and -leave that UX to the wallet, but it is a better UX when dapps provide updates on transactions constructed within the -dapp, because dapps will always have more context than the wallets on the action that a set of calls is -meant to perform. For example, an approve and swap might both be related to a trade that a user is attempting to make. -Without these APIs, it's necessary for a dapp to represent those actions as individual transactions. +We also debated whether the methods should be called `wallet_sendTransaction`, `wallet_sendCalls`, or something else. We ultimately landed on `wallet_sendCalls` because in the case of EOA wallets the `wallet_send*` method might send more than one transaction. Similarly, we decided against `wallet_sendTransactions` because in the case of other wallet implementations (e.g. [ERC-4337](./eip-4337.md)) multiple calls could result in a single transaction. + +### Call Execution Atomicity + +The `wallet_sendCalls` method accepts an array of `calls`. However, this proposal does not require that these calls be executed as part of a single transaction. It enables EOA wallets to accept multiple calls as well over the same interface. That said, we expect that in some cases app developers might want to submit batched calls if and only if they will be executed atomically. This would reduce the number of error cases an app developer would need to handle, while still contributing to the unification over time of interfaces across wallets types. + +We initially proposed that multiple calls must be executed atomically, but after some debate we ultimately decided this was too opinionated. Instead, we are including a specification for an `atomicBatch` capability. This allows for EOA wallets to accept multiple calls and still gives developers the option to only submit batched calls if they are executed atomically. + +### Call Gas Limit + +Our initial proposal included an optional `gas` field for each call in the `calls` field accepted by the `walletSendCalls` method. However, we realized this could be misleading because in the case of [ERC-4337](./eip-4337.md) wallets you cannot specify a gas limit per call, only a single gas limit for all calls in the user operation. We then proposed a single `gas` value that would apply to all of the calls. This works for [ERC-4337](./eip-4337.md) wallets, but not for EOA wallets. When we decided that EOA wallets should be able to handle multiple calls, the common `gas` field became untenable across use cases and we removed it altogether. ## Backwards Compatibility -Wallets that do not support the following methods should return error responses to the new JSON-RPC methods. -Dapps MAY attempt to send the same bundle of calls via `eth_sendTransaction` when they receive a not implemented -call, or otherwise indicate to the user that their wallet is not supported. +Wallets that do not support the methods defined here SHOULD return error responses when these new JSON-RPC methods are called. Apps MAY attempt to send the same batch of calls serially via `eth_sendTransaction` when a call to these methods fails for lack of wallet support, or they MAY indicate to the user that their wallet is not supported and the request was not processed. ## Security Considerations -Dapp developers MUST treat each call in a bundle as if the call was an independent transaction. -In other words, there may be additional untrusted transactions between any of the calls in a bundle. -The calls in the bundle may also be included in separate, non-contiguous blocks. There is no constraint over how long -it will take a bundle to be included. Dapps must encode deadlines in the smart contract calls as they do today. -Dapp developers MUST NOT assume that all calls are sent in a single transaction. +App developers MUST treat each call in a batch as if the call were an independent transaction. In other words, there may be additional untrusted transactions between any of the calls in a batch. The calls in the batch MAY also be included in separate, non-contiguous blocks. There is no constraint over how long it will take all the calls in a batch to be included. Apps MUST encode deadlines and timeout behaviors in the smart contract calls, just as they do today for transactions, including ones otherwise bundled. Unless a wallet has indicated affirmatively to the application that it can submit batched calls atomically via capability declarations, app developers MUST NOT assume that all calls will be sent in a single transaction. + +### Privacy Considerations + +Progressive authorization and progressive consent paradigms are important to modern user experience, as well as to preserving the anonymity of user agents. To protect these patterns from the cross-incentives of feature-discovery that enables better user experiences, capability semantics are used and the difference between lack of feature support and lack of feature permission explicitly occluded in the design of the `wallet_` RPC for querying capabilities. + +Furthermore, wallets are recommended to avoid exposing capabilities to untrusted callers or to more callers than necessary, as this may allow their "user-agent" (i.e. client software) to be "fingerprinted" or probabilistically identified, which combined with other deanonymization vectors inherent to the web platform could contribute to the deanonymization of the individual user or to the deanonymization of all users of a given client in aggregate. Similarly, applications over-querying capabilities or incentivizing capability oversharing (including third-party capability oversharing) is an anti-pattern to be avoided in the implementation of capability exchanges serving to discover features. ## Copyright diff --git a/EIPS/eip-5793.md b/EIPS/eip-5793.md index 8064056f526ab0..b87f67c59a81f8 100644 --- a/EIPS/eip-5793.md +++ b/EIPS/eip-5793.md @@ -4,7 +4,7 @@ title: eth/68 - Add tx type to tx announcement description: Adds the transaction type and transaction size to tx announcement messages in the wire protocol author: Marius van der Wijden (@MariusVanDerWijden) discussions-to: https://ethereum-magicians.org/t/eip-5793-eth-68-add-transaction-type-to-tx-announcement/11364 -status: Review +status: Final type: Standards Track category: Networking created: 2022-10-18 @@ -28,12 +28,21 @@ The added metadata fields will also enable future - upgradeless - protocol tweak Modify the `NewPooledTransactionHashes (0x08)` message: * **(eth/67)**: `[hash_0: B_32, hash_1: B_32, ...]` -* **(eth/68)**: `[[type_0: B_1, type_1: B_1, ...], [size_0: B_4, size_1: B_4, ...], [hash_0: B_32, hash_1: B_32, ...]]` +* **(eth/68)**: `[types: B, [size_0: P, size_1: P, ...], [hash_0: B_32, hash_1: B_32, ...]]` + +The new `types` element refers to the transaction types of the announced hashes. Note the +transaction types are packed as a 'byte array' instead of a list. + +The `size_0`, `size_1` etc. elements refer to the transaction sizes of the announced hashes. ## Rationale This change will make the `eth` protocol future-proof for new transaction types that might not be relevant for all nodes. It gives the receiving node better control over the data it fetches from the peer as well as allow throttling the download of specific types. +The `types` message element is a byte array because early implementations of this EIP +erroneously implemented it that way. It was later decided to keep this behavior in order +to minimize work. + ## Backwards Compatibility This EIP changes the `eth` protocol and requires rolling out a new version, `eth/68`. Supporting multiple versions of a wire protocol is possible. Rolling out a new version does not break older clients immediately, since they can keep using protocol version `eth/67`. diff --git a/EIPS/eip-5805.md b/EIPS/eip-5805.md index 024df6d7579e90..492bb63793e05d 100644 --- a/EIPS/eip-5805.md +++ b/EIPS/eip-5805.md @@ -1,442 +1,7 @@ --- eip: 5805 -title: Voting with delegation -description: An interface for voting weight tracking, with delegation support -author: Hadrien Croubois (@Amxx), Francisco Giordano (@frangio) -discussions-to: https://ethereum-magicians.org/t/eip-5805-voting-with-delegation/11407 -status: Draft -type: Standards Track category: ERC -created: 2022-07-04 -requires: 712 +status: Moved --- -## Abstract - -Many DAOs (decentralized autonomous organizations) rely on tokens to represent one's voting power. In order to perform this task effectively, the token contracts need to include specific mechanisms such as checkpoints and delegation. The existing implementations are not standardized. This EIP proposes to standardize the way votes are delegated from one account to another, and the way current and past votes are tracked and queried. The corresponding behavior is compatible with many token types, including but not limited to [EIP-20](./eip-20.md) and [EIP-721](./eip-721.md). This EIP also considers the diversity of time tracking functions, allowing the voting tokens (and any contract associated with it) to track the votes based on `block.number`, `block.timestamp`, or any other non-decreasing function. - -## Motivation - -Beyond simple monetary transactions, decentralized autonomous organizations are arguably one of the most important use cases of blockchain and smart contract technologies. Today, many communities are organized around a governance contract that allows users to vote. Among these communities, some represent voting power using transferable tokens ([EIP-20](./eip-20.md), [EIP-721](./eip-721.md), other). In this context, the more tokens one owns, the more voting power one has. Governor contracts, such as Compound's `GovernorBravo`, read from these "voting token" contracts to get the voting power of the users. - -Unfortunately, simply using the `balanceOf(address)` function present in most token standards is not good enough: - -- The values are not checkpointed, so a user can vote, transfer its tokens to a new account, and vote again with the same tokens. -- A user cannot delegate their voting power to someone else without transferring full ownership of the tokens. - -These constraints have led to the emergence of voting tokens with delegation that contain the following logic: - -- Users can delegate the voting power of their tokens to themselves or a third party. This creates a distinction between balance and voting weight. -- The voting weights of accounts are checkpointed, allowing lookups for past values at different points in time. -- The balances are not checkpointed. - -This EIP is proposing to standardize the interface and behavior of these voting tokens. - -Additionally, the existing (non-standardized) implementations are limited to `block.number` based checkpoints. This choice causes many issues in a multichain environment, where some chains (particularly L2s) have an inconsistent or unpredictable time between blocks. This EIP also addresses this issue by allowing the voting token to use any time tracking function it wants, and exposing it so that other contracts (such as a Governor) can stay consistent with the token checkpoints. - -## Specification - -Following pre-existing (but not-standardized) implementation, the EIP proposes the following mechanism. - -Each user account (address) can delegate to an account of its choice. This can be itself, someone else, or no one (represented by `address(0)`). Assets held by the user cannot express their voting power unless they are delegated. - -When a "delegator" delegates its tokens voting power to a "delegatee", its balance is added to the voting power of the delegatee. If the delegator changes its delegation, the voting power is subtracted from the old delegatee's voting power and added to the new delegate's voting power. The voting power of each account is tracked through time so that it is possible to query its value in the past. With tokens being delegated to at most one delegate at a given point in time, double voting is prevented. - -Whenever tokens are transferred from one account to another, the associated voting power should be deducted from the sender's delegate and added to the receiver's delegate. - -Tokens that are delegated to `address(0)` should not be tracked. This allows users to optimize the gas cost of their token transfers by skipping the checkpoint update for their delegate. - -To accommodate different types of chains, we want the voting checkpoint system to support different forms of time tracking. On the Ethereum mainnet, using block numbers provides backward compatibility with applications that historically use it. On the other hand, using timestamps provides better semantics for end users, and accommodates use cases where the duration is expressed in seconds. Other monotonic functions could also be deemed relevant by developers based on the characteristics of future applications and blockchains. - -Both timestamps, block numbers, and other possible modes use the same external interfaces. This allows transparent binding of third-party contracts, such as governor systems, to the vote tracking built into the voting contracts. For this to be effective, the voting contracts must, in addition to all the vote-tracking functions, expose the current value used for time-tracking. - -### Methods - -#### clock - -This function returns the current timepoint. It could be `block.timestamp`, `block.number` (or any other **non-decreasing** function) depending on the mode the contract is operating on. - -- If operating using **block number**, then this function SHOULD be implemented. -- If operating using **timestamp**, then this function MUST be implemented. -- If operating using any other mode, then this function MUST be implemented. - -This function is thus optional, and its absence should be considered as a marker of the contract operating using block number. (This makes this EIP compatible with pre-existing voting contracts). - -```yaml -- name: clock - type: function - stateMutability: view - inputs: [] - outputs: - - name: timepoint - type: uint48 -``` - -### CLOCK_MODE - -This function returns a string describing the clock the contract is operating on. - -- If operating using **block number**: - - If the block numbers are those of the `NUMBER` opcode (`0x43`), then this function SHOULD be implemented and return `mode=blocknumber&from=default`. - - If it is any other block number, then this function MUST be implemented and return `mode=blocknumber&from=`, where `` is a CAIP-2 Blockchain ID such as `eip155:1`. -- If operating using **timestamp**, then this function MUST be implemented and return `mode=timestamp`. -- If operating using any other mode, then this function MUST be implemented and return a unique identifier for the encoded `mode` field. - -This function is thus optional, and its absence should be considered as a marker of the contract operating using block numbers, which can be clearly identified from the absence of this function. (This makes this EIP compatible with pre-existing voting contracts). - -Note that when operating using **block number**, the `clock()` is expected to return the value given by the `NUMBER` opcode (`0x43`). In some cases this can be the block number of another chain (in arbitrum, opcode `0x43` returns the block number of the last recorded operation on the parent chain). A contract can use `from=default` to specify that the block number used is the one provided by the `NUMBER` opcode (`0x43`). If a more explicit description is needed, CAIP-2 blockchain id should be used, as shown in the above. - -The return string MUST be formatted like a URL query string (a.k.a. `application/x-www-form-urlencoded`). This allows easy decoding in standard JavaScript with `new URLSearchParams(CLOCK_MODE)`. - -```yaml -- name: CLOCK_MODE - type: function - stateMutability: view - inputs: [] - outputs: - - name: descriptor - type: string -``` - -#### getVotes - -This function returns the current voting weight of an account. This corresponds to all the voting power delegated to it at the moment this function is called. - -As tokens delegated to `address(0)` should not be counted/snapshotted, `getVotes(0)` SHOULD always return `0`. - -This function MUST be implemented - -```yaml -- name: getVotes - type: function - stateMutability: view - inputs: - - name: account - type: address - outputs: - - name: votingWeight - type: uint256 -``` - -#### getPastVotes - -This function returns the historical voting weight of an account. This corresponds to all the voting power delegated to it at a specific timepoint. The timepoint parameter MUST match the operating mode of the contract. This function SHOULD only serve past checkpoints, which SHOULD be immutable. - -- Calling this function with a timepoint that is greater or equal to `clock()` SHOULD revert. -- Calling this function with a timepoint strictly smaller than `clock()` SHOULD NOT revert. -- For any integer that is strictly smaller than `clock()`, the value returned by `getPastVotes` SHOULD be constant. This means that for any call to this function that returns a value, re-executing the same call (at any time in the future) SHOULD return the same value. - -As tokens delegated to `address(0)` should not be counted/snapshotted, `getPastVotes(0,x)` SHOULD always return `0` (for all values of `x`). - -This function MUST be implemented - -```yaml -- name: getPastVotes - type: function - stateMutability: view - inputs: - - name: account - type: address - - name: timepoint - type: uint256 - outputs: - - name: votingWeight - type: uint256 -``` - -#### delegates - -This function returns the address to which the voting power of an account is currently delegated. - -Note that if the delegate is `address(0)` then the voting power SHOULD NOT be checkpointed, and it should not be possible to vote with it. - -This function MUST be implemented - -```yaml -- name: delegates - type: function - stateMutability: view - inputs: - - name: account - type: address - outputs: - - name: delegatee - type: address -``` - -#### delegate - -This function changes the caller's delegate, updating the vote delegation in the meantime. - -This function MUST be implemented - -```yaml -- name: delegate - type: function - stateMutability: nonpayable - inputs: - - name: delegatee - type: address - outputs: [] -``` - -#### delegateBySig - -This function changes an account's delegate using a signature, updating the vote delegation in the meantime. - -This function MUST be implemented - -```yaml -- name: delegateBySig - type: function - stateMutability: nonpayable - inputs: - - name: delegatee - type: address - - name: nonce - type: uint256 - - name: expiry - type: uint256 - - name: v - type: uint8 - - name: r - type: bytes32 - - name: s - type: bytes32 - outputs: [] -``` - -This signature should follow the [EIP-712](./eip-712.md) format: - -A call to `delegateBySig(delegatee, nonce, expiry, v, r, s)` changes the signer's delegate to `delegatee`, increment the signer's nonce by 1, and emits a corresponding `DelegateChanged` event, and possibly `DelegateVotesChanged` events for the old and the new delegate accounts, if and only if the following conditions are met: - - -- The current timestamp is less than or equal to `expiry`. -- `nonces(signer)` (before the state update) is equal to `nonce`. - -If any of these conditions are not met, the `delegateBySig` call must revert. This translates to the following solidity code: - -```sol -require(expiry <= block.timestamp) -bytes signer = ecrecover( - keccak256(abi.encodePacked( - hex"1901", - DOMAIN_SEPARATOR, - keccak256(abi.encode( - keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"), - delegatee, - nonce, - expiry)), - v, r, s) -require(signer != address(0)); -require(nounces[signer] == nonce); -// increment nonce -// set delegation of `signer` to `delegatee` -``` - -where `DOMAIN_SEPARATOR` is defined according to [EIP-712](./eip-712.md). The `DOMAIN_SEPARATOR` should be unique to the contract and chain to prevent replay attacks from other domains, -and satisfy the requirements of EIP-712, but is otherwise unconstrained. - -A common choice for `DOMAIN_SEPARATOR` is: - -```solidity -DOMAIN_SEPARATOR = keccak256( - abi.encode( - keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), - keccak256(bytes(name)), - keccak256(bytes(version)), - chainid, - address(this) -)); -``` - -In other words, the message is the EIP-712 typed structure: - -```js -{ - "types": { - "EIP712Domain": [ - { - "name": "name", - "type": "string" - }, - { - "name": "version", - "type": "string" - }, - { - "name": "chainId", - "type": "uint256" - }, - { - "name": "verifyingContract", - "type": "address" - } - ], - "Delegation": [{ - "name": "delegatee", - "type": "address" - }, - { - "name": "nonce", - "type": "uint256" - }, - { - "name": "expiry", - "type": "uint256" - } - ], - "primaryType": "Permit", - "domain": { - "name": contractName, - "version": version, - "chainId": chainid, - "verifyingContract": contractAddress - }, - "message": { - "delegatee": delegatee, - "nonce": nonce, - "expiry": expiry - } -}} -``` - -Note that nowhere in this definition do we refer to `msg.sender`. The caller of the `delegateBySig` function can be any address. - -When this function is successfully executed, the delegator's nonce MUST be incremented to prevent replay attacks. - -#### nonces - -This function returns the current nonce for a given account. - -Signed delegations (see `delegateBySig`) are only accepted if the nonce used in the EIP-712 signature matches the return of this function. This value of `nonce(delegator)` should be incremented whenever a call to `delegateBySig` is performed on behalf of `delegator`. - -This function MUST be implemented - -```yaml -- name: nonces - type: function - stateMutability: view - inputs: - - name: account - type: delegator - outputs: - - name: nonce - type: uint256 -``` - -### Events - -#### DelegateChanged - -`delegator` changes the delegation of its assets from `fromDelegate` to `toDelegate`. - -MUST be emitted when the delegate for an account is modified by `delegate(address)` or `delegateBySig(address,uint256,uint256,uint8,bytes32,bytes32)`. - -```yaml -- name: DelegateChanged - type: event - inputs: - - name: delegator - indexed: true - type: address - - name: fromDelegate - indexed: true - type: address - - name: toDelegate - indexed: true - type: address -``` - -#### DelegateVotesChanged - -`delegate` available voting power changes from `previousBalance` to `newBalance`. - -This MUST be emitted when: - -- an account (that holds more than 0 assets) updates its delegation from or to `delegate`, -- an asset transfer from or to an account that is delegated to `delegate`. - -```yaml -- name: DelegateVotesChanged - type: event - inputs: - - name: delegate - indexed: true - type: address - - name: previousBalance - indexed: false - type: uint256 - - name: newBalance - indexed: false - type: uint256 -``` - -### Solidity interface - -```sol -interface IERC5805 { - event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); - event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); - - function clock() external view returns (uint48); - function CLOCK_MODE() external view returns (string); - - function getVotes(address account) external view returns (uint256); - function getPastVotes(address account, uint256 timepoint) external view returns (uint256); - function delegates(address account) external view returns (address); - function nonces(address owner) public view virtual returns (uint256) - - function delegate(address delegatee) external; - function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; -} -``` - -### Expected properties - -- The `clock()` function MUST be non-decreasing. -- For all timepoints `t < clock()`, `getVotes(address(0))` and `getPastVotes(address(0), t)` SHOULD return 0. -- For all accounts `a != 0`, `getVotes(a)` SHOULD be the sum of the "balances" of all the accounts that delegate to `a`. -- For all accounts `a != 0` and all timestamp `t < clock()`, `getPastVotes(a, t)` SHOULD be the sum of the "balances" of all the accounts that delegated to `a` when `clock()` overtook `t`. -- For all accounts `a`, `getPastVotes(a, t)` MUST be constant after `t < clock()` is reached. -- For all accounts `a`, the action of changing the delegate from `b` to `c` MUST not increase the current voting power of `b` (`getVotes(b)`) and MUST not decrease the current voting power of `c` (`getVotes(c)`). - -## Rationale - -Delegation allows token holders to trust a delegate with their vote while keeping full custody of their token. This means that only a small-ish number of delegates need to pay gas for voting. This leads to better representation of small token holders by allowing their votes to be cast without requiring them to pay expensive gas fees. Users can take over their voting power at any point, and delegate it to someone else, or to themselves. - -The use of checkpoints prevents double voting. Votes, for example in the context of a governance proposal, should rely on a snapshot defined by a timepoint. Only tokens delegated at that timepoint can be used for voting. This means any token transfer performed after the snapshot will not affect the voting power of the sender/receiver's delegate. This also means that in order to vote, someone must acquire tokens and delegate them before the snapshot is taken. Governors can, and do, include a delay between the proposal is submitted and the snapshot is taken so that users can take the necessary actions (change their delegation, buy more tokens, ...). - -`clock` returns `uint48` as it is largely sufficient for storing realistic values. In timestamp mode, `uint48` will be enough until the year 8921556. Even in block number mode, with 10,000 blocks per second, it would be enough until the year 2861. Using a type smaller than uint256 allows some storage packing of timepoints with other associated values. Greatly reducing the cost of writing and reading from storage. Depending on the evolution of the blockchain (particularly layer twos), `uint32` might cause issues fairly quickly. On the other hand, anything bigger than `uint48` is overkill. - -While timestamps produced by `clock` are represented as `uint48`, `getPastVotes`'s timepoint argument is `uint256` for backward compatibility. Any timepoint `>=2**48` passed to `getPastVotes` SHOULD cause the function to revert, as it would be a lookup in the future. - -`delegateBySig` is necessary to offer a gasless workflow to token holders that do not want to pay gas for voting. - -The `nonces` mapping is given for replay protection. - -EIP-712 typed messages are included because of their widespread adoption in many wallet providers. - -## Backwards Compatibility - -Compound and OpenZeppelin already provide implementations of voting tokens. The delegation-related methods are shared between the two implementations and this EIP. For the vote lookup, this EIP uses OpenZeppelin's implementation (with return type uint256) as Compound's implementation causes significant restrictions of the acceptable values (return type is uint96). - -Both implementations use `block.number` for their checkpoints and do not implement the `clock()` method, which is compatible with this EIP. - -Existing governors, that are currently compatible with OpenZeppelin's implementation will be compatible with the "block number mode" of this EIP. - -## Security Considerations - -Before doing a lookup, one should check the return value of `clock()` and make sure that the parameters of the lookup are consistent. Performing a lookup using a timestamp argument on a contract that uses block numbers will very likely cause a revert. On the other end, performing a lookup using a block number argument on a contract that uses timestamps will likely return 0. - -Though the signer of a `Delegation` may have a certain party in mind to submit their transaction, another party can always front-run this transaction and call `delegateBySig` before the intended party. The result is the same for the `Delegation` signer, however. - -Since the ecrecover precompile fails silently and just returns the zero address as `signer` when given malformed messages, it is important to ensure `signer != address(0)` to avoid `delegateBySig` from delegating "zombie funds" belonging to the zero address. - -Signed `Delegation` messages are censorable. The relaying party can always choose to not submit the `Delegation` after having received it, withholding the option to submit it. The `expiry` parameter is one mitigation to this. If the signing party holds ETH they can also just submit the `Delegation` themselves, which can render previously signed `Delegation`s invalid. - -If the `DOMAIN_SEPARATOR` contains the `chainId` and is defined at contract deployment instead of reconstructed for every signature, there is a risk of possible replay attacks between chains in the event of a future chain split. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5805.md diff --git a/EIPS/eip-5806.md b/EIPS/eip-5806.md index 4f2fd5133bbd4e..bd6fef9d8d921c 100644 --- a/EIPS/eip-5806.md +++ b/EIPS/eip-5806.md @@ -1,7 +1,7 @@ --- eip: 5806 title: Delegate transaction -description: Adds a new transaction type that allows a EOAs to execute arbitrary code through delegation +description: Adds a new transaction type that allows EOAs to execute arbitrary code through delegation author: Hadrien Croubois (@Amxx) discussions-to: https://ethereum-magicians.org/t/eip-5806-delegate-transaction/11409 status: Draft @@ -17,20 +17,26 @@ This EIP adds a new transaction type that allows EOAs to execute arbitrary code ## Motivation -Account abstraction has been extensively discussed but the path toward mainstream adoption is still unclear. Some approaches, such as [EIP-4337](./eip-4337.md) hope to improve the usability of smart wallets, without addressing the issue of smart wallet support by applications. [EIP-3074](./eip-3074.md) proposes another approach that favors existing EOAs but comes with replay risks. +EOA are the most widely used type of account, yet their ability to perform operations is limited to deploying contracts and sending "call" transactions. It is currently not possible for an EOA to execute arbitrary code, which greatly limits the interactions users can have with the blockchain. Account abstraction has been extensively discussed but the path toward mainstream adoption is still unclear. Some approaches, such as [ERC-4337](./eip-4337.md) hope to improve the usability of smart wallets, without addressing the issue of smart wallet support by applications. -This EIP proposes a simpler approach that addresses some of the objectives of account abstraction for EOAs with minimal change over the EVM. By allowing EOAs to perform delegate calls to a contract (similarly to how contracts can delegate calls to other contracts using [EIP-7](./eip-7.md)), EOAs will be able to have more control over what operations they want to execute. +While smart contract wallets have a lot to offer in terms of UX, it is unlikely that all users will migrate any time soon because of the associated cost and the fact that some EOAs have custody of non-transferable assets. -Performing a delegate call to a multicall contract (such as the one deployed to `0xcA11bde05977b3631167028862bE2a173976CA11`), EOAs would be able to batch multiple transactions into a single one, while being the `msg.sender` of all the sub calls. Other unforeseen logic could be implemented in smart contracts and used by EOA. This includes emitting events, using storage under the EOA's account, or even deploying contracts using `create2`. +This EIP proposes an approach to allow the execution of arbitrary code by EOAs, with minimal change over the EVM, and using the same security model users are used to. By allowing EOAs to perform delegate calls to a contract (similarly to how contracts can delegate calls to other contracts using [EIP-7](./eip-7.md)), EOAs will be able to have more control over what operations they want to execute. This proposal's goal is NOT to provide an account abstraction primitive. + +By performing a delegate call to a multicall contract (such as the one deployed to `0xcA11bde05977b3631167028862bE2a173976CA11`), EOAs would be able to batch multiple transactions into a single one (being the `msg.sender` of all the sub calls). This would provide a better UX for users that want to interact with protocols (no need for multiple transactions, with variable gas prices and 21k gas overhead) and increase the security of such interactions (by avoiding unsafe token approvals being exploited between an `approval` and the following `transferFrom`). + +Other unforeseen logic could be implemented in smart contracts and used by EOA. This includes emitting events. This EIP doesn't aim to replace other account abstraction proposals. It hopes to be an easy-to-implement alternative that would significantly improve the user experience of EOA owners in the near future. ## Specification -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. ### Parameters + - `FORK_BLKNUM` = `TBD` -- `TX_TYPE` = TBD, > 0x02 ([EIP-1559](./eip-1559.md)) +- `TX_TYPE` = TBD, > 0x03 ([EIP-4844](./eip-4844.md)) As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` = `TX_TYPE(TBD)`. @@ -42,13 +48,25 @@ The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, data, access_list, signature_y_parity, signature_r, signature_s]) ``` -The definitions of all fields share the same meaning with [EIP-1559](./eip-1559.md). Note the absence of `amount` field in this transaction! +The definitions of all fields follow the same semantics as [EIP-1559](./eip-1559.md). Note the absence of `amount` field in this transaction! -The `signature_y_parity, signature_r, signature_s` elements of this transaction represent a secp256k1 signature over `keccak256(0x02 || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, data, access_list]))`. +The `to` field deviates slightly from the semantics with the exception that it MUST NOT be nil and therefore must always represent a 20-byte address. This means that delegate transactions cannot have the form of a create transaction. + +The `signature_y_parity, signature_r, signature_s` elements of this transaction represent a secp256k1 signature over `keccak256(TX_TYPE || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, data, access_list]))`. The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. -The execution of this new transaction type is equivalent to the delegate call mechanism introduced in [EIP-7](./eip-7.md), but performed by an EOA (the transaction sender). This implies that the code present at `destination`, if any, should be executed in the context of the sender. As a consequence, such a transaction can set and read storage under the EOA. It can also emit an event from the EOA. +The execution of this new transaction type is equivalent to the delegate call mechanism introduced in [EIP-7](./eip-7.md), but performed by an EOA (the transaction sender). This implies that the code present at `destination`, if any, should be executed in the context of the sender. As a consequence, such a transaction emit an event from the EOA or use `Create2` with the address of the EOA as the creator. This transaction includes some restrictions though. + +### Opcode restriction + +For security reasons, some opcodes should not be executed in the context of an EOA: + +- `SSTORE` (0x55): Setting storage under an EOA breaks many assumptions. In particular storage set through a delegate transaction could cause issues if the accounts later "migrates" using [EIP-7377](./eip-7377.md) or similar. Additionally, storage may be a source of conflicts if a single EOA uses delegate transactions to target codes that interpret the storage layout under this account differently. For all these reasons, EOA should be forbidden from performing `SSTORE` in the context of a delegate transaction. If a delegate transaction performs a CALL, the target of the call is free to manipulate storage normally. + +- `CREATE` (0xF0), `CREATE2` (0xF5) and `SELFDESTRUCT` (0xFF): There may be an expectation that transactions from a given sender should have consecutive nonces. This assumption would be broken if an EOA was able to execute one or multiple operations that alter the sender account's nonce. Consequently, EOA performing a delegate transaction should not be able to use the `CREATE`, `CREATE2` or `SELFDESTRUCT` opcodes. If a delegate transaction performs a CALL, the target of the call is free to create contracts normally. + +Any attempts to make execute one of these restricted operations will instead throw an exception. ## Rationale @@ -58,13 +76,18 @@ This EIP would drastically expand the ability of EOAs to interact with smart con ## Backwards Compatibility -No known backward compatibility issues thanks to the transaction envelope ([EIP-2718](./eip-2718.md)) +No known backward compatibility issues thanks to the transaction envelope ([EIP-2718](./eip-2718.md)). + +Due to the inclusion logic and the gas cost being similar to type 2 transactions, it should be possible to include this new transaction type in the same mempool. ## Security Considerations -The nonce mechanism, already used in other transaction types, prevents replay attacks. This makes this approach safer, but also less powerful than [EIP-3074](./eip-3074.md). +The nonce mechanism, already used in other transaction types, prevents replay attacks. Similar to existing transaction types, a delegate transaction can be cancelled by replacing it with a dummy transaction that pays more fees. + +Since the object signed by the wallet is a transaction and not a signature that could potentially be processed in many ways (as is the case for [EIP-3074](./eip-3074.md)), the risks associated with the miss-use of the signature are reduced. A wallet could simulate the execution of this delegate transaction and provide good guarantees that the operation that the user signs won't be manipulated. -Contracts being called through this mechanism can execute any operation on behalf of the signer. Signers should be extremely careful signing this transaction (just like any other transaction). +Contracts being called through this mechanism can execute any operation on behalf of the signer. As with other transaction types, signers should be extremely careful when signing a delegate transaction. ## Copyright + Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-5827.md b/EIPS/eip-5827.md index 5147c14d3a736f..43cdfb58b9795c 100644 --- a/EIPS/eip-5827.md +++ b/EIPS/eip-5827.md @@ -1,236 +1,7 @@ --- eip: 5827 -title: Auto-renewable allowance extension -description: Extension to enable automatic renewals on allowance approvals -author: zlace (@zlace0x), zhongfu (@zhongfu), edison0xyz (@edison0xyz) -discussions-to: https://ethereum-magicians.org/t/eip-5827-auto-renewable-allowance-extension/10392 -status: Draft -type: Standards Track category: ERC -created: 2022-10-22 -requires: 20, 165 +status: Moved --- -## Abstract - -This extension adds a renewable allowance mechanism to [EIP-20](./eip-20.md) allowances, in which a `recoveryRate` defines the amount of token per second that the allowance regains towards the initial maximum approval `amount`. - -## Motivation - -Currently, EIP-20 tokens support allowances, with which token owners can allow a spender to spend a certain amount of tokens on their behalf. However, this is not ideal in circumstances involving recurring payments (e.g. subscriptions, salaries, recurring direct-cost-averaging purchases). - -Many existing DApps circumvent this limitation by requesting that users grant a large or unlimited allowance. This presents a security risk as malicious DApps can drain users' accounts up to the allowance granted, and users may not be aware of the implications of granting allowances. - -An auto-renewable allowance enables many traditional financial concepts like credit and debit limits. An account owner can specify a spending limit, and limit the amount charged to the account based on an allowance that recovers over time. - - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -```solidity -pragma solidity ^0.8.0; - -interface IERC5827 /* is ERC20, ERC165 */ { - /* - * Note: the ERC-165 identifier for this interface is 0x93cd7af6. - * 0x93cd7af6 === - * bytes4(keccak256('approveRenewable(address,uint256,uint256)')) ^ - * bytes4(keccak256('renewableAllowance(address,address)')) ^ - * bytes4(keccak256('approve(address,uint256)') ^ - * bytes4(keccak256('transferFrom(address,address,uint256)') ^ - * bytes4(keccak256('allowance(address,address)') ^ - */ - - /** - * @notice Thrown when the available allowance is less than the transfer amount. - * @param available allowance available; 0 if unset - */ - error InsufficientRenewableAllowance(uint256 available); - - /** - * @notice Emitted when any allowance is set. - * @dev MUST be emitted even if a non-renewable allowance is set; if so, the - * @dev `_recoveryRate` MUST be 0. - * @param _owner owner of token - * @param _spender allowed spender of token - * @param _value initial and maximum allowance granted to spender - * @param _recoveryRate recovery amount per second - */ - event RenewableApproval( - address indexed _owner, - address indexed _spender, - uint256 _value, - uint256 _recoveryRate - ); - - /** - * @notice Grants an allowance of `_value` to `_spender` initially, which recovers over time - * @notice at a rate of `_recoveryRate` up to a limit of `_value`. - * @dev SHOULD cause `allowance(address _owner, address _spender)` to return `_value`, - * @dev SHOULD throw when `_recoveryRate` is larger than `_value`, and MUST emit a - * @dev `RenewableApproval` event. - * @param _spender allowed spender of token - * @param _value initial and maximum allowance granted to spender - * @param _recoveryRate recovery amount per second - */ - function approveRenewable( - address _spender, - uint256 _value, - uint256 _recoveryRate - ) external returns (bool success); - - /** - * @notice Returns approved max amount and recovery rate of allowance granted to `_spender` - * @notice by `_owner`. - * @dev `amount` MUST also be the initial approval amount when a non-renewable allowance - * @dev has been granted, e.g. with `approve(address _spender, uint256 _value)`. - * @param _owner owner of token - * @param _spender allowed spender of token - * @return amount initial and maximum allowance granted to spender - * @return recoveryRate recovery amount per second - */ - function renewableAllowance(address _owner, address _spender) - external - view - returns (uint256 amount, uint256 recoveryRate); - - /// Overridden ERC-20 functions - - /** - * @notice Grants a (non-increasing) allowance of _value to _spender and clears any existing - * @notice renewable allowance. - * @dev MUST clear set `_recoveryRate` to 0 on the corresponding renewable allowance, if - * @dev any. - * @param _spender allowed spender of token - * @param _value allowance granted to spender - */ - function approve(address _spender, uint256 _value) - external - returns (bool success); - - /** - * @notice Moves `amount` tokens from `from` to `to` using the caller's allowance. - * @dev When deducting `amount` from the caller's allowance, the allowance amount used - * @dev SHOULD include the amount recovered since the last transfer, but MUST NOT exceed - * @dev the maximum allowed amount returned by `renewableAllowance(address _owner, address - * @dev _spender)`. - * @dev SHOULD also throw `InsufficientRenewableAllowance` when the allowance is - * @dev insufficient. - * @param from token owner address - * @param to token recipient - * @param amount amount of token to transfer - */ - function transferFrom( - address from, - address to, - uint256 amount - ) external returns (bool); - - /** - * @notice Returns amount currently spendable by `_spender`. - * @dev The amount returned MUST be as of `block.timestamp`, if a renewable allowance - * @dev for the `_owner` and `_spender` is present. - * @param _owner owner of token - * @param _spender allowed spender of token - * @return remaining allowance at the current point in time - */ - function allowance(address _owner, address _spender) - external - view - returns (uint256 remaining); -} -``` - -Base method `approve(address _spender, uint256 _value)` MUST set `recoveryRate` to 0. - -Both `allowance()` and `transferFrom()` MUST be updated to include allowance recovery logic. - -`approveRenewable(address _spender, uint256 _value, uint256 _recoveryRate)` MUST set both the initial allowance amount and the maximum allowance limit (to which the allowance can recover) to `_value`. - -`supportsInterface(0x93cd7af6)` MUST return `true`. - -### Additional interfaces - -**Token Proxy** - -Existing EIP-20 tokens can delegate allowance enforcement to a proxy contract that implements this specification. An additional query function exists to get the underlying EIP-20 token. - -```solidity -interface IERC5827Proxy /* is IERC5827 */ { - - /* - * Note: the ERC-165 identifier for this interface is 0xc55dae63. - * 0xc55dae63 === - * bytes4(keccak256('baseToken()') - */ - - /** - * @notice Get the underlying base token being proxied. - * @return baseToken address of the base token - */ - function baseToken() external view returns (address); -} -``` - -The `transfer()` function on the proxy MUST NOT emit the `Transfer` event (as the underlying token already does so). - -**Automatic Expiration** - -```solidity -interface IERC5827Expirable /* is IERC5827 */ { - /* - * Note: the ERC-165 identifier for this interface is 0x46c5b619. - * 0x46c5b619 === - * bytes4(keccak256('approveRenewable(address,uint256,uint256,uint64)')) ^ - * bytes4(keccak256('renewableAllowance(address,address)')) ^ - */ - - /** - * @notice Grants an allowance of `_value` to `_spender` initially, which recovers over time - * @notice at a rate of `_recoveryRate` up to a limit of `_value` and expires at - * @notice `_expiration`. - * @dev SHOULD throw when `_recoveryRate` is larger than `_value`, and MUST emit - * @dev `RenewableApproval` event. - * @param _spender allowed spender of token - * @param _value initial allowance granted to spender - * @param _recoveryRate recovery amount per second - * @param _expiration Unix time (in seconds) at which the allowance expires - */ - function approveRenewable( - address _spender, - uint256 _value, - uint256 _recoveryRate, - uint64 _expiration - ) external returns (bool success); - - /** - * @notice Returns approved max amount, recovery rate, and expiration timestamp. - * @return amount initial and maximum allowance granted to spender - * @return recoveryRate recovery amount per second - * @return expiration Unix time (in seconds) at which the allowance expires - */ - function renewableAllowance(address _owner, address _spender) - external - view - returns (uint256 amount, uint256 recoveryRate, uint64 expiration); -} -``` - -## Rationale - -Renewable allowances can be implemented with discrete resets per time cycle. However, a continuous `recoveryRate` allows for more flexible use cases not bound by reset cycles and can be implemented with simpler logic. - -## Backwards Compatibility - -Existing EIP-20 token contracts can delegate allowance enforcement to a proxy contract that implements this specification. - -## Security Considerations - -This EIP introduces a stricter set of constraints compared to EIP-20 with unlimited allowances. However, when `_recoveryRate` is set to a large value, large amounts can still be transferred over multiple transactions. - -Applications that are not [EIP-5827](./eip-5827.md)-aware may erroneously infer that the value returned by `allowance(address _owner, address _spender)` or included in `Approval` events is the maximum amount of tokens that `_spender` can spend from `_owner`. This may not be the case, such as when a renewable allowance is granted to `_spender` by `_owner`. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5827.md diff --git a/EIPS/eip-5850.md b/EIPS/eip-5850.md index 09eed5af674e2c..195495e589ae45 100644 --- a/EIPS/eip-5850.md +++ b/EIPS/eip-5850.md @@ -1,77 +1,7 @@ --- eip: 5850 -title: Complex Numbers stored in `bytes32` types -description: Store real and imaginary parts of complex numbers in the least significant and most significant 16 bytes respectively of a `bytes32` type. -author: Paul Edge (@genkifs) -discussions-to: https://ethereum-magicians.org/t/eip-5850-store-real-and-imaginary-parts-of-complex-numbers-in-the-least-significant-and-most-significant-16-bytes-respectively-of-a-bytes32-type/11532 -status: Draft -type: Standards Track category: ERC -created: 2022-10-29 +status: Moved --- - -## Abstract -This EIP proposes a natural way for complex numbers to be stored in and retrieved from the `bytes32` data-type. It splits the storage space exactly in half and, most importantly, assigns the real number part to the least significant 16 bytes and the imaginary number part to the most significant 16 bytes. - -## Motivation - -Complex numbers are an essential tool for many mathematical and scientific calculations. For example, Fourier Transforms, Characteristic functions, AC Circuits and Navier-Stokes equations all require the concept. - -Complex numbers can be represented in many different forms (polynomial, cartesian, polar, exponential). The EIP creates a standard that can accomodate cartesian, polar and exponential formats with example code given for the Cartesian representation, where a complex number is just the pair of real numbers which gives the real and imaginary co-ordinates of the complex number. Equal storage capacity is assigned to both components and the order they appear is explicitly defined. - -Packing complex numbers into a single `bytes32` data object halves storage costs and creates a more natural code object that can be passed around the solidity ecosystem. Existing code may not need to be rewritten for complex numbers. For example, mappings by `bytes32` are common and indexing in the 2D complex plane may improve code legibility. - -Decimal numbers, either fix or floating, are not yet fully supported by Solidity so enforcing similar standards for complex versions is premature. It can be suggested that fixed point methods such as prb-math be used with 18 decimal places, or floating point methods like abdk. However, it should be noted that this EIP supports any decimal number representation so long as it fits inside the 16 bytes space. - -## Specification - -A complex number would be defined as `bytes32` and a cartesian representation would be initalized with the `cnNew` function and converted back with `RealIm`, both given below. - -To create the complex number one would use - -```solidity -function cnNew(int128 _Real, int128 _Imag) public pure returns (bytes32){ - bytes32 Imag32 = bytes16(uint128(_Imag)); - bytes32 Real32 = bytes16(uint128(_Real)); - return (Real32>> 128) | Imag32; -} -``` - -and to convert back - -```solidity -function RealIm(bytes32 _cn) public pure returns (int128 Real, int128 Imag){ - bytes16[2] memory tmp = [bytes16(0), 0]; - assembly { - mstore(tmp, _cn) - mstore(add(tmp, 16), _cn) - } - Imag=int128(uint128(tmp[0])); - Real=int128(uint128(tmp[1])); -} -``` - -## Rationale - -An EIP is required as this proposal defines a complex numbers storage/type standard for multiple apps to use. - -This EIP proposes to package both the real and imaginary within one existing data type, `bytes32`. This allows compact storage without the need for structures and facilitates easy library implementations. The `bytes32` would remain available for existing, non-complex number uses. -Only the split and position of the real & imaginary parts is defined in this EIP. Manipulation of complex numbers (addition, multiplication etc.), number of decimal places and other such topics are left for other EIP discussions. This keeps this EIP more focused and therfore more likely to succeed. - -Defining real numbers in the 16 least-significant bytes allows direct conversion from `uint128` to `bytes32` for positive integers less than 2**127. -Direct conversion back from `bytes32` -> `uint` -> `int` are not recommended as the complex number may contain imaginary parts and/or the real part may be negative. It is better to always use `RealIm` for separating the complex part. - -Libraries for complex number manipulation can be implemented with the `Using Complex for bytes32` syntax where `Complex` would be the name of the library. - -## Backwards Compatibility - -There is no impact on other uses of the `bytes32` datatype. - -## Security Considerations - -If complex numbers are manipulated in `bytes32` form then overflow checks must be performed manually during the manipulation. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5850.md diff --git a/EIPS/eip-5851.md b/EIPS/eip-5851.md index a886e1442f7203..d79d24892ead03 100644 --- a/EIPS/eip-5851.md +++ b/EIPS/eip-5851.md @@ -1,265 +1,7 @@ --- eip: 5851 -title: On-Chain Verifiable Credentials -description: Interface for contracts that manage verifiable claims and identifiers as Soulbound tokens. -author: Yu Liu (@yuliu-debond), Junyi Zhong (@Jooeys) -discussions-to: https://ethereum-magicians.org/t/eip-5815-kyc-certification-issuer-and-verifier-standard/11513 -status: Draft -type: Standards Track category: ERC -created: 2022-10-18 -requires: 721, 1155, 1167, 1967, 3475 +status: Moved --- -## Abstract -This proposal introduces a method of certifying that a particular address meets a claim, and a method of verifying those certifications using on-chain metadata. Claims are assertions or statements made about a subject having certain properties that may be met conditions (for example: `age >= 18`), and are certified by issuers using a Soundbound Token (SBT). - -## Motivation - -On-chain issuance of verifiable attestations are essential for use-case like: - -- Avoiding Sybil attacks with one person one vote -- Participation in certain events with credentials -- Compliance to government financial regulations etc. - -We are proposing a standard claims structure for Decentralized Identity (DID) issuers and verifier entities to create smart contracts in order to provide on-chain commitment of the off-chain verification process, and once the given address is associated with the given attestation of the identity verification off-chain, the issuers can then onboard other verifiers (i.e. governance, financial institution, non-profit organization, web3 related cooperation) to define the condition of the ownership of the user in order to reduce the technical barriers and overhead of current implementations. - -The motivation behind this proposal is to create a standard for verifier and issuer smart contracts to communicate with each other in a more efficient way. This will reduce the cost of KYC processes, and provide the possibility for on-chain KYC checks. By creating a standard for communication between verifiers and issuers, it will create an ecosystem in which users can be sure their data is secure and private. This will ultimately lead to more efficient KYC processes and help create a more trustful environment for users. It will also help to ensure that all verifier and issuer smart contracts are up-to-date with the most recent KYC regulations. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -### Definitions - -- Zero-Knowledge Proof (ZKP): a cryptographic device that can convince a verifier that an assertion is correct without revealing all of the inputs to the assertion. - -- Soulbound Token (SBT): A non-fungible and non-transferrable token that is used for defining the identity of the users. - -- SBT Certificate: An SBT that represents the ownership of ID signatures corresponding to the claims defined in `function standardClaim()`. - -- Verifiable Credential (VC): A collection of claims made by an issuer. These are temper evident credentials that allow the holders to prove that they posses certain characteristics (for example, passport verification, constraints like value of tokens in your wallet, etc) as demanded by the verifier entity. - -- Claim: An assertion that the DID Holder must fulfill to be verified. - -- Holder: The entity that stores the claim, such as a digital identity provider or a DID registry. The holder is responsible for validating the claim and providing verifiable evidence of the claim. - -- Claimer: The party making a claim, such as in an identity verification process. - -- Issuer: The entity that creates a verifiable credential from claims about one or more subjects to a holder. Example issuers include governments, corporations, non-profit organizations, trade associations, and individuals. - -- Verifier: An entity that validates data provided by an issuer of verifiable credentials, determining its accuracy, origin, currency and trustworthiness. - - - -### Metadata Standard - -Claims MUST be exposed in the following structures: - -#### 1. Metadata information - -Each claim requirement MUST be exposed using the following structure: - -```solidity - /** Metadata - * - * @param title defines the name of the claim field - * @param _type is the type of the data (bool,string,address,bytes,..) - * @param description additional information about claim details. - */ - struct Metadata { - string title; - string _type; - string description; - } -``` - -#### 2. Values Information - -This following structure will be used to define the actual claim information, based on the description of the `Metadata` structure, the structure is the same as `Values` structure of [EIP-3475](./eip-3475.md). - -```solidity - struct Values{ - string stringValue; - uint uintValue; - address addressValue; - bool boolValue; - } -``` - -#### 3. Claim structure - -Claims (eg. `age >= 18`, jurisdiction in allowlist, etc.) are represented by one or many instances of the `Claim` structure below: - -```solidity - /** Claims - * - * Claims structure consist of the conditions and value that holder claims to associate and verifier has to validate them. - * @notice the below given parameters are for reference purposes only, developers can optimize the fields that are needed to be represented on-chain by using schemes like TLV, encoding into base64 etc. - * @dev structure that defines the parameters for specific claims of the SBT certificate - * @notice this structure is used for the verification process, it contains the metadata, logic and expectation - * @notice logic can represent either the enum format for defining the different operations, or they can be logic operators (stored in form of ASCII figure based on unicode standard). like e.g: -("⊄" = U+2284, "⊂" = U+2282, "<" = U+003C , "<=" = U + 2265,"==" = U + 003D, "!="U + 2260, ">=" = U + 2265,">" = U + 2262). - */ - struct Claim { - Metadata metadata; - string logic; - Values expectation; - - } -``` - -description of some logic functions that can be used are as follows: - -| Symbol | Description | -|--------|--------------| -| ⊄ | does not belong to the set of values (or range) defined by the corresponding `Values` | -| ⊂ | condition that the parameter belongs to one of values defined by the `Values` | -| < | condition that the parameter is greater than value defined by the `Values` | -| == | condition that the parameter is strictly equal to the value defined by the `Values` structure | - -#### Claim Example - -```json -{ - "title":"age", - "type":"unit", - "description":"age of the person based on the birth date on the legal document", - "logic":">=", - "value":"18" -} -``` - -Defines the condition encoded for the index 1 (i.e the holder must be equal or more than 18 years old). - -### Interface specification - -#### Verifier - -```solidity - - /// @notice getter function to validate if the address `claimer` is the holder of the claim defined by the tokenId `SBTID` - /// @dev it MUST be defining the conditional operator (logic explained below) to allow the application to convert it into code logic - /// @dev logic given here MUST be the conditiaonl operator, MUST be one of ("⊄", "⊂", "<", "<=", "==", "!=", ">=", ">") - /// @param claimer is the EOA address that wants to validate the SBT issued to it by the issuer. - /// @param SBTID is the Id of the SBT that user is the claimer. - /// @return true if the assertion is valid, else false - /** - example ifVerified(0xfoo, 1) => true will mean that 0xfoo is the holder of the SBT identity token defined by tokenId of the given collection. - */ - function ifVerified(address claimer, uint256 SBTID) external view returns (bool); -``` - -#### Issuer - -```solidity - - /// @notice getter function to fetch the on-chain identification logic for the given identity holder. - /// @dev it MUST not be defined for address(0). - /// @param SBTID is the Id of the SBT that the user is the claimer. - /// @return the struct array of all the descriptions of condition metadata that is defined by the administrator for the given KYC provider. - /** - ex: standardClaim(1) --> { - { "title":"age", - "type": "uint", - "description": "age of the person based on the birth date on the legal document", - }, - "logic": ">=", - "value":"18" - } - Defines the condition encoded for the identity index 1, defining the identity condition that holder must be equal or more than 18 years old. - **/ - - function standardClaim(uint256 SBTID) external view returns (Claim[] memory); - - /// @notice function for setting the claim requirement logic (defined by Claims metadata) details for the given identity token defined by SBTID. - /// @dev it should only be called by the admin address. - /// @param SBTID is the Id of the SBT-based identity certificate for which the admin wants to define the Claims. - /// @param `claims` is the struct array of all the descriptions of condition metadata that is defined by the administrator. check metadata section for more information. - /** - example: changeStandardClaim(1, { "title":"age", - "type": "uint", - "description": "age of the person based on the birth date on the legal document", - }, - "logic": ">=", - "value":"18" - }); - will correspond to the functionality that admin needs to adjust the standard claim for the identification SBT with tokenId = 1, based on the conditions described in the Claims array struct details. - **/ - - function changeStandardClaim(uint256 SBTID, Claim[] memory _claims) external returns (bool); - - /// @notice function which uses the ZKProof protocol to validate the identity based on the given - /// @dev it should only be called by the admin address. - /// @param SBTID is the Id of the SBT-based identity certificate for which admin wants to define the Claims. - /// @param claimer is the address that needs to be proven as the owner of the SBT defined by the tokenID. - /** - example: certify(0xA....., 10) means that admin assigns the DID badge with id 10 to the address defined by the `0xA....` wallet. - */ - function certify(address claimer, uint256 SBTID) external returns (bool); - - /// @notice function which uses the ZKProof protocol to validate the identity based on the given - /// @dev it should only be called by the admin address. - /// @param SBTID is the Id of the SBT-based identity certificate for which the admin wants to define the Claims. - /// @param claimer is the address that needs to be proven as the owner of the SBT defined by the tokenID. - /* eg: revoke(0xfoo,1): means that KYC admin revokes the SBT certificate number 1 for the address '0xfoo'. */ - function revoke(address certifying, uint256 SBTID) external returns (bool); - -``` - -#### Events - -```solidity - /** - * standardChanged - * @notice standardChanged MUST be triggered when claims are changed by the admin. - * @dev standardChanged MUST also be triggered for the creation of a new SBTID. - e.g : emit StandardChanged(1, Claims(Metadata('age', 'uint', 'age of the person based on the birth date on the legal document' ), ">=", "18"); - is emitted when the Claim condition is changed which allows the certificate holder to call the functions with the modifier, claims that the holder must be equal or more than 18 years old. - */ - event StandardChanged(uint256 SBTID, Claim[] _claims); - - /** - * certified - * @notice certified MUST be triggered when the SBT certificate is given to the certifying address. - * eg: Certified(0xfoo,2); means that wallet holder address `0xfoo` is certified to hold a certificate issued with id 2, and thus can satisfy all the conditions defined by the required interface. - */ - event Certified(address claimer, uint256 SBTID); - - /** - * revoked - * @notice revoked MUST be triggered when the SBT certificate is revoked. - * eg: Revoked( 0xfoo,1); means that entity user 0xfoo has been revoked to all the function access defined by the SBT ID 1. - */ - event Revoked(address claimer, uint256 SBTID); -} -``` - -## Rationale - -TBD - -## Backwards Compatibility - -- This EIP is backward compliant for the contracts that keep intact the metadata structure of previous issued SBT's with their ID and claim requirement details. - - For e.g if the DeFI provider (using the modifiers to validate the ownership of required SBT by owner) wants the admin to change the logic of verification or remove certain claim structure, the previous holders of the certificates will be affected by these changes. - -## Test Cases - -Test cases for the minimal reference implementation can be found [here](../assets/eip-5851/contracts/test.sol) for using transaction verification regarding whether the users hold the tokens or not. Use Remix IDE to compile and test the contracts. - -## Reference Implementation - -The [interface](../assets/eip-5851/contracts/interfaces/IERC5851.sol) is divided into two separate implementations: - -- [EIP-5851 Verifier](../assets/eip-5851/contracts/ERC5851Verifier.sol) is a simple modifier that needs to be imported by functions that are to be only called by holders of the SBT certificates. Then the modifier will call the issuer contract to verifiy if the claimer has the SBT certifcate in question. - -- [EIP-5851 Issuer](../assets/eip-5851/contracts/ERC5851Issuer.sol) is an example of an identity certificate that can be assigned by a KYC controller contract. This is a full implementation of the standard interface. - -## Security Considerations - -1. Implementation of functional interfaces for creating KYC on SBT (i.e `changeStandardClaim()`, `certify()` and `revoke()`) are dependent on the admin role. Thus the developer must insure security of admin role and rotation of this role to the entity entrusted by the KYC attestation service provider and DeFI protocols that are using this attestation service. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5851.md diff --git a/EIPS/eip-5883.md b/EIPS/eip-5883.md new file mode 100644 index 00000000000000..668ae28d1d40d8 --- /dev/null +++ b/EIPS/eip-5883.md @@ -0,0 +1,7 @@ +--- +eip: 5883 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5883.md diff --git a/EIPS/eip-5902.md b/EIPS/eip-5902.md index e9ffe7073892d5..fa02fc96c8426b 100644 --- a/EIPS/eip-5902.md +++ b/EIPS/eip-5902.md @@ -1,641 +1,7 @@ --- eip: 5902 -title: Smart Contract Event Hooks -description: Format that allows contracts to semi-autonoumously respond to events emitted by other contracts -author: Simon Brown (@orbmis) -discussions-to: https://ethereum-magicians.org/t/idea-smart-contract-event-hooks-standard/11503 -status: Draft -type: Standards Track category: ERC -created: 2022-11-09 -requires: 712 +status: Moved --- -## Abstract - -This EIP proposes a standard for creating "hooks" that allow a smart contract function to be called automatically in response to a trigger fired by another contract, by using a public relayer network as a messaging bus. - -While there are many similar solutions in existence already, this proposal describes a simple yet powerful primitive that can be employed within many applications in an open, permissionless and decentralized manner. - -It relies on two interfaces, one for a publisher contract and one for a subscriber contract. The publisher contract emits events that are picked up by "relayers", who are independent entities that subscribe to hook events on publisher contracts, and call a function on the respective subscriber contracts whenever a hook event is fired by the publisher contracts. When a relayer calls the respective subscriber's contract with the details of the hook event emitted by the publisher contract, they are paid a fee by the subscriber. Both the publisher and subscriber contracts are registered in a central registry smart contract that relayers can use to discover hooks. - -## Motivation - -There exists a number of use cases that require some off-chain party to monitor the chain and respond to on-chain events by broadcasting a transaction. Such cases usually require some off-chain process to run alongside an Ethereum node, in order to subscribe to events via a web socket connection, and perform some logic in response to an event, by broadcasting a respective transaction to the network. For some use-cases, this may require an Ethereum node and an open websocket connection to some long-running process that may only be used infrequently, resulting in a sub-optimal use of resources. - -This proposal would allow for a smart contract to contain the logic it needs to respond to events without having to store that logic in some off-chain process. The smart contract can subscribe to events fired by other smart contracts and would only execute the required logic when it is needed. This method would suit any contract logic that does not require off-chain computation, but requires an off-chain process to monitor chain state in order to call one of its functions in response. - -Firing hooks from publisher smart contracts still requires some off-chain impetus. To put it another way, somebody has to pull the trigger on the publisher contract, by submitting a transaction to the publisher contract in order to emit the hook event. This is how it works today, and this proposal doesn't change that. Where it does offer an improvement, is that each subscriber no longer needs its own dedicated off-chain process for monitoring and responding to these events. Instead, a single incentivized relayer can subscribe to many different events on behalf of multiple subscriber contracts. - -Thanks to innovations such as web3 webhooks from Moralis, web3 actions from Tenderly, or hal.xyz, creating a relayer is easier than ever. - -Examples of use cases that would benefit from this scheme include: - -### Collateralised lending protocols - -For example, Maker uses the "medianizer" smart contract which maintains a whitelist of price feed contracts which are allowed to post price updates. Every time a new price update is received, the median of all feed prices is re-computed and the medianized value is updated. In this case, the medianizer smart contract could fire a hook event that would allow subscriber contracts to decide to re-collateralize their positions. - -### Automated market makers - -AMM liquidity pools could fire a hook event whenever liquidity is added or removed. This could allow a subscriber smart contracts to add or remove liquidity once the total pool liquidity reaches a certain point. - -AMMs can fire a hook whenever there is a trade within a trading pair, emitting the time-weighted-price-oracle update via an hook event. Subscribers can use this to create an automated Limit-Order-Book contract to buy/sell tokens once an asset's spot price breaches a pre-specified threshold. - -### DAO voting - -Hook events can be emitted by a DAO governance contract to signal that a proposal has been published, voted on, carried or vetoed, and would allow any subscriber contract to automatically respond accordingly. - -### Scheduled function calls - -A scheduler service can be created whereby a subscriber can register for a scheduled funtion call, this could be done using unix cron format and the service can fire events from a smart contract on separate threads. Subscriber contracts can subscriber to the respective threads in order to subscribe to certain schedules (e.g. daily, weekly, hourly etc.), and could even register customer cron schedules. - -### Coordination via Delegation - -Hook event payloads can contain any arbitrary data, this means you can use things like the Delegatable framework to sign off-chain delegations which can faciliate a chain of authorized entities to publish valid Hook events. You can also use things like BLS threshold signatures. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -### Registering a Publisher - -Both the publisher and subscriber contracts **MUST** register in a specific register contract, similarly to how smart contracts register an interface in the [EIP-1820](./eip-1820.md) contract. - -To register a hook in a publisher contract, the `registerHook` function **MUST** be called on the registry contract. The parameters that need to be supplied are: - - - `address` - The publisher contract address, in the form of an ethereum address - - `bytes32` - The public key associated with the hook events - - `uint256` - The thread id that the hooks events will reference (a single contract can fire hook events with any number of threads, subscribers can choose which threads to subscribe to) - -When the `registerHook` function is called on the registry contract, the registry contract **MUST** make a downstream call to the publisher contract address, by calling the publisher contract's `verifyEventHookRegistration` function, with the same arguments as passed to the `registerHook` function on the registry contract. The `verifyEventHookRegistration` function in the publisher contract **MUST** return `true` to indicate that the contract will allow itself to be added to the registry as a publisher. The registry contract **MUST** emit a `HookRegistered` event to indicate that a new publisher contract has been added. - -### Updating a Publisher - -Publishers may want to revoke or update public keys associated with a hook event, or indeed remove support for a hook event completely. The registry contract **MUST** implement the `updatePublisher` function to allow for an existing publisher contract to be updated in the registry. The registry contract **MUST** emit a `PublisherUpdated` event to indicate that the publisher contract was updated. - -### Registering a Subscriber - -To register a subscriber to a hook, the `registerSubscriber` function **MUST** be called on the registry contract with the following parameters: - - - `address` - The publisher contract address - - `bytes32` - The subscriber contract address - - `uint256` - The thread id to subscribe to - - `uint256` - the fee that the subscriber is willing to pay to get updates - - `uint256` - the maximum gas that the subscriber will allow for updates, to prevent griefing attacks - - `uint256` - the maximum gas price that the subscriber is willing to rebate, or 0 to indicate no rebates, in which case it assumed the relay fee covers gas fees - - `uint256` - the chain id that the subscriber wants updates on - - `address` - the address of the token that the fee will be paid in or 0x0 for the chain's native asset (e.g. ETH, MATIC etc.) - -The subscriber contract **MAY** implement gas refunds on top of the fixed fee per update. When a subscriber chooses to do this, they **SHOULD** specify the `maximum gas` and `maximum gas price` parameters in order to protect themselves from griefing attacks. This is so that a malicious or careless relay doesn't set an exorbitantly high gas price and ends up draining the subscriber contracts. Subscriber contracts can otherwise choose to set a fee that is estimated to be sufficiently high to cover gas fees, but they will need to take care to check that the specified gas price does not effectively reduce the fee to zero (see the note under front-running below for a more detailed explanation). - -Note that while the chain ID and the token address were not included in the original version of the spec, the simple addition of these two parameters allows for cross chain messages, should the subscriber wish to do this, and also allows for payment in various tokens. - -### Updating a subscriber - -To update a subscription, the `updateSubscriber` function **MUST** be called with the same set of parameters as the `registerSubscriber` function. This might be done in order to cancel a subscription, or to change the subscription fee. Note that if the average gas fees on a network change over time, the subscription fee might not be enough to incentivise relayers to notify the subscribers of hook events, so in this case the subscription fee might want to be updated periodically. Note that the `updateSubscriber` function **MUST** maintain the same `msg.sender` that the `registerSubscriber` function was called with. - -### Publishing an event - -A publisher contract **SHOULD** emit a hook event from at least one function. The emitted event **MUST** be called `Hook` and **MUST** contain the following parameters: - - - `uint256 indexed` threadId - - `uint256 indexed` nonce - - `bytes32` digest - - `bytes` payload - - `bytes32` checksum - -The `nonce` value **MUST** be incremented every time a `Hook` event is fired by a publisher contract. Every `Hook` event **MUST** have a unique `nonce` value. The `nonce` property is initialized to `1`, but the first `Hook` event **MUST** have a nonce of `2`, to allow for simpler logic in initiating and auto-incremental state variable. - -The `digest` parameter of the event **MUST** be the keccak256 hash of the payload, and the `checksum` **MUST** be the keccak256 hash of the concatenation of the `digest` with the current block number, e.g.: - -```solidity -bytes32 checksum = keccak256(abi.encodePacked(digest, block.number)); -``` - -The function in the publisher contract that emits the `Hook` event **MAY** be passed a signature from an EOA that calls the function. This signature **MUST** be verified by the subscriber's contracts. When using this approach, the signature **SHOULD** be placed at the start of the payload (e.g. bytes `0` to `65` for an ECDSA signature with `r`, `s`, and `v` properties). - -The publisher contract **MAY** emit a `Hook` event without a signature, which allows the `Hook` event to be triggered by a function call from ANY EOA or external contract, and allows the payload to be created dynamically within the publisher contract. In this case the subscriber contract **SHOULD** call the `verifyEventHook` function on the publisher contract to verify that the received Hook payload is valid. - -The payload **MAY** be passed to the function firing the event or **MAY** be generated by the contract itself, but if a signature is provided, it **MUST** sign a hash of the payload, and it is strongly recommended to use the [EIP-712](./eip-712.md) standard as described in the "Replay Attacks" section below. This signature **SHOULD** be verified by the subscribers to ensure they are getting authentic events. The signature **MUST** correspond to the public key that was registered with the event. - -The payload **MUST** be passed as a byte array in calldata. The subscriber smart contract **SHOULD** convert the byte array into the required data type. For example, if the payload is a snark proof, the actual payload might look something like: - -- `uint256[2]` a -- `uint256[2][2]` b -- `uint256[2]` c -- `uint256[1]` input - -In this case the publisher would need to serialize the variables into a bytes32 array, and the subscriber smart contract would need to deserialize it on the other end, e.g.: - -```text -a[0] = uint256(bytes32(payload[0:32])); -a[1] = uint256(bytes32(payload[32:64])); -b[0][0] = uint256(bytes32(payload[64:96])); -b[0][1] = uint256(bytes32(payload[96:128])); -b[1][0] = uint256(bytes32(payload[128:160])); -b[1][1] = uint256(bytes32(payload[160:192])); -c[0] = uint256(bytes32(payload[192:224])); -c[1] = uint256(bytes32(payload[224:256])); -input[0] = uint256(bytes32(payload[256:288])); -``` - -### Relayers - -Relayers are independent parties that listen to `Hook` events on publisher smart contracts. Relayers retrieve a list of subscribers for different hooks from the registry, and listen for hook events being fired on the publisher contracts. Once a hook event has been fired by a publisher smart contract, relayers can decide to relay the hook event's payload to the subscriber contracts by broadcasting a transaction that calls the subscriber contract's `verifyHook` function. Relayers are incentivised to do this because it is expected that the subscriber contract will remunerate them with ETH, or potentially some other asset. - -Relayers **SHOULD** simulate the transaction locally before broadcasting it to make sure that the contract has sufficient balance for payment of the fee. This requires subscriber contracts to maintain a balance of ETH in order to provision payment of relayer fees. A subscriber contract **MAY** decide to revert a transaction based on some logic, which subsequently allows the subscriber contract to conditionally respond to events, depending on the data in the payload. In this case the relayer will simulate the transaction locally and determine not to relay the Hook event to the publisher contract. - -### Verifying a hook event - -The `verifyHook` function of the subscriber contracts **SHOULD** include logic to ensure that they are retrieving authentic events. In the case where the Hook event contains a signature, then subscriber contracts **SHOULD** create a hash of the required parameters, and **SHOULD** verify that the signature in the hook event is valid against the derived hash and the publisher's public key (see the [EIP-712](./eip-712.md) example for reference). The hook function **SHOULD** also verify the nonce of the hook event and record it internally, in order to prevent replay attacks. - -For Hook events without signatures, the subscriber contract **SHOULD** call the `verifyHookEvent` on the publisher contract in order to verify that the hook event is valid. The publisher smart contract **MUST** implement the `verifyHookEvent`, which accepts the hash of the payload, the thread id, the nonce, and the block height associated with the Hook event, and returns a boolean value to indicate the Hook event's authenticity. - -### Interfaces - -#### `IRegistry` - -```solidity -/// @title IRegistry -/// @dev Implements the registry contract -interface IRegistry { - /// @dev Registers a new hook event by a publisher - /// @param publisherContract The address of the publisher contract - /// @param threadId The id of the thread these hook events will be fired on - /// @return Returns true if the hook is successfully registered - function registerHook(address publisherContract, uint256 threadId) external returns (bool); - - /// @dev Verifies a hook with the publisher smart contract before adding it to the registry - /// @param publisherAddress The address of the publisher contract - /// @param threadId The id of the thread these hook events will be fired on - /// @return Returns true if the hook is successfully verified - function verifyHook(address publisherAddress, uint256 threadId) external returns (bool); - - /// @dev Update a previously registered hook event - /// @dev Can be used to transfer hook authorization to a new address - /// @dev To remove a hook, transfer it to the burn address - /// @param publisherContract The address of the publisher contract - /// @param publisherPubKey The public key used to verify the hook signatures - /// @param threadId The id of the thread these hook events will be fired on - /// @return Returns true if the hook is successfully updated - function updateHook( - address publisherContract, - address publisherPubKey, - uint256 threadId - ) external returns (bool); - - /// @dev Registers a subscriber to a hook event - /// @param publisherContract The address of the publisher contract - /// @param subscriberContract The address of the contract subscribing to the event hooks - /// @param threadId The id of the thread these hook events will be fired on - /// @param fee The fee that the subscriber contract will pay the relayer - /// @param maxGas The maximum gas that the subscriber allow to spend, to prevent griefing attacks - /// @param maxGasPrice The maximum gas price that the subscriber is willing to rebate - /// @param chainId The chain id that the subscriber wants updates on - /// @param feeToken The address of the token that the fee will be paid in or 0x0 for the chain's native asset (e.g. ETH) - /// @return Returns true if the subscriber is successfully registered - function registerSubscriber( - address publisherContract, - address subscriberContract, - uint256 threadId, - uint256 fee, - uint256 maxGas, - uint256 maxGasPrice, - uint256 chainId, - address feeToken - ) external returns (bool); - - /// @dev Registers a subscriber to a hook event - /// @param publisherContract The address of the publisher contract - /// @param subscriberContract The address of the contract subscribing to the event hooks - /// @param threadId The id of the thread these hook events will be fired on - /// @param fee The fee that the subscriber contract will pay the relayer - /// @return Returns true if the subscriber is successfully updated - function updateSubscriber( - address publisherContract, - address subscriberContract, - uint256 threadId, - uint256 fee - ) external returns (bool); -} - -``` - -#### `IPublisher` - -```solidity -/// @title IPublisher -/// @dev Implements a publisher contract -interface IPublisher { - /// @dev Example of a function that fires a hook event when it is called - /// @param payload The actual payload of the hook event - /// @param digest Hash of the hook event payload that was signed - /// @param threadId The thread number to fire the hook event on - function fireHook(bytes calldata payload, bytes32 digest, uint256 threadId) external; - - /// @dev Adds / updates a new hook event internally - /// @param threadId The thread id of the hook - /// @param publisherPubKey The public key associated with the private key that signs the hook events - function addHook(uint256 threadId, address publisherPubKey) external; - - /// @dev Called by the registry contract when registering a hook, used to verify the hook is valid before adding - /// @param threadId The thread id of the hook - /// @param publisherPubKey The public key associated with the private key that signs the hook events - /// @return Returns true if the hook is valid and is ok to add to the registry - function verifyEventHookRegistration(uint256 threadId, address publisherPubKey) external view returns (bool); - - /// @dev Returns the address that will sign the hook events on a given thread - /// @param threadId The thread id of the hook - /// @return Returns the address that will sign the hook events on a given thread - function getEventHook(uint256 threadId) external view returns (address); - - /// @dev Returns true if the specified hook is valid - /// @param payloadhash The hash of the hook's data payload - /// @param threadId The thread id of the hook - /// @param nonce The nonce of the current thread - /// @param blockheight The blockheight that the hook was fired at - /// @return Returns true if the specified hook is valid - function verifyEventHook( - bytes32 payloadhash, - uint256 threadId, - uint256 nonce, - uint256 blockheight - ) external view returns (bool); -} - -``` - -#### `ISubscriber` - -```solidity -/// @title ISubscriber -/// @dev Implements a subscriber contract -interface ISubscriber { - /// @dev Example of a function that is called when a hook is fired by a publisher - /// @param publisher The address of the publisher contract in order to verify hook event with - /// @param payload Hash of the hook event payload that was signed - /// @param threadId The id of the thread this hook was fired on - /// @param nonce Unique nonce of this hook - /// @param blockheight The block height at which the hook event was fired - function verifyHook( - address publisher, - bytes calldata payload, - uint256 threadId, - uint256 nonce, - uint256 blockheight - ) external; -} - -``` - -## Rationale - -The rationale for this design is that it allows smart contract developers to write contract logic that listens and responds to events fired in other smart contracts, without requiring them to run some dedicated off-chain process to achieve this. This best suits any simple smart contract logic that runs relatively infrequently in response to events in other contracts. - -This improves on the existing solutions to achieve a pub/sub design pattern. To elaborate: a number of service providers currently offer "webhooks" as a way to subscribe to events emitted by smart contracts, by having some API endpoint called when the events are emitted, or alternatively offer some serverless feature that can be triggered by some smart contract event. This approach works very well, but it does require that some API endpoint or serverless function be always available, which may require some dedicated server / process, which in turn will need to have some private key, and some amount of ETH in order to re-broadcast transactions. - -This approach offers a more suitable alternative for when an "always-on" server instance is not desirable, e.g. in the case that it will be called infrequently. - -This proposal incorporates a decentralized market-driven relay network, and this decision is based on the fact that this is a highly scalable approach. Conversely, it is possible to implement this functionality without resorting to a market-driven approach, by simply defining a standard for contracts to allow other contracts to subscribe directly. That approach is conceptually simpler, but has its drawbacks, in so far as it requires a publisher contract to record subscribers in its own state, creating an overhead for data management, upgradeability etc. That approach would also require the publisher to call the `verifyHook` function on each subscriber contract, which will incur potentially significant gas costs for the publisher contract. - -## Reference Implementation - -### `Registry` - -```solidity -contract Registry is IRegistry { - event HookRegistered( - address indexed publisherContract, - address publisherPubKey, - uint256 threadId, - address result, - bool valid - ); - - event HookUpdated( - address indexed publisherContract, - address publisherPubKey, - uint256 threadId - ); - - event SubscriberRegistered( - address indexed publisherContract, - address indexed subscriberContract, - uint256 threadId, - uint256 fee, - uint256 maxGas, - uint256 maxGasPrice, - uint256 chainId, - address feeToken - ); - - event SubscriberUpdated( - address indexed publisherContract, - address indexed subscriberContract, - uint256 threadId, - uint256 fee - ); - - /// mapping of publisherContractAddress to threadId to publisherPubKey - /// a publisher contract can pubish multiple different hooks on different thread ids - mapping(address => mapping(uint256 => address)) public publishers; - - /// mapping of subscriberContractAddress to publisherContractAddress to threadIds to fee - /// a subscriber contract can subscribe to multiple hook events on one or more contracts - mapping(address => mapping(address => mapping(uint256 => uint256))) public subscribers; - - /// records the owners of a subscriber contract so that updates can be authorized - mapping(address => address) public owners; - - function registerHook(address publisherContract, uint256 threadId) public returns (bool) { - require( - (publishers[publisherContract][threadId] == address(0)), - "Hook already registered" - ); - - address result = IPublisher(publisherContract).getEventHook(threadId); - - bool isHookValid = verifyHook(publisherContract, threadId); - - require(isHookValid, "Hook not valid"); - - // the sender must be the account that signs the hook events - publishers[publisherContract][threadId] = msg.sender; - - emit HookRegistered(publisherContract, msg.sender, threadId, result, isHookValid); - - return true; - } - - function verifyHook(address publisherAddress, uint256 threadId) public view returns (bool) { - return IPublisher(publisherAddress).verifyEventHookRegistration(threadId, msg.sender); - } - - function updateHook( - address publisherContract, - address publisherPubKey, - uint256 threadId - ) public returns (bool) { - require( - publishers[publisherContract][threadId] == msg.sender, - "Not authorized to update hook" - ); - - publishers[publisherContract][threadId] = publisherPubKey; - - emit HookUpdated(publisherContract, publisherPubKey, threadId); - - return true; - } - - function registerSubscriber( - address publisherContract, - address subscriberContract, - uint256 threadId, - uint256 fee, - uint256 maxGas, - uint256 maxGasPrice, - uint256 chainId, - address feeToken - ) public returns (bool) { - require(fee > 0, "Fee must be greater than 0"); - - require( - subscribers[subscriberContract][publisherContract][threadId] != fee, - "Subscriber already registered" - ); - - subscribers[subscriberContract][publisherContract][threadId] = fee; - - owners[subscriberContract] = msg.sender; - - emit SubscriberRegistered(publisherContract, subscriberContract, threadId, fee, maxGas, maxGasPrice, chainId, feeToken); - - return true; - } - - function updateSubscriber( - address publisherContract, - address subscriberContract, - uint256 threadId, - uint256 fee - ) public returns (bool) { - require(owners[subscriberContract] == msg.sender, "Not authorized to update subscriber"); - - subscribers[subscriberContract][publisherContract][threadId] = fee; - - emit SubscriberUpdated(publisherContract, subscriberContract, threadId, fee); - - return true; - } -} -``` - -### `Publisher` - -```solidity -contract Publisher is IPublisher, Ownable { - uint256 public hookNonce = 1; - - // mapping of threadId to nonce to digest (payload data hash) - mapping(uint256 => mapping(uint256 => bytes32)) public firedHooks; - - event Hook( - uint256 indexed threadId, - uint256 indexed nonce, - bytes32 digest, - bytes payload, - bytes32 checksum - ); - - mapping(uint256 => address) public hooks; - - function fireHook( - bytes calldata payload, - bytes32 digest, - uint256 threadId - ) public onlyOwner { - hookNonce++; - - bytes32 checksum = keccak256(abi.encodePacked(digest, block.number)); - - firedHooks[threadId][hookNonce] = checksum; - - emit Hook(threadId, hookNonce, digest, payload, checksum); - } - - function addHook(uint256 threadId, address publisherPubKey) public onlyOwner { - hooks[threadId] = publisherPubKey; - } - - function verifyEventHookRegistration( - uint256 threadId, - address publisherPubKey - ) public view override returns (bool) { - return (hooks[threadId] == publisherPubKey); - } - - function verifyEventHook( - bytes32 payloadhash, - uint256 threadId, - uint256 nonce, - uint256 blockheight - ) external view returns (bool) { - bytes32 checksum = keccak256(abi.encodePacked(payloadhash, blockheight)); - - bool result = firedHooks[threadId][nonce] == checksum; - - return result; - } - - function getEventHook(uint256 threadId) public view returns (address) { - return hooks[threadId]; - } -} -``` - -### `Subscriber` - -```solidity -contract Subscriber is ISubscriber, Ownable { - uint256 public constant RELAYER_FEE = 0.001 ether; - uint256 public constant MAX_AGE = 4; - uint256 public constant STARTING_GAS = 21000; - uint256 public constant VERIFY_HOOK_ENTRY_GAS = 8000; - uint256 public constant VERIFY_HOOK_GAS_COST = 60000; - uint256 public constant MAX_GAS_PRICE = 10000000000; - - uint256 public constant MAX_GAS_ALLOWED = - STARTING_GAS + VERIFY_HOOK_ENTRY_GAS + VERIFY_HOOK_GAS_COST; - - // mapping of publisher address to threadId to nonce - mapping(address => mapping(uint256 => uint256)) public validPublishers; - - receive() external payable {} - - function updateValidPublishers( - address publisher, - uint256 threadId, - uint256 nonce - ) public onlyOwner { - require(nonce > 0, "nonce must be greater than zero"); - validPublishers[publisher][threadId] = nonce; - } - - function getPublisherNonce(address publisher, uint256 threadId) public view returns (uint256) { - return validPublishers[publisher][threadId]; - } - - function verifyHook( - address publisher, - bytes calldata payload, - uint256 threadId, - uint256 nonce, - uint256 blockheight - ) public { - uint256 gasStart = gasleft(); - - bool isHookValid = IPublisher(publisher).verifyEventHook( - keccak256(payload), - threadId, - nonce, - blockheight - ); - - // checks - require(isHookValid, "Hook not verified by publisher"); - require(nonce > validPublishers[publisher][threadId], "Obsolete hook detected"); - require(tx.gasprice <= MAX_GAS_PRICE, "Gas price is too high"); - require(blockheight < block.number, "Hook event not valid yet"); - require((block.number - blockheight) < MAX_AGE, "Hook has expired"); - require(validPublishers[publisher][threadId] != 0, "Publisher not valid"); - - // effects - validPublishers[publisher][threadId] = nonce; - - // interactions - (bool result, ) = msg.sender.call{value: RELAYER_FEE}(""); - - require(result, "Failed to send relayer fee"); - - require( - (gasStart - gasleft()) < MAX_GAS_ALLOWED, - "Function call exceeded gas allowance" - ); - } -} -``` - -## Security Considerations - -### Griefing attacks - -It is imperative that subscriber contracts trust the publisher contracts not to fire events that hold no intrinsic interest or value for them, as it is possible that malicious publisher contracts can publish a large number of events that will in turn drain the ETH from the subscriber contracts. If the private key used to sign the hook events is ever compromised, then the potential to drain ETH from all subscriber contracts is a very real possibility. - -### Front-running attacks - -When using signatures to validate Hook events, it is important for publishers and subscribers of hooks to realize that it is possible for a relayer to relay hook events before they are broadcast, by examining the publisher's originating transaction in the mempool. The normal flow is for the originating transaction to call a function in the publisher smart contract, which in turn fires an event which is then picked up by relayers. Competitive relayers will observe that it is possible to pluck the signature from the originating transaction from the mempool and simply relay it to subscriber contracts before the originating transaction has been actually included in a block. In fact, it is possible that the subscriber contracts process the event before the originating transaction is processed, based purely on gas fee dynamics. This can mitigated against by subscriber contracts calling the `verifyEventHook` function on the publisher contract when they receive a Hook event. - -Another risk from front-running affects relayers, whereby the relayer's transactions to the subscriber contracts can be front-run by generalized MEV searchers in the mempool. It is likely that this sort of MEV capture will occur in the public mempool, and therefore it is advised that relayers use private channels to block builders to mitigate against this issue. By broadcasting transactions to a segregated mempool, relayers protect themselves from front-running by generalized MEV bots, but their transactions can still fail due to competition from other relayers. If two or more relayers decide to start relaying hook events from the same publisher, then the relay transactions with the highest gas price will be executed before the others. This will result in the other relayer's transactions potentially failing on-chain, by being included later in the same block. For now, there are certain transaction optimization services that will prevent transactions from failing on-chain, which will offer a solution to this problem, though this is out-of-scope for this document. A future iteration of this proposal may well include the option for trusted relayers, who can enter into an on-chain enforceable agreement with subscribers, which should reduce the race-to-the-bottom competitive gas fee issue. - -In order to cultivate and maintain a reliable relayer market, it is recommended that where possible, a subscriber contract implements logic to either rebate any gas fees up to a specified limit, (while still allowing for execution of hook updates under normal conditions), or implements a logical condition that checks that the gas price of the transaction that is calling the `verifyHook` function to ensure that the gas price does not effectively reduce the fee to zero. This would require that the smart contract have some knowledge of the approximate gas used by the `verifyHook` function, and checks that the condition `minFee >= fee - (gasPrice * gasUsed)`. This will mitigate against competitive bidding that would drive the _effective_ relayer fee to zero, by ensuring that there is some minimum fee below which the effective fee is not allowed to drop. This would mean that the highest gas price that can be paid before the transaction reverts is `fee - minFee + ε` where `ε ~= 1 gwei`. This will require careful estimation of the gas cost of the `verifyHook` function and an awareness that the gas used may change over time as the contract's state changes. - -Another important consideration is with batching of Hook events. If a relayer decides to batch multiple Hook event updates to various subscriber contracts into a single transaction, via a multi-call proxy contract, then they increase the risk of the entire batching failing on-chain. For example, if relayer A batches x number of Hook updates, and relayer B batches y number of Hook updates, it is possible that relayer A's batch is included in the same block in front of relayer B's batch, and if both batches contain at least one duplicate, (i.e. the same Hook event to the same subscriber), then this will cause relayer B entire batch transaction to revert on-chain. This is an inportant consideration for relayers. - -### Replay attacks - -When using signature verification, it is advised to use the [EIP-712](./eip-712.md) standard in order to prevent cross network replay attacks, where the same contract deployed on more than one network can have its hook events pushed to subscribers on other networks, e.g. a publisher contract on Polygon can fire an hook event that could be relayed to a subscriber contract on Gnosis Chain. Whereas the keys used to sign the hook events should ideally be unique, in reality this may not always be the case. - -For this reason, it is recommended to use [EIP-721](./eip-712.md) Typed Data Signatures. In this case the off-chain process that initiates the hook should create the signature according to the following data structure: - -```solidity -const domain = [ - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - { name: "salt", type: "bytes32" } -] - -const hook = [ - { name: "payload", type: "string" }, - { type: "uint256", name: "nonce" }, - { type: "uint256", name: "blockheight" }, - { type: "uint256", name: "threadId" }, -] - -const domainData = { - name: "Name of Publisher Dapp", - version: "1", - chainId: parseInt(web3.version.network, 10), - verifyingContract: "0x123456789abcedf....publisher contract address", - salt: "0x123456789abcedf....random hash unique to publisher contract" -} - -const message = { - payload: "bytes array serialized payload" - nonce: 1, - blockheight: 999999, - threadId: 1, -} - -const eip712TypedData = { - types: { - EIP712Domain: domain, - Hook: hook - }, - domain: domainData, - primaryType: "Hook", - message: message -} -``` - -Note: please refer to the unit tests for an example of how a hook event should be constructed properly by the publisher. - -Replay attacks can also occur on the same network that the event hook was fired, by simply re-broadcasting an event hook that was already broadcast previously. For this reason, subscriber contracts should check that a nonce is included in the event hook being received, and record the nonce in the contract's state. If the hook nonce is not valid, or has already been recorded, the transaction should revert. - -It is worth noting that the `chainId` event topic should also be used to prevent cross chain replay attacks, in the case that a dapp is deployed on multiple networks. There is also the possibility to leverage the `chainId` for more than preventing replay attacks, but also for accepting messages from other chains. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5902.md diff --git a/EIPS/eip-5920.md b/EIPS/eip-5920.md index d442dfa66bf569..ba7a1ac496ef99 100644 --- a/EIPS/eip-5920.md +++ b/EIPS/eip-5920.md @@ -2,13 +2,13 @@ eip: 5920 title: PAY opcode description: Introduces a new opcode, PAY, to send ether to an address without calling any of its functions -author: Pandapip1 (@Pandapip1), Zainan Victor Zhou (@xinbenlv) +author: Gavin John (@Pandapip1), Zainan Victor Zhou (@xinbenlv), Sam Wilson (@SamWilsn) discussions-to: https://ethereum-magicians.org/t/eip-5920-pay-opcode/11717 status: Review type: Standards Track category: Core created: 2022-03-14 -requires: 2929 +requires: 2929, 7523 --- ## Abstract @@ -17,31 +17,55 @@ This EIP introduces a new opcode, `PAY`, taking two stack parameters, `addr` and ## Motivation -Currently, to send ether to an address requires you to call a function of that address, which has a few issues. First of all, it opens a reentrancy attack vector, as the recipient can call back into the sender. Secondly, it opens a DoS vector, so parent functions must be cognizant of the possibility that the recipient will run out of gas or revert. Finally, the `CALL` opcode is needlessly expensive for simple ether transfers, as it requires the memory and stack to be expanded, the recipient's full data including code and memory to be loaded, and finally needs to execute a call, which might do other unintentional operations. Having a dedicated opcode for ether transfers solves all of these issues, and would be a useful addition to the EVM. +Currently, to send ether to an address requires you to call into that address, which transfers execution context to that address, which creates several issues: + +- First of all, it opens a reentrancy attack vector, as the recipient can call back into the sender. More generally, the recipient can unilaterally execute arbitrary state changes, limited only by the gas stipend, which is not desirable from the point of view of the sender. +- Secondly, it opens a DoS vector. Contracts which want to send ether must be cognizant of the possibility that the recipient will run out of gas or revert. +- Finally, the `CALL` opcode is needlessly expensive for simple ether transfers, as it requires the memory and stack to be expanded, the recipient's full data including code and memory to be loaded, and finally needs to execute a call, which might do other unintentional operations. Having a dedicated opcode for ether transfers solves all of these issues, and would be a useful addition to the EVM. ## Specification -| Parameter | Value | -| ------------------- | ------- | -| `PAY_OPCODE` | `0xf9` | -| `GAS_COST` | `3000` | +### Constants + +| Constant | Definition | +| -------------------------- | ------------------------- | +| `WARM_STORAGE_READ_COST` | [EIP-2929](./eip-2929.md) | +| `COLD_ACCOUNT_ACCESS_COST` | [EIP-2929](./eip-2929.md) | +| `GAS_NEW_ACCOUNT` | [EELS][gna] | +| `GAS_CALL_VALUE` | [EELS][gcv] | + +[gna]: https://github.com/ethereum/execution-specs/blob/4d953035fb0cceda7cf21d71b2ab7a9a6f4632f0/src/ethereum/frontier/vm/gas.py#L52 +[gcv]: https://github.com/ethereum/execution-specs/blob/4d953035fb0cceda7cf21d71b2ab7a9a6f4632f0/src/ethereum/frontier/vm/gas.py#L53 + +### Behavior -A new opcode is introduced: `PAY` (`PAY_OPCODE`), which: +A new opcode is introduced: `PAY` (`0xf9`), which: - Pops two values from the stack: `addr` then `val`. -- Transfers `val` wei from the executing address to the address `addr`. If `addr` is the zero address, instead, `val` wei is burned from the executing address. +- Transfers `val` wei from the current target address to the address `addr`. +- Marks `addr` as warm (adding `addr` to `accessed_addresses`.) -The cost of this opcode is `GAS_COST`. If `addr` is not the zero address, the [EIP-2929](./eip-2929.md) account access costs are also incurred. +### Gas Cost -## Rationale +The gas cost for `PAY` is the sum of the following: + +- Is `addr` in `accessed_addresses`? + - If yes, `WARM_STORAGE_READ_COST`; + - Otherwise, `COLD_ACCOUNT_ACCESS_COST`. +- Does `addr` exist or is `val` zero? + - If yes to either, zero; + - Otherwise, `GAS_NEW_ACCOUNT`. +- Is `val` zero? + - If yes, zero; + - Otherwise, `GAS_CALL_VALUE`. -### Gas pricing +`PAY` cannot be implemented on networks with empty accounts (see [EIP-7523](./eip-7523.md).) -The gas pricing is that of a `CALL` with a positive `msg.value`, but without any memory expansion costs or "gas sent with call" costs, with a gas reduction of `500` to compensate for the reduced amount of computation. +## Rationale ### Argument order -The order of arguments mimicks that of `CALL`, which pops `addr` before `val`. Beyond consistency, though, this ordering aids validators pattern-matching MEV opportunities, so `PAY` always appears immediately after `COINBASE`. +The order of arguments mimics that of `CALL`, which pops `addr` before `val`. Beyond consistency, though, this ordering aids validators pattern-matching MEV opportunities, so `PAY` always appears immediately after `COINBASE`. ## Backwards Compatibility diff --git a/EIPS/eip-5982.md b/EIPS/eip-5982.md index 1a2be955ca2298..0297f6b7a99f73 100644 --- a/EIPS/eip-5982.md +++ b/EIPS/eip-5982.md @@ -1,92 +1,7 @@ --- eip: 5982 -title: Role-based Access Control -description: An interface for role-based access control for smart contracts. -author: Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/eip-5982-role-based-access-control/11759 -status: Review -type: Standards Track category: ERC -created: 2022-11-15 -requires: 165, 5750 +status: Moved --- -## Abstract - -This EIP defines an interface for role-based access control for smart contracts. Roles are defined as `byte32`. The interface specifies how to read, grant, create and destroy roles. It specifies the sense of role power in the format of its ability to call a given method -identified by `bytes4` method selector. It also specifies how metadata of roles are represented. - -## Motivation - -There are many ways to establish access control for privileged actions. One common pattern is "role-based" access control, where one or more users are assigned to one or more "roles," which grant access to privileged actions. This pattern is more secure and flexible than ownership-based access control since it allows for many people to be granted permissions according to the principle of least privilege. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -Interfaces of reference is described as followed: - -```solidity -interface IERC_ACL_CORE { - function hasRole(bytes32 role, address account) external view returns (bool); - function grantRole(bytes32 role, address account) external; - function revokeRole(bytes32 role, address account) external; -} -``` - -```solidity -interface IERC_ACL_GENERAL { - event RoleGranted(address indexed grantor, bytes32 indexed role, address indexed grantee, bytes _data); - event RoleRevoked(address indexed revoker, bytes32 indexed role, address indexed revokee, bytes _data); - - event RoleCreated(address indexed roleGrantor, bytes32 role, bytes32 adminOfRole, string name, string desc, string uri, bytes32 calldata _data); - event RoleDestroyed(address indexed roleDestroyer, bytes32 role, bytes32 calldata _data); - event RolePowerSet(address indexed rolePowerSetter, bytes32 role, bytes4 methods, bytes calldata _data); - - function grantRole(bytes32 role, address account, bytes calldata _data) external; - function revokeRole(bytes32 role, address account, bytes calldata _data) external; - - function createRole(bytes32 role, bytes32 adminOfRole, string name, string desc, string uri, bytes32 calldata _data) external; - function destroyRole(bytes32 role, bytes32 calldata _data) external; - function setRolePower(bytes32 role, bytes4 methods, bytes calldata _data) view external returns(bool); - - function hasRole(bytes32 role, address account, bytes calldata _data) external view returns (bool); - function canGrantRole(bytes32 grantor, bytes32 grantee, bytes calldata _data) view external returns(bool); - function canRevokeRole(bytes32 revoker, bytes32 revokee, address account, bytes calldata _data) view external returns(bool); - function canExecute(bytes32 executor, bytes4 methods, bytes32 calldata payload, bytes calldata _data) view external returns(bool); -} -``` - -```solidity -interface IERC_ACL_METADATA { - function roleName(bytes32) external view returns(string); - function roleDescription(bytes32) external view returns(string); - function roleURI(bytes32) external view returns(string); -} -``` - -1. Compliant contracts MUST implement `IERC_ACL_CORE` -2. It is RECOMMENDED for compliant contracts to implement the optional extension `IERC_ACL_GENERAL`. -3. Compliant contracts MAY implement the optional extension `IERC_ACL_METADATA`. -4. A role in a compliant smart contract is represented in the format of `bytes32`. It's RECOMMENDED the value of such role is computed as a -`keccak256` hash of a string of the role name, in this format: `bytes32 role = keccak256("")`. such as `bytes32 role = keccak256("MINTER")`. -5. Compliant contracts SHOULD implement [EIP-165](./eip-165.md) identifier. - -## Rationale - -1. The names and parameters of methods in `IERC_ACL_CORE` are chosen to allow backward compatibility with OpenZeppelin's implementation. -2. The methods in `IERC_ACL_GENERAL` conform to [EIP-5750](./eip-5750.md) to allow extension. -3. The method of `renounceRole` was not adopted, consolidating with `revokeRole` to simplify interface. - - -## Backwards Compatibility - -Needs discussion. - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-5982.md diff --git a/EIPS/eip-5988.md b/EIPS/eip-5988.md index 778c1d4b460851..a2cf4d6dfe01ff 100644 --- a/EIPS/eip-5988.md +++ b/EIPS/eip-5988.md @@ -4,7 +4,7 @@ title: Add Poseidon hash function precompile description: Add a precompiled contract which implements the hash function used in the Poseidon cryptographic hashing algorithm author: Abdelhamid Bakhta (@abdelhamidbakhta), Eli Ben Sasson (@Elistark), Avihu Levy (@avihu28), David Levit Gurevich (@DavidLevitGurevich) discussions-to: https://ethereum-magicians.org/t/eip-5988-add-poseidon-hash-function-precompile/11772 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-11-15 diff --git a/EIPS/eip-600.md b/EIPS/eip-600.md index 5165fa1fda244c..8cab2d27265750 100644 --- a/EIPS/eip-600.md +++ b/EIPS/eip-600.md @@ -1,65 +1,7 @@ --- eip: 600 -title: Ethereum purpose allocation for Deterministic Wallets -author: Nick Johnson (@arachnid), Micah Zoltu (@micahzoltu) -type: Standards Track category: ERC -status: Final -discussions-to: https://ethereum-magicians.org/t/eip-erc-app-keys-application-specific-wallet-accounts/2742 -created: 2017-04-13 +status: Moved --- -## Abstract -This EIP defines a logical hierarchy for deterministic wallets based on [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), the purpose scheme defined in [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and [this proposed change to BIP43](https://github.com/bitcoin/bips/pull/523). - -This EIP is a particular application of BIP43. - -## Motivation -Because Ethereum is based on account balances rather than UTXO, the hierarchy defined by BIP44 is poorly suited. As a result, several competing derivation path strategies have sprung up for deterministic wallets, resulting in inter-client incompatibility. This BIP seeks to provide a path to standardise this in a fashion better suited to Ethereum's unique requirements. - -## Specification -We define the following 2 levels in BIP32 path: - -
-m / purpose' / subpurpose' / EIP'
-
- -Apostrophe in the path indicates that BIP32 hardened derivation is used. - -Each level has a special meaning, described in the chapters below. - -### Purpose - -Purpose is set to 43, as documented in [this proposed change to BIP43](https://github.com/bitcoin/bips/pull/523). - -The purpose field indicates that this path is for a non-bitcoin cryptocurrency. - -Hardened derivation is used at this level. - -### Subpurpose -Subpurpose is set to 60, the SLIP-44 code for Ethereum. - -Hardened derivation is used at this level. - -### EIP -EIP is set to the EIP number specifying the remainder of the BIP32 derivation path. This permits new Ethereum-focused applications of deterministic wallets without needing to interface with the BIP process. - -Hardened derivation is used at this level. - -## Rationale -The existing convention is to use the 'Ethereum' coin type, leading to paths starting with `m/44'/60'/*`. Because this still assumes a UTXO-based coin, we contend that this is a poor fit, resulting in standardisation, usability, and security compromises. As a result, we are making the above proposal to define an entirely new hierarchy for Ethereum-based chains. - -## Backwards Compatibility -The introduction of another derivation path requires existing software to add support for this scheme in addition to any existing schemes. Given the already confused nature of wallet derivation paths in Ethereum, we anticipate this will cause relatively little additional disruption, and has the potential to improve matters significantly in the long run. - -## Test Cases -TBD - -## Implementation -None yet. - -## References -[This discussion on derivation paths](https://github.com/ethereum/EIPs/issues/84) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-600.md diff --git a/EIPS/eip-601.md b/EIPS/eip-601.md index 50504640ce3fe2..7802e2fd27792c 100644 --- a/EIPS/eip-601.md +++ b/EIPS/eip-601.md @@ -1,80 +1,7 @@ --- eip: 601 -title: Ethereum hierarchy for deterministic wallets -author: Nick Johnson (@arachnid), Micah Zoltu (@micahzoltu) -type: Standards Track category: ERC -status: Final -discussions-to: https://ethereum-magicians.org/t/eip-erc-app-keys-application-specific-wallet-accounts/2742 -created: 2017-04-13 +status: Moved --- -## Abstract -This EIP defines a logical hierarchy for deterministic wallets based on [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki), the purpose scheme defined in [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) and eip-draft-ethereum-purpose. - -This EIP is a particular application of eip-draft-ethereum-purpose. - -## Motivation -At present, different Ethereum clients and wallets use different derivation paths; a summary of them can be found [here](https://github.com/ethereum/EIPs/issues/84#issuecomment-292324521). Some of these paths violate BIP44, the standard defining derivation paths starting with `m/44'/`. This creates confusion and incompatibility between wallet implementations, in some cases making funds from one wallet inaccessible on another, and in others requiring prompting users manually for a derivation path, which hinders usability. - -Further, BIP44 was designed with UTXO-based blockchains in mind, and is a poor fit for Ethereum, which uses an accounts abstraction instead. - -As an alternative, we propose a deterministic wallet hierarchy better tailored to Ethereum's unique requiremnts. - -## Specification -We define the following 4 levels in BIP32 path: - -
-m / purpose' / subpurpose' / EIP' / wallet'
-
- -Apostrophe in the path indicates that BIP32 hardened derivation is used. - -Each level has a special meaning, described in the chapters below. - -### Purpose - -Purpose is a constant set to 43, indicating the key derivation is for a non-bitcoin cryptocurrency. - -Hardened derivation is used at this level. - -### Subpurpose -Subpurpose is set to 60, the SLIP-44 code for Ethereum. - -Hardened derivation is used at this level. - -### EIP -EIP is set to the EIP number specifying the remainder of the BIP32 derivation path. For paths following this EIP specification, the number assigned to this EIP is used. - -Hardened derivation is used at this level. - -### Wallet -This component of the path splits the wallet into different user identities, allowing a single wallet to have multiple public identities. - -Accounts are numbered from index 0 in sequentially increasing manner. This number is used as child index in BIP32 derivation. - -Hardened derivation is used at this level. - -Software should prevent a creation of an account if a previous account does not have a transaction history (meaning its address has not been used before). - -Software needs to discover all used accounts after importing the seed from an external source. - -## Rationale -The existing convention is to use the 'Ethereum' coin type, leading to paths starting with `m/44'/60'/*`. Because this still assumes a UTXO-based coin, we contend that this is a poor fit, resulting in standardisation, usability, and security compromises. As a result, we are making the above proposal to define an entirely new hierarchy for Ethereum-based chains. - -## Backwards Compatibility -The introduction of another derivation path requires existing software to add support for this scheme in addition to any existing schemes. Given the already confused nature of wallet derivation paths in Ethereum, we anticipate this will cause relatively little additional disruption, and has the potential to improve matters significantly in the long run. - -For applications that utilise mnemonics, the authors expect to submit another EIP draft that describes a method for avoiding backwards compatibility concerns when transitioning to this new derivation path. - -## Test Cases -TBD - -## Implementation -None yet. - -## References -[This discussion on derivation paths](https://github.com/ethereum/EIPs/issues/84) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-601.md diff --git a/EIPS/eip-6046.md b/EIPS/eip-6046.md index a4af4fed15d756..753b50d1fde955 100644 --- a/EIPS/eip-6046.md +++ b/EIPS/eip-6046.md @@ -4,7 +4,7 @@ title: Replace SELFDESTRUCT with DEACTIVATE description: Change SELFDESTRUCT to not delete storage keys and use a special value in the account nonce to signal deactivation author: Alex Beregszaszi (@axic) discussions-to: https://ethereum-magicians.org/t/almost-self-destructing-selfdestruct-deactivate/11886 -status: Draft +status: Stagnant type: Standards Track category: Core created: 2022-11-25 diff --git a/EIPS/eip-6047.md b/EIPS/eip-6047.md new file mode 100644 index 00000000000000..43579b7ba48212 --- /dev/null +++ b/EIPS/eip-6047.md @@ -0,0 +1,7 @@ +--- +eip: 6047 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6047.md diff --git a/EIPS/eip-6051.md b/EIPS/eip-6051.md index c1f380db909a2e..5a766130a7a6a0 100644 --- a/EIPS/eip-6051.md +++ b/EIPS/eip-6051.md @@ -4,7 +4,7 @@ title: Private Key Encapsulation description: defines a specification for encapsulating private keys. author: Base Labs (@Base-Labs), Weiji Guo (@weiji-cryptonatty) discussions-to: https://ethereum-magicians.org/t/private-key-encapsulation-to-move-around-securely-without-entering-seed/11604 -status: Draft +status: Stagnant type: Standards Track category: Interface created: 2022-11-21 diff --git a/EIPS/eip-6059.md b/EIPS/eip-6059.md index 216cea55f0f2d9..de4f33ed0fff82 100644 --- a/EIPS/eip-6059.md +++ b/EIPS/eip-6059.md @@ -1,481 +1,7 @@ --- eip: 6059 -title: Parent-Governed Nestable Non-Fungible Tokens -description: An interface for Nestable Non-Fungible Tokens with emphasis on parent token's control over the relationship. -author: Bruno Škvorc (@Swader), Cicada (@CicadaNCR), Steven Pineda (@steven2308), Stevan Bogosavljevic (@stevyhacker), Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/eip-6059-parent-governed-nestable-non-fungible-tokens/11914 -status: Review -type: Standards Track category: ERC -created: 2022-11-15 -requires: 165, 721 +status: Moved --- -## Abstract - -The Parent-Governed Nestable NFT standard extends [EIP-721](./eip-721.md) by allowing for a new inter-NFT relationship and interaction. - -At its core, the idea behind the proposal is simple: the owner of an NFT does not have to be an Externally Owned Account (EOA) or a smart contract, it can also be an NFT. - -The process of nesting an NFT into another is functionally identical to sending it to another user. The process of sending a token out of another one involves issuing a transaction from the account owning the parent token. - -An NFT can be owned by a single other NFT, but can in turn have a number of NFTs that it owns. This proposal establishes the framework for the parent-child relationships of NFTs. A parent token is the one that owns another token. A child token is a token that is owned by another token. A token can be both a parent and child at the same time. Child tokens of a given token can be fully managed by the parent token's owner, but can be proposed by anyone. - -![Nestable tokens](../assets/eip-6059/img/eip-6059-nestable-tokens.png) - -The graph illustrates how a child token can also be a parent token, but both are still administered by the root parent token's owner. - -## Motivation - -With NFTs being a widespread form of tokens in the Ethereum ecosystem and being used for a variety of use cases, it is time to standardize additional utility for them. Having the ability for tokens to own other tokens allows for greater utility, usability and forward compatibility. - -In the four years since [EIP-721](./eip-721.md) was published, the need for additional functionality has resulted in countless extensions. This EIP improves upon EIP-721 in the following areas: - -- [Bundling](#bundling) -- [Collecting](#collecting) -- [Membership](#membership) -- [Delegation](#delegation) - -### Bundling - -One of the most frequent uses of [EIP-721](./eip-721.md) is to disseminate the multimedia content that is tied to the tokens. In the event that someone wants to offer a bundle of NFTs from various collections, there is currently no easy way of bundling all of these together and handle their sale as a single transaction. This proposal introduces a standardized way of doing so. Nesting all of the tokens into a simple bundle and selling that bundle would transfer the control of all of the tokens to the buyer in a single transaction. - -### Collecting - -A lot of NFT consumers collect them based on countless criteria. Some aim for utility of the tokens, some for the uniqueness, some for the visual appeal, etc. There is no standardized way to group the NFTs tied to a specific account. By nesting NFTs based on their owner's preference, this proposal introduces the ability to do it. The root parent token could represent a certain group of tokens and all of the children nested into it would belong to it. - -The rise of soulbound, non-transferable, tokens, introduces another need for this proposal. Having a token with multiple soulbound traits (child tokens), allows for numerous use cases. One concrete example of this can be drawn from supply trains use case. A shipping container, represented by an NFT with its own traits, could have multiple child tokens denoting each leg of its journey. - -### Membership - -A common utility attached to NFTs is a membership to a Decentralised Autonomous Organization (DAO) or to some other closed-access group. Some of these organizations and groups occasionally mint NFTs to the current holders of the membership NFTs. With the ability to nest mint a token into a token, such minting could be simplified, by simply minting the bonus NFT directly into the membership one. - -### Delegation - -One of the core features of DAOs is voting and there are various approaches to it. One such mechanic is using fungible voting tokens where members can delegate their votes by sending these tokens to another member. Using this proposal, delegated voting could be handled by nesting your voting NFT into the one you are delegating your votes to and transferring it when the member no longer wishes to delegate their votes. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// @title EIP-6059 Parent-Governed Nestable Non-Fungible Tokens -/// @dev See https://eips.ethereum.org/EIPS/eip-6059 -/// @dev Note: the ERC-165 identifier for this interface is 0x60b766e5. - -pragma solidity ^0.8.16; - -interface INestable { - /** - * @notice The core struct of ownership. - * @dev The `DirectOwner` struct is used to store information of the next immediate owner, be it the parent token, - * an `ERC721Receiver` contract or an externally owned account. - * @dev If the token is not owned by an NFT, the `tokenId` MUST equal `0`. - * @param tokenId ID of the parent token - * @param ownerAddress Address of the owner of the token. If the owner is another token, then the address MUST be - * the one of the parent token's collection smart contract. If the owner is externally owned account, the address - * MUST be the address of this account - * @param isNft A boolean value signifying whether the token is owned by another token (`true`) or by an externally - * owned account (`false`) - */ - struct DirectOwner { - uint256 tokenId; - address ownerAddress; - bool isNft; - } - - /** - * @notice Used to notify listeners that the token is being transferred. - * @dev Emitted when `tokenId` token is transferred from `from` to `to`. - * @param from Address of the previous immediate owner, which is a smart contract if the token was nested. - * @param to Address of the new immediate owner, which is a smart contract if the token is being nested. - * @param fromTokenId ID of the previous parent token. If the token was not nested before, the value MUST be `0` - * @param toTokenId ID of the new parent token. If the token is not being nested, the value MUST be `0` - * @param tokenId ID of the token being transferred - */ - event NestTransfer( - address indexed from, - address indexed to, - uint256 fromTokenId, - uint256 toTokenId, - uint256 indexed tokenId - ); - - /** - * @notice Used to notify listeners that a new token has been added to a given token's pending children array. - * @dev Emitted when a child NFT is added to a token's pending array. - * @param tokenId ID of the token that received a new pending child token - * @param childIndex Index of the proposed child token in the parent token's pending children array - * @param childAddress Address of the proposed child token's collection smart contract - * @param childId ID of the child token in the child token's collection smart contract - */ - event ChildProposed( - uint256 indexed tokenId, - uint256 childIndex, - address indexed childAddress, - uint256 indexed childId - ); - - /** - * @notice Used to notify listeners that a new child token was accepted by the parent token. - * @dev Emitted when a parent token accepts a token from its pending array, migrating it to the active array. - * @param tokenId ID of the token that accepted a new child token - * @param childIndex Index of the newly accepted child token in the parent token's active children array - * @param childAddress Address of the child token's collection smart contract - * @param childId ID of the child token in the child token's collection smart contract - */ - event ChildAccepted( - uint256 indexed tokenId, - uint256 childIndex, - address indexed childAddress, - uint256 indexed childId - ); - - /** - * @notice Used to notify listeners that all pending child tokens of a given token have been rejected. - * @dev Emitted when a token removes all a child tokens from its pending array. - * @param tokenId ID of the token that rejected all of the pending children - */ - event AllChildrenRejected(uint256 indexed tokenId); - - /** - * @notice Used to notify listeners a child token has been transferred from parent token. - * @dev Emitted when a token transfers a child from itself, transferring ownership. - * @param tokenId ID of the token that transferred a child token - * @param childIndex Index of a child in the array from which it is being transferred - * @param childAddress Address of the child token's collection smart contract - * @param childId ID of the child token in the child token's collection smart contract - * @param fromPending A boolean value signifying whether the token was in the pending child tokens array (`true`) or - * in the active child tokens array (`false`) - */ - event ChildTransferred( - uint256 indexed tokenId, - uint256 childIndex, - address indexed childAddress, - uint256 indexed childId, - bool fromPending - ); - - /** - * @notice The core child token struct, holding the information about the child tokens. - * @return tokenId ID of the child token in the child token's collection smart contract - * @return contractAddress Address of the child token's smart contract - */ - struct Child { - uint256 tokenId; - address contractAddress; - } - - /** - * @notice Used to retrieve the *root* owner of a given token. - * @dev The *root* owner of the token is the top-level owner in the hierarchy which is not an NFT. - * @dev If the token is owned by another NFT, it MUST recursively look up the parent's root owner. - * @param tokenId ID of the token for which the *root* owner has been retrieved - * @return owner The *root* owner of the token - */ - function ownerOf(uint256 tokenId) external view returns (address owner); - - /** - * @notice Used to retrieve the immediate owner of the given token. - * @dev If the immediate owner is another token, the address returned, MUST be the one of the parent token's - * collection smart contract. - * @param tokenId ID of the token for which the direct owner is being retrieved - * @return address Address of the given token's owner - * @return uint256 The ID of the parent token. MUST be `0` if the owner is not an NFT - * @return bool The boolean value signifying whether the owner is an NFT or not - */ - function directOwnerOf(uint256 tokenId) - external - view - returns ( - address, - uint256, - bool - ); - - /** - * @notice Used to burn a given token. - * @dev When a token is burned, all of its child tokens are recursively burned as well. - * @dev When specifying the maximum recursive burns, the execution MUST be reverted if there are more children to be - * burned. - * @dev Setting the `maxRecursiveBurn` value to 0 SHOULD only attempt to burn the specified token and MUST revert if - * there are any child tokens present. - * @param tokenId ID of the token to burn - * @param maxRecursiveBurns Maximum number of tokens to recursively burn - * @return uint256 Number of recursively burned children - */ - function burn(uint256 tokenId, uint256 maxRecursiveBurns) - external - returns (uint256); - - /** - * @notice Used to add a child token to a given parent token. - * @dev This adds the child token into the given parent token's pending child tokens array. - * @dev The destination token MUST NOT be a child token of the token being transferred or one of its downstream - * child tokens. - * @dev This method MUST NOT be called directly. It MUST only be called from an instance of `INestable` as part of a - `nestMint`, `nestTransfer` or `transferChild` to an NFT. - * @dev Requirements: - * - * - `directOwnerOf` on the child contract MUST resolve to the called contract. - * - the pending array of the parent contract MUST not be full. - * @param parentId ID of the parent token to receive the new child token - * @param childId ID of the new proposed child token - */ - function addChild(uint256 parentId, uint256 childId) external; - - /** - * @notice Used to accept a pending child token for a given parent token. - * @dev This moves the child token from parent token's pending child tokens array into the active child tokens - * array. - * @param parentId ID of the parent token for which the child token is being accepted - * @param childIndex Index of the child token to accept in the pending children array of a given token - * @param childAddress Address of the collection smart contract of the child token expected to be at the specified - * index - * @param childId ID of the child token expected to be located at the specified index - */ - function acceptChild( - uint256 parentId, - uint256 childIndex, - address childAddress, - uint256 childId - ) external; - - /** - * @notice Used to reject all pending children of a given parent token. - * @dev Removes the children from the pending array mapping. - * @dev The children's ownership structures are not updated. - * @dev Requirements: - * - * - `parentId` MUST exist - * @param parentId ID of the parent token for which to reject all of the pending tokens - * @param maxRejections Maximum number of expected children to reject, used to prevent from - * rejecting children which arrive just before this operation. - */ - function rejectAllChildren(uint256 parentId, uint256 maxRejections) external; - - /** - * @notice Used to transfer a child token from a given parent token. - * @dev MUST remove the child from the parent's active or pending children. - * @dev When transferring a child token, the owner of the token MUST be set to `to`, or not updated in the event of `to` - * being the `0x0` address. - * @param tokenId ID of the parent token from which the child token is being transferred - * @param to Address to which to transfer the token to - * @param destinationId ID of the token to receive this child token (MUST be 0 if the destination is not a token) - * @param childIndex Index of a token we are transferring, in the array it belongs to (can be either active array or - * pending array) - * @param childAddress Address of the child token's collection smart contract - * @param childId ID of the child token in its own collection smart contract - * @param isPending A boolean value indicating whether the child token being transferred is in the pending array of the - * parent token (`true`) or in the active array (`false`) - * @param data Additional data with no specified format, sent in call to `to` - */ - function transferChild( - uint256 tokenId, - address to, - uint256 destinationId, - uint256 childIndex, - address childAddress, - uint256 childId, - bool isPending, - bytes data - ) external; - - /** - * @notice Used to retrieve the active child tokens of a given parent token. - * @dev Returns array of Child structs existing for parent token. - * @dev The Child struct consists of the following values: - * [ - * tokenId, - * contractAddress - * ] - * @param parentId ID of the parent token for which to retrieve the active child tokens - * @return struct[] An array of Child structs containing the parent token's active child tokens - */ - function childrenOf(uint256 parentId) - external - view - returns (Child[] memory); - - /** - * @notice Used to retrieve the pending child tokens of a given parent token. - * @dev Returns array of pending Child structs existing for given parent. - * @dev The Child struct consists of the following values: - * [ - * tokenId, - * contractAddress - * ] - * @param parentId ID of the parent token for which to retrieve the pending child tokens - * @return struct[] An array of Child structs containing the parent token's pending child tokens - */ - function pendingChildrenOf(uint256 parentId) - external - view - returns (Child[] memory); - - /** - * @notice Used to retrieve a specific active child token for a given parent token. - * @dev Returns a single Child struct locating at `index` of parent token's active child tokens array. - * @dev The Child struct consists of the following values: - * [ - * tokenId, - * contractAddress - * ] - * @param parentId ID of the parent token for which the child is being retrieved - * @param index Index of the child token in the parent token's active child tokens array - * @return struct A Child struct containing data about the specified child - */ - function childOf(uint256 parentId, uint256 index) - external - view - returns (Child memory); - - /** - * @notice Used to retrieve a specific pending child token from a given parent token. - * @dev Returns a single Child struct locating at `index` of parent token's active child tokens array. - * @dev The Child struct consists of the following values: - * [ - * tokenId, - * contractAddress - * ] - * @param parentId ID of the parent token for which the pending child token is being retrieved - * @param index Index of the child token in the parent token's pending child tokens array - * @return struct A Child struct containing data about the specified child - */ - function pendingChildOf(uint256 parentId, uint256 index) - external - view - returns (Child memory); - - /** - * @notice Used to transfer the token into another token. - * @dev The destination token MUST NOT be a child token of the token being transferred or one of its downstream - * child tokens. - * @param from Address of the direct owner of the token to be transferred - * @param to Address of the receiving token's collection smart contract - * @param tokenId ID of the token being transferred - * @param destinationId ID of the token to receive the token being transferred - */ - function nestTransferFrom( - address from, - address to, - uint256 tokenId, - uint256 destinationId - ) external; -} -``` - -ID MUST never be a `0` value, as this proposal uses `0` values do signify that the token/destination is not an NFT. - -## Rationale - -Designing the proposal, we considered the following questions: - -1. **How to name the proposal?**\ -In an effort to provide as much information about the proposal we identified the most important aspect of the proposal; the parent centered control over nesting. The child token's role is only to be able to be `Nestable` and support a token owning it. This is how we landed on the `Parent-Centered` part of the title. -2. **Why is automatically accepting a child using [EIP-712](./eip-712.md) permit-style signatures not a part of this proposal?**\ -For consistency. This proposal extends EIP-721 which already uses 1 transaction for approving operations with tokens. It would be inconsistent to have this and also support signing messages for operations with assets. -3. **Why use indexes?**\ -To reduce the gas consumption. If the token ID was used to find which token to accept or reject, iteration over arrays would be required and the cost of the operation would depend on the size of the active or pending children arrays. With the index, the cost is fixed. Lists of active and pending children per token need to be maintained, since methods to get them are part of the proposed interface.\ -To avoid race conditions in which the index of a token changes, the expected token ID as well as the expected token's collection smart contract is included in operations requiring token index, to verify that the token being accessed using the index is the expected one.\ -Implementation that would internally keep track of indices using mapping was attempted. The minimum cost of accepting a child token was increased by over 20% and the cost of minting has increased by over 15%. We concluded that it is not necessary for this proposal and can be implemented as an extension for use cases willing to accept the increased transaction cost this incurs. In the sample implementation provided, there are several hooks which make this possible. -4. **Why is the pending children array limited instead of supporting pagination?**\ -The pending child tokens array is not meant to be a buffer to collect the tokens that the root owner of the parent token wants to keep, but not enough to promote them to active children. It is meant to be an easily traversable list of child token candidates and should be regularly maintained; by either accepting or rejecting proposed child tokens. There is also no need for the pending child tokens array to be unbounded, because active child tokens array is.\ -Another benefit of having bounded child tokens array is to guard against spam and griefing. As minting malicious or spam tokens could be relatively easy and low-cost, the bounded pending array assures that all of the tokens in it are easy to identify and that legitimate tokens are not lost in a flood of spam tokens, if one occurs.\ -A consideration tied to this issue was also how to make sure, that a legitimate token is not accidentally rejected when clearing the pending child tokens array. We added the maximum pending children to reject argument to the clear pending child tokens array call. This assures that only the intended number of pending child tokens is rejected and if a new token is added to the pending child tokens array during the course of preparing such call and executing it, the clearing of this array SHOULD result in a reverted transaction. -5. **Should we allow tokens to be nested into one of its children?**\ -The proposal enforces that a parent token can't be nested into one of its child token, or downstream child tokens for that matter. A parent token and its children are all managed by the parent token's root owner. This means that if a token would be nested into one of its children, this would create the ownership loop and none of the tokens within the loop could be managed anymore. -6. **Why is there not a "safe" nest transfer method?**\ -`nestTransfer` is always "safe" since it MUST check for `INestable` compatibility on the destination. -7. **How does this proposal differ from the other proposals trying to address a similar problem?**\ -This interface allows for tokens to both be sent to and receive other tokens. The propose-accept and parent governed patterns allow for a more secure use. The backward compatibility is only added for EIP-721, allowing for a simpler interface. The proposal also allows for different collections to inter-operate, meaning that nesting is not locked to a single smart contract, but can be executed between completely separate NFT collections. - -### Propose-Commit pattern for child token management - -Adding child tokens to a parent token MUST be done in the form of propose-commit pattern to allow for limited mutability by a 3rd party. When adding a child token to a parent token, it is first placed in a *"Pending"* array, and MUST be migrated to the *"Active"* array by the parent token's root owner. The *"Pending"* child tokens array SHOULD be limited to 128 slots to prevent spam and griefing. - -The limitation that only the root owner can accept the child tokens also introduces a trust inherent to the proposal. This ensures that the root owner of the token has full control over the token. No one can force the user to accept a child if they don't want to. - -### Parent Governed pattern - -The parent NFT of a nested token and the parent's root owner are in all aspects the true owners of it. Once you send a token to another one you give up ownership. - -We continue to use EIP-721's `ownerOf` functionality which will now recursively look up through parents until it finds an address which is not an NFT, this is referred to as the *root owner*. Additionally we provide the `directOwnerOf` which returns the most immediate owner of a token using 3 values: the owner address, the tokenId which MUST be 0 if the direct owner is not an NFT, and a flag indicating whether or not the parent is an NFT. - -The root owner or an approved party MUST be able do the following operations on children: `acceptChild`, `rejectAllChildren` and `transferChild`. - -The root owner or an approved party MUST also be allowed to do these operations only when token is not owned by an NFT: `transferFrom`, `safeTransferFrom`, `nestTransferFrom`, `burn`. - -If the token is owned by an NFT, only the parent NFT itself MUST be allowed to execute the operations listed above. Transfers MUST be done from the parent token, using `transferChild`, this method in turn SHOULD call `nestTransferFrom` or `safeTransferFrom` in the child token's smart contract, according to whether the destination is an NFT or not. For burning, tokens must first be transferred to an EOA and then burned. - -We add this restriction to prevent inconsistencies on parent contracts, since only the `transferChild` method takes care of removing the child from the parent when it is being transferred out of it. - -### Child token management - -This proposal introduces a number of child token management functions. In addition to the permissioned migration from *"Pending"* to *"Active"* child tokens array, the main token management function from this proposal is the `tranferChild` function. The following state transitions of a child token are available with it: - -1. Reject child token -2. Abandon child token -3. Unnest child token -4. Transfer the child token to an EOA or an `ERC721Receiver` -5. Transfer the child token into a new parent token - -To better understand how these state transitions are achieved, we have to look at the available parameters passed to `transferChild`: - -```solidity - function transferChild( - uint256 tokenId, - address to, - uint256 destinationId, - uint256 childIndex, - address childAddress, - uint256 childId, - bool isPending, - bytes data - ) external; -``` - -Based on the desired state transitions, the values of these parameters have to be set accordingly (any parameters not set in the following examples depend on the child token being managed): - -1. **Reject child token**\ -![Reject child token](../assets/eip-6059/img/eip-6059-reject-child.png) -2. **Abandon child token**\ -![Abandon child token](../assets/eip-6059/img/eip-6059-abandon-child.png) -3. **Unnest child token**\ -![Unnest child token](../assets/eip-6059/img/eip-6059-unnest-child.png)\ -4. **Transfer the child token to an EOA or an `ERC721Receiver`**\ -![Transfer child token to EOA](../assets/eip-6059/img/eip-6059-transfer-child-to-eoa.png) -5. **Transfer the child token into a new parent token**\ -![Transfer child token to parent token](../assets/eip-6059/img/eip-6059-transfer-child-to-token.png)\ -This state change places the token in the pending array of the new parent token. The child token still needs to be accepted by the new parent token's root owner in order to be placed into the active array of that token. - -## Backwards Compatibility - -The Nestable token standard has been made compatible with [EIP-721](./eip-721.md) in order to take advantage of the robust tooling available for implementations of EIP-721 and to ensure compatibility with existing EIP-721 infrastructure. - -## Test Cases - -Tests are included in [`nestable.ts`](../assets/eip-6059/test/nestable.ts). - -To run them in terminal, you can use the following commands: - -``` -cd ../assets/eip-6059 -npm install -npx hardhat test -``` - -## Reference Implementation - -See [`NestableToken.sol`](../assets/eip-6059/contracts/NestableToken.sol). - - -## Security Considerations - -The same security considerations as with [EIP-721](./eip-721.md) apply: hidden logic may be present in any of the functions, including burn, add resource, accept resource, and more. - -Caution is advised when dealing with non-audited contracts. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6059.md diff --git a/EIPS/eip-6065.md b/EIPS/eip-6065.md index 52373c3f8ad783..eeaa018cdf7c26 100644 --- a/EIPS/eip-6065.md +++ b/EIPS/eip-6065.md @@ -1,423 +1,7 @@ --- eip: 6065 -title: Real Estate Token -description: An interface for real estate NFTs that extends EIP-721 -author: Alex (@Alex-Klasma), Ben Fusek (@bfusek), Daniel Fallon-Cyr (@dfalloncyr) -discussions-to: https://ethereum-magicians.org/t/eip-6065-real-estate-token/11936 -status: Draft -type: Standards Track category: ERC -created: 2022-11-29 -requires: 721 +status: Moved --- -## Abstract - -This proposal introduces an open structure for physical real estate and property to exist on the blockchain. This standard builds off of [EIP-721](./eip-721.md), adding important functionality necessary for representing real world assets such as real estate. The three objectives this standard aims to meet are: universal transferability of the NFT, private property rights attached to the NFT, and atomic transfer of property rights with the transfer of the NFT. The token contains a hashed operating agreement component, the ability to transfer legal ownership of the property, a payment function, and a repossession function. In addition to the token component, there are legal requirements that have to be met, which are discussed in the specification. - -## Motivation - -Real estate is the largest asset class in the world. By tokenizing real estate, barriers to entry are lowered, transaction costs are minimized, information asymmetry is reduced, ownership structures become more malleable, and a new building block for innovation is formed. However, in order to tokenize this asset class, a common standard is needed that accounts for its real world particularities while remaining flexible enough to adapt to various jurisdictions and regulatory environments. - -Ethereum tokens involving real world assets are notoriously tricky. This is because Ethereum tokens exist on-chain, while real estate exists off-chain. As such, the two are subject to entirely different consensus environments. For Ethereum tokens, consensus is reached through a formalized process of distributed validators. When a purely-digital NFT is transferred, the new owner has a cryptographic guarantee of ownership. For real estate, consensus is supported by legal contracts, property law, and enforced by the court system. With existing asset-backed EIP-721 tokens, a transfer of the token to another individual does not necessarily have any impact on the legal ownership of the physical asset. - -This standard attempts to solve the real world reconciliation issue, enabling real estate NFTs to function seamlessly on-chain, just like their purely-digital counterparts. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -In order to meet the above objectives and create an open standard for on-chain property ownership we have created a token structure that builds on the EIP-721 standard and coupled that with a set of legal requirements broad enough to adapt to various jurisdictions and regulatory environments. - -### Token Components: - -1. Inherits EIP-721 - Allows for backwards compatibility with the most widely accepted NFT token standard. -2. Transferable Administrator of physical asset - Ability for NFT owner to initiate a transfer of the legal owner of the physical asset. -3. Hashed operating agreement - Immutable legal agreement between Administrator and NFT owner that requires both parties to accept any proposed changes before they are made. -4. Payment function - Ability for NFT Administrator to request payment for financing any payments made by the Administrator on behalf of the NFT owner (e.g. property taxes). -5. Repossession function - Ability for Administrator to repossess the asset to ensure legally required payments are made whole (e.g. unpaid property taxes). - -### Token Legal Requirements (Outlined in Hashed Operating Agreement): - -1. Property held by the Administrator is self-contained, transferable, and bankruptcy remote. -2. Transfer of property rights are atomic with the digital transfer of the NFT. -3. The NFT owner Ethereum address has the right to change the Administrator (i.e. legal owner) of the property. -4. The operating agreement for the legal entity which holds the property must be hashed to the NFT and cannot be changed without mutual approval from both the NFT owner and the Administrator. -5. The operating agreement must contain the right for the NFT owner to hold, occupy, rent, alter, resell, or transfer the property. -6. The Administrator has no usage right to the property and may not collateralize, use, or otherwise encumber the property attached to the NFT. -7. The Administrator is the sole legal owner of the property, and responsible for facilitating mandatory filings and payments for the property. -8. The Administrator is entitled to limited liability with regard to the property and has a right to require insurance on the property. -9. Failure of the NFT owner to make required payments for the property (e.g. property taxes) triggers the Administrator’s right to repossess the property in order to make required payments. - -### Interfaces - -We rely on the EIP-721 NFT token standard for all transfer and approval logic. All transfer and approval functions are inherited from this token standard without changes. This allows an NFT under this standard to become interoperable with preexisting NFT exchanges and services, however some care must be taken. Please refer to the `Backwards Compatibility` section. - -#### Administrator - -``` -/// @dev This event emits when a change of NFT Administrator is proposed. -/// Note that contracts can be init'ed with changes proposed without this event emitted. -event AdministratorChangeInit(uint256 indexed _tokenId, address indexed _owner, address indexed _from, address indexed _to, string _extradata); - -/// @dev This event emits when a change of NFT Administrator is canceled. -/// When an EIP-721 transfer event emits, any proposed Administrator changes should be nulled and this event should also emit -event AdministratorChangeCanceled(uint256 indexed _tokenId, address indexed _owner, address indexed _from, address indexed _to, string _extradata); - -/// @dev This event emits when a change of NFT Administrator is accepted. The new Administrator MUST accept this change for this event to emit. -/// This event MUST emit on any change, however, contracts can be init'ed with Administrators set and without emitting events. -event AdministratorChangeAccept(uint256 indexed _tokenId, address indexed _owner, address indexed _from, address indexed _to, string _extradata); - -/// @dev MUST emit if cancelAdministratorAccept is called successfully -event AdministratorChangeAcceptCanceled(uint256 indexed _tokenId, address indexed _owner, address indexed _from, address indexed _to, string _extradata); - -/// @dev MUST emit if finishAdministratorChange is called successfully -event AdministratorChangeFinish(uint256 indexed _tokenId, address indexed _owner, address indexed _from, address indexed _to, string _extradata); - -/// @notice query current Administrator of an NFT -/// @dev NFTs assigned to zero address are considered invalid, and queries about them do throw. -/// @param _tokenId The identifier for an NFT -/// @return The address of the Administrator of the NFT -function administratorOf(uint256 _tokenId) external view returns (address); - -// STEP 1: Owner propose Administrator change, possible to cancel - -/// @notice propose a change of an Administrator for an NFT, called by ownerOf(NFT) -/// @dev Throws unless msg.sender is the current ownerOf this NFT. -/// @param _tokenId The identifier for an NFT -/// @param _to The newly proposed Administrator of an NFT, if _to == address(0), -/// this can be interpreted as _to == msg.sender == ownerOf, and they want to self-custody. -/// @param _extradata An optional field for metadata -function initAdministratorChange(uint256 _tokenId, address _to, string calldata _extradata) external; - -/// @notice query current proposed Administrator of an NFT -/// @dev NFTs assigned to zero addresses are considered invalid, and queries -/// about them do throw. On a EIP-721 transfer event emit, any proposed Administrator should be set to address(0) -/// @param _tokenId The identifier for an NFT -function proposedAdministratorOf(uint256 _tokenId) external view returns (address); - -/// @notice ownerOf(NFT) can cancel Administrator change. After a period of time, you might allow anyone (or old administrator) -/// to cancel the change, as this blocks payment delinquency -> repossess logic. You can call this function as long as -/// Administrator change was not accepted/finalized by new Administrator -/// @dev throw if tokenId doesn't have an Administrator change. -/// also implement logic for who/when can Administrator change be canceled -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function cancelAdministratorChange(uint256 _tokenId, string calldata _extradata) external; - -// STEP 2: New Administrator, accept Administrator change, possible to cancel - -/// @notice new Administrator accept a change of Administrator of an NFT -/// @dev Throws unless msg.sender is proposedAdministratorOf this NFT. you may clear proposedAdministratorOf data -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function acceptAdministratorChange(uint256 _tokenId, string calldata _extradata) external; - -/// @notice once the Administrator change is accepted as a new Administrator, this function needs to return their address -/// @dev on an EIP-721 transfer, this address remains, as the transfer is in progress. -/// @param _tokenId The identifier for an NFT -function pendingAdministratorOf(uint256 _tokenId) external view returns(address); - -/// @notice allow a cancellation of the processing/pending Administrator change -/// @dev determine who is allowed to cancel this change, up to implementor, -/// msg.sender should be pendingAdministratorOf in most cases, but perhaps can be canceled by anyone after a period of time -/// throw if there's no pendingAdministratorOf -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function cancelAdministratorChangeAccept(uint256 _tokenId, string calldata _extradata) external; - -// STEP 3: Finalize Administrator change, cannot cancel. This occurs after the "real world legal steps" to change Administrator have taken place off-chain. - -/// @notice finalize the change in Administrator of the NFT -/// @dev throws if msg.sender is not pendingAdministratorOf. now administratorOf(NFT) will return the new Administrator address, you may clear pendingAdministratorOf() -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function finishAdministratorChange(uint256 _tokenId, string calldata _extradata) external; -``` - -#### Operating Agreement Updates - -``` -/// @dev emit this event if there's a successful call of initOperatingAgreementChange -/// @param _proposer is the msg.sender of the init -event OperatingAgreementChangeInit(uint256 indexed _tokenId, address indexed _proposer, string _updatedAgreementHash, string _extradata); - -/// @dev emit this event if there's a successful call of cancelOperatingAgreementChange -/// also emit this if there is a owner proposed change but the owner transfers to new owner -/// also emit if there is a Administrator proposed change, but the Administrator transfers to a new owner -event OperatingAgreementChangeCancel(uint256 indexed _tokenId, address indexed _proposer, string _extradata); - -// @dev emit if there's a successful call of finishOperatingAgreementChange -// @param _proposer is the msg.sender of the init -// @param _agreer is the msg.sender of the finishOperatingAgreementChange -// @param _updatedAgreementHash must be == the _updatedAgreementHash from the OperatingAgreementChangeInit event -event OperatingAgreementChangeFinish(uint256 indexed _tokenId, address indexed _proposer, address indexed _agreer, string _updatedAgreementHash, string _extradata); - -/// @notice query the current operating agreement, this is recommended to be an IPFS link -/// or some other URL or reference. see best practices for NFT metadata. -/// @dev if tokenId doesn't exist, throw -/// @param _tokenId The identifier for an NFT -/// @returns some string, likely to an external resource as a legal document is very expensive to store on-chain -function operatingAgreementOf(uint256 _tokenId) external view returns(string); - -/// @notice propose a change to the operating agreement -/// @dev throw is msg.sender is not ownerOf(NFT) or is not administratorOf(NFT). update needs to be accepted by the other party -/// (owner if Administrator proposed, Administrator if owner proposed) -/// @param _tokenId The identifier for an NFT -/// @param _updatedAgreementHash Is the proposed new agreement -/// @param _extradata An optional field for metadata -function initOperatingAgreementChange(uint256 _tokenId, string calldata _updatedAgreementHash, string calldata _extradata) external; - -/// @notice view a pending change for _tokenId -/// @dev if _tokenId doesn't exist then throw, if there is not an update proposed then throw -/// also note that if the Administrator has made a proposal, but the Administrator is changed to a new Administrator (finished change) -/// then any update proposals should be nulled -/// also note that is the owner has made a proposal, but the owner changes (EIP-721 transfer), then any update proposals should be nulled as well -/// @param _tokenId The identifier for an NFT -/// @returns _proposer is either the Administrator or owner who proposed the update -/// @returns _updatedAgreementHash is the proposed agreement to be update -function pendingOperatingAgreementOf(uint256 _tokenId) external view returns(address _proposer, string _updatedAgreementHash); - -/// @notice allow proposer to cancel agreement -/// @dev throw if tokenId doesn't exist, or if there is no proposal for this agreement, or if msg.sender was not the proposer of the change -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function cancelOperatingAgreementChange(uint256 _tokenId, string calldata _extradata) external; - -/// @notice accept a change to the operating agreement -/// @dev msg.sender must be ownerOf(NFT) if AdministratorOf(NFT) proposed change, OR must be AdministratorOf(NFT) if ownerOf(NFT) proposed change, ELSE throw -/// also throw if _updatedAgreementHash does not match the originally proposed agreement -/// @param _tokenId The identifier for an NFT -/// @param _updatedAgreementHash hash that MUST match the prior submitted change suggestion hash to confirm the agreement -/// @param _extradata An optional field for metadata -function finishOperatingAgreementChange(uint256 _tokenId, string calldata _updatedAgreementHash, string calldata _extradata) external; -``` - -#### Payments - -``` -/// @dev emit this event when initPayment is called successfully -event PaymentInit(uint256 indexed _tokenId, address indexed _administrator, address indexed _paymentToken, uint256 _amount, bool _decreaseAmtOwed, uint256 _oldestTimestamp, string _extradata); - -/// @dev This event emits when a finishPayment is successful. The payment MUST be completed for this event to emit, and -/// this event MUST emit if the payment is completed and funds are transferred from msg.sender address -event PaymentFinish(uint256 indexed _tokenId, address indexed _administrator, address indexed _paymentToken, uint256 _amount, string _extradata); - -/// @notice Administrator assess payment on the NFT owner -/// @dev throw if msg.sender is not the current administratorOf(_tokenId), you may store payments by token to be paid, and you may sum the values of all other -/// prior unpaid payments. store the timestamp of the oldest unpaid payment for this payment type, if this is a new token with no prior payments -/// then store block.timestamp for this payment, this will be used for delinquent payments -/// if payments are _decreaseAmtOwed, the total amount owed can never be negative, if this will happen null payment storage for this _paymentToken -/// if a new Administrator is adding/decreasing a payment token outstanding by an old Administrator, overwrite the Administrator name in storage -/// you might want to change the timestamp of old Administrator payments to be a new/current timestamp -/// @param _tokenId The identifier for an NFT -/// @param _paymentToken the EIP-20 token address to define the payment -/// @param _amount the amount of EIP-20 token payment due -/// @param _decreaseAmtOwed this decreases any payment by the _amount, this can be used to revise or adjust down any payments, basically adding a negative sign to _amount -/// @param _extradata An optional field for metadata -function initPayment(uint256 _tokenId, address _paymentToken, uint256 _amount, bool _decreaseAmtOwed, string calldata _extradata) external; - -/// @notice query an existing unpaid payment -/// @dev queries about non-existent _tokenId, _token pairings are considered invalid, and queries -/// about them do throw. This can include already completed payments (where the blockchain reference is deleted) -/// @param _tokenId The identifier for an NFT -/// @param _paymentToken the EIP-20 token address to define the payment -/// @returns _amount the amount of _paymentToken that needs to be paid to fulfill payment -/// @returns _receiver is the Administrator of the specific tokenId, who will receive payment -/// @returns _timestamp of the oldest non-completed payment in this _paymentToken -function pendingPaymentOf(uint256 _tokenId, address _paymentToken) external view returns (uint256 _amount, address _receiver, uint256 _timestamp); - -/// @notice NFT owner make payment that was invoiced by Administrator -/// @dev do NOT throw if msg.sender isn't ownerOf(_tokenId), anyone can fulfill a payment if they desire -/// allow msg.sender to make a partial payment for an amount, if _amount > total payments outstanding, then pay their total, do not pay extra -/// also note the Administrator the payment is supposed to go to, we recommend ignoring payments to an old Administrator, or throwing -/// @param _tokenId The identifier for an NFT -/// @param _paymentToken The EIP-20 token address to define the payment -/// @param _amount The amount user desires to pay -/// @param _extradata An optional field for metadata -function finishPayment(uint256 _tokenId, address _paymentToken, uint256 _amount, string calldata _extradata) external; - -/// @notice query if a payment is delinquent, a payment considered to be delinquent is defined by implementor -/// it's recommended that a payment cannot be delinquent if there is a proposedAdministratorOf || pendingAdministratorOf -/// if payments are delinquent, then the underlying physical asset is liable to be repossessed -/// we recommend ignoring payments to an old Administrator in a delinquency determination -/// @dev queries about non-existent payments are considered invalid and queries about them do throw. -/// this can include already completed payments (where the blockchain reference is deleted) -/// @param _tokenId The identifier for an NFT -/// @param _paymentToken The EIP-20 token address to define the payment -/// @returns false if there is no delinquent payment for this payment id, EIP-20 payment token, true if there is -function paymentIsDelinquent(uint256 _tokenId, address _paymentToken) external view returns (bool); -``` - -#### Repossess/Foreclosure - -``` -/// @dev this event emits when a initRepossess is successful, only emit if initRepossess is successful -event RepossessInit(uint256 indexed _tokenId, address indexed _administrator, address _token, string _extradata); - -/// @dev this event emits when a cancelRepossess is successful, only emit if there is successful canceled repossess -event RepossessCancel(uint256 indexed _tokenId, address indexed _administrator, string _extradata); - -/// @dev this event emits when finishRepossess is successfully called, only emit if there is a successfully finished repossess -/// @param _amount is the amount of ETH paid back to user after a repossess is complete -event RepossessFinish(uint256 indexed _tokenId, address indexed _administrator, uint256 _amount, string _extradata); - -/// @dev this event emits when claimRepossess is called, only emit if it's successfully called -/// @param _amount is the amount of ETH sent to the user -event RepossessClaim(uint256 indexed _tokenId, address indexed _owner, uint256 _amount) - -/// @notice if this function returns true, then the underlying physical asset has been repossessed -/// due to the user not paying required fees for the asset. if true, then the asset only contains -/// the second return value in wei, and this amount of ETH can be withdrawn at any time by ownerOf NFT. -/// @param _tokenId The identifier for an NFT -/// @returns _repossessed true if the asset has finished repossessing, else false -/// @returns _amount, the amount of ETH that was returned after the repossess took place, zero if claimed (below) -function isRepossessed(uint256 _tokenId) external view returns(bool _repossessed, uint256 _amount); - -/// @notice initialize repossess underlying RWA asset that backs NFT if a payment is delinquent -/// @dev paymentIsDelinquent(_tokenId, _token) must return true, else this function reverts. -/// is msg.sender is not the Administrator, this function reverts. -/// if the Administrator is in transfer state, we recommend not letting a repossess happen as it could be malicious -/// (see paymentIsDelinquent logic) -/// however we also recommend forcing Administrator transfers to happen within a certain period of time to prevent griefing -/// and allowing a repossess after a certain time has elapsed without an Administrator accepting the proposed Administrator change -/// @param _tokenId The identifier for an NFT -/// @param _token The payment token that a payment was delinquent -/// @param _extradata An optional field for metadata -function initRepossess(uint256 _tokenId, address _token, string calldata _extradata) external; - -/// @notice view if a payment has a repossess pending on the asset, this will warn any prospective buyer that the asset is in question -/// @dev true if there is a pending repossess, false otherwise, if tokenId doesn't exist, then throw -/// @param _tokenId The identifier for an NFT -/// @returns true if there is a repossess pending, false if not -function pendingRepossess(uint256 _tokenID) external view returns(bool); - -/// @notice cancel a prior initialized repossess, Administrator can cancel for any reason -/// @dev tokenId must have an initialized repossess, and msg.sender must be administratorOf(tokenId) or function reverts -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function cancelRepossess(uint256 _tokenId, string calldata _extradata) external; - -/// @notice finish repossessing underlying physical asset that backs NFT, underlying asset sold/auctioned at fair value -/// and function is payable so that Administrator can send remaining auction proceeds to contract *in ETH* -/// @dev if msg.sender is not the Administrator, this function reverts -/// @param _tokenId The identifier for an NFT -/// @param _extradata An optional field for metadata -function finishRepossess(uint256 _tokenId, string calldata _extradata) external payable; - -/// @notice after an asset is repossessed, ownerOf(NFT) can claim the proceeds of the repossession -/// @dev throw is ownerOf(_tokenId) != msg.sender, otherwise send amount of ETH from finishRepossess() to caller -/// @param _tokenId The identifier for an NFT -function claimRepossess(uint256 _tokenId) external; -``` - -## Rationale - -### Introduction - -Real world assets operate in messy, non-deterministic environments. Because of this, validating the true state of an asset can be murky, expensive, or time-consuming. For example, in the U.S., change of property ownership is usually recorded at the County Recorder’s office, sometimes using pen and paper. It would be infeasible to continuously update this manual record every time an NFT transaction occurs on the blockchain. Additionally, since real world property rights are enforced by the court of law, it is essential that property ownership be documented in such a way that courts are able to interpret and enforce ownership if necessary. - -For these reasons, it is necessary to have a trusted party tasked with the responsibility of ensuring the state of the on-chain property accurately mirrors its physical counterpart. By having an Administrator for the property who issues a legally-binding digital representation of the physical property, we are able to solve for both the atomic transfer of the property rights with the transfer of the NFT, as well as institute a seamless process for making the necessary payments and filings associated with property ownership. - -There are various ways to meet the legal requirements of this standard, especially considering different property ownership laws and regulations between various jurisdictions. Therefore, we do not prescribe a specific legal structure. However, an example structure implemented by Klasma Inc. for property tokenization in the U.S. is provided in the [Reference Implementation](#reference-implementation). - -### Guiding Objectives - -We have designed this EIP to achieve three primary objectives necessary for creating an NFT representation of physical real estate: - -#### 1. Real Estate NFTs are universally transferable - -A key aspect to private property is the right to transfer ownership to any legal person or entity that has the capacity to own that property. Therefore, an NFT representation of physical property should maintain that universal freedom of transfer. - -#### 2. All rights associated with property ownership are maintained - -The rights associated with private property ownership are the right to hold, occupy, rent, alter, resell, or transfer the property. It is essential that these same rights are maintained in an NFT representation of real estate. - -#### 3. Property rights are transferred atomically with the transfer of the NFT. - -Token ownership on any blockchain is atomic with the transfer of the digital token. To ensure the digital representation of a physical property is able to fully integrate the benefits of blockchain technology, it is essential the rights associated with the property are passed atomically with the transfer of the digital token representation. For this reason, the legal ownership of the property must be packaged in such a way that allows for the atomic transfer of rights with the transfer of the digital token. - -This EIP proposes a way to mesh the transfers of off-chain assets (in a legal sense) with on-chain Ethereum blockchain transfers and state-transitions. The following section specifies the technological and legal requirements needed to accomplish this. - -### Administrator, Legal Entity, & Administrator Transferability - -The Administrator is the legal owner of a singular legal entity special purpose vehicle (SPV) which holds the title to an individual physical property and issues the corresponding NFT. It is the duty of the Administrator to make all necessary filings and payments for the legal entity and corresponding property (e.g. tax filings, property tax payments & required utility payments). In addition to ensuring the property is in good standing with the government, the Administrator is tasked with ensuring the rightful occupancy of the home, signing documents on behalf of the NFT owner when necessary, and posting up-to-date information regarding the condition of the property to the NFT. - -Within the token components exists a function to transfer the Administrator of the asset. Any owner of the physical property NFT can transfer legal ownership of the asset by calling this function. This action kicks off the pen and paper process whereby the Administrator changes ownership of the legal entity. This process also allows the NFT owner to bridge the asset off-chain by transferring ownership of the entity to themselves and taking legal ownership of the title to the property. - -Trusted roles are antithetical to crypto. Ideally, the Administrator role eventually becomes obsolete. However, currently, this function is essential to providing enforceable property rights to the NFT owner. There are various avenues to explore for making the role of Administrators trust-minimized, including reputation systems and financial/game theory incentives, but they are outside the scope of this standard. - -### Hashed Operating Agreement - -The hashed operating agreement is a legal document issued by the Administrator that contains the rights to the physical property, as well as terms and conditions. This document is hashed to the NFT to ensure the immutability of these rights. In order to make changes to this contract, either the Administrator or NFT owner must submit a change request via the legal entity and it must be approved by the corresponding side. Upon transfer of the NFT, these legal rights are transferred to the new owner. - -As this standard is adopted and developed further, we anticipate a collection of particular operating requirements to become common across different Administrators and asset types. These requirements will be componentized into referenceable hashes that can be easily understood and verified when interacting with a digital representation of a property. - -### Payment Function - -Payments are a necessary part of owning real estate. Owners must pay for property taxes, basic utilities, and other required costs. Because the Administrator is the legal owner of the entity that holds the title to the property, it is the Administrator’s responsibility to make any and all required payments. Administrators will issue all anticipated fees and payments to the NFT owner using the payment function. Owners are then able to make the necessary payments for the property directly through their NFT. Administrators are strongly encouraged to submit any bills or invoices in “paper form” using the `_extradata` field and attach a link to a PDF or other documentation, as well as group payments by time period to ensure simplicity for the owners. - -### Repossession Function - -If the payments mentioned in the previous section go unpaid, the property is at risk of having silent liens placed against it or in extreme circumstances, being repossessed by the state. In order to ensure Administrators are able to provide reliable and clean transfers of a property, the Administrator must have the means to make payments without being subject to payment liability risk. If the Administrator makes payments for a property on behalf of a NFT owner and then needs to be reimbursed, the Administrator is exposed to risk of financial loss in the event the NFT owner sells the NFT without reimbursing the Administrator. For this reason all payments need to be funded directly from the NFT owner through the smart contract. - -If the NFT owner fails to pay the invoice, the Administrator has the right to repossess the property, sell it in order to generate the required funds for payment, and then replace the physical asset backing the original NFT with the remaining funds from the sale in ETH. Any proceeds from the repossession/foreclosure sale must be converted to ETH in order to be returned to the original owner. It is up to the implementer to determine what criterion for payment delinquency triggers a repossession. - -## Backwards Compatibility - -Although this standard is backwards compatible with EIP-721, there are important security and implementation considerations to take into account before any smart contract integration. These considerations primarily surround the built-in payment function of the token. While treating NFTs under this standard as identical to EIP-721 NFTs is technically possible, we recommend considering additional logic to support fee payment and recognize any unpaid obligations. - -Specific applications that incorporate these NFTs can suffer losses from incorrect implementation. See `Integration Checks and Considerations` for more details. - -## Reference Implementation - -This section details an implementation of the legal standard by Klasma Inc. specifically for property tokenization in the U.S. in the 2022 regulatory environment. - -![Sample Corporate Structure Image](../assets/eip-6065/corporate-structure.png) - -The Klasma Inc. legal structure for U.S. real estate and property is as follows: - -* Klasma Inc., a parent company and property Administrator, owns a bankruptcy remote LLC for each individual property they act as Administrator for. -* This LLC owns a DAO LLC, which issues the NFT for the property and holds the title and deed to the property. -* This structure enables the following three outcomes: - 1. Homeowners are shielded from any financial stress or bankruptcy their physical asset Administrator encounters. In the event of an Administrator bankruptcy or dissolution the owner of the NFT is entitled to transfer of the DAO LLC, or the sale and distribution of proceeds from the property. - 2. Transfer of the rights to the property are atomic with the transfer of the NFT. The rights to the property are issued and controlled by a DAO LLC, a legally recognized entity that can be algorithmically managed, (e.g. managed by smart contract). This enables the enforceable rights to the physical property to be passed digitally with the transfer of the NFT without having to update the legal owner of the property with each transfer. - 3. Each real estate NFT is universally transferable. The DAO LLC will be taxed as a corporation to limit any pass-through tax benefits that could put the token at risk of being deemed a security in the U.S. The DAO LLC will always operate in a tax neutral or negative status thus not requiring any tax payments to be made on behalf of the LLC. Additionally, it is important to note that the NFT associated with a particular property merely provides a means of digital transfer for the private ownership rights to the property. Therefore, there is no action by the Administrator that could increase the value of the asset, ensuring the NFT is deemed a commodity, the same as any other home or property. - -## Security Considerations - -This standard attempts to strike a balance between the crypto ethos of “code is law” and the understanding that a stolen home with no possibility of recourse for the owner is a non-starter for almost all users. On a risk-adjusted basis, the benefits of using a decentralized finance protocol are unlikely to offset the possibility of a catastrophic loss of the property via a protocol exploit. Losing your home in a DeFi hack is unacceptable. - -On the other hand, granting the Administrator full control of the NFTs through backdoor access to the smart contracts is also unacceptable. Given the complex nature of many exploits, requiring Administrators to act as judge and jury in defining a hack and determining the rightful owner is sub-optimal. The following sections define how private key loss and protocol hacks are addressed, as well as provide important checks and considerations for smart contract integrations, particularly for lending protocols. - -### Private Key Loss and Theft - -While DeFi protocol hacks leave an immutable trail on-chain, private key hacks do not. A private key transferring an asset legitimately or maliciously looks identical in any blockchain analysis. As such, Administrators should not be tasked with arbitrating or remedying private key hacks or loss. - -Secure private key storage is a fundamental requirement to be able to interact with the crypto ecosystem. Users unable to do so should either pay for an NFT custody solution, or refrain from owning digital assets altogether. - -### Protocol Hacks and Exploits - -A protocol hack or exploit occurs within the confines of a smart contract integration and thus is reviewable on-chain, via specific transaction hashes and block explorer level evidence. A respectable Administrator should lay out their process for classifying and addressing protocol exploits in the Operating Agreement. - -To remedy a hack, the Administrator may issue a charge against the NFT to the new owner of the NFT for the full market value of the underlying asset via the `initPayment()` function. If the new owner does nothing, the Administrator will repossess this asset and return it to the original owner or protocol. To contest the classification of a hack, the new owner may start the `initAdministratorChange()` workflow to change the Administrator or self-custody the asset. Since all Administrators must be legal entities, the original owner may now bring this case to the traditional legal system if they desire. - -Through leveraging the existing payment and Administrator change flow, a safety mechanism against protocol exploits is provided without inserting a smart contract backdoor. In the event that an exploit is contestable (e.g. a hack, versus an economic exploit, versus a well timed trade), this system provides an avenue for the new asset owner to make her case through the jurisdictional legal system. - -### Integration Checks and Considerations - -The following are checks and recommendations for protocols integrating NFTs under this standard. These are of particular relevance to applications which lend against any asset utilizing this standard. - -* Lending protocol integrators are recommended to pay any payments on behalf of their NFT depositors by calling `finishPayment()` and adding this balance to their users outstanding debt position. This avoids repossession by the Administrator, which may lead to loans becoming undercollateralized or undefined behavior in the protocol. -* Before accepting NFT deposits, a protocol integrator should check any `pendingPaymentOf()` the asset. A protocol may decide not accept an asset until all payments are cleared, or mark down the fair market value of the asset. -* Protocol integrators should also check if the function `paymentIsDelinquent()` returns `true` for any payments. If so, they should reject the asset as it is at risk of being repossessed. -* Protocol integrators are recommended to implement a time-delay before performing irreversible actions. This is to protect against future to-be-assessed payments that may occur if a hacked NFT is deposited into the protocol. - * For example, a protocol should implement a waiting period before issuing stablecoins as part of a collateralized mortgage on the NFT. If another DeFi protocol can be hacked, and a hacker can immediately run to a different protocol to receive an 80% LTV loan on the asset, it is likely that this second protocol will take a loss when this hack is resolved by the Administrator billing the NFT via `initPayment()` for it’s entire market value. Now this second protocol is stuck with valueless collateral, but already issued a 80% LTV loan. - * Because there is no standardized waiting period, DeFi protocols should specifically whitelist Administrator addresses for deposit into their protocols. Administrators may have specialized descriptor smart contracts to give an upper bound on wait-time recommendations. For example, Administrator A could state that one should wait 7 days for any of their assets, and after 7 days it is guaranteed that there will be no `initPayments()` for any prior malicious activity or hacks of the asset, and the asset is now safe to accept as collateral as its value is simply value(asset) without any possible liabilities. -* It is recommended that protocol integrators expose `initAdministratorChange()` logic in their smart contracts in order to change the Administrator in the future, if necessary. -Protocol integrators may decide to only accept assets with certain operating agreement hashes, viewable by calling `operatingAgreementOf()`. This ensures that all legal clauses and terms in this off-chain contract have been reviewed prior. -* More advanced protocol integrators may decide to expose `initOperatingAgreementChange()` functionality, in case a better legal agreement standard is designed in order to upgrade their assets to the best possible protections. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6065.md diff --git a/EIPS/eip-6066.md b/EIPS/eip-6066.md index 096b84e19cd2b4..103a4eadc35d31 100644 --- a/EIPS/eip-6066.md +++ b/EIPS/eip-6066.md @@ -1,127 +1,7 @@ --- eip: 6066 -title: Signature Validation Method for NFTs -description: A way to verify signatures when the signing entity is an EIP-721 or EIP-1155 NFT -author: Jack Boyuan Xu (@boyuanx) -discussions-to: https://ethereum-magicians.org/t/eip-6066-signature-validation-method-for-nfts/ -status: Draft -type: Standards Track category: ERC -created: 2022-11-29 -requires: 721, 1155, 1271, 5750 +status: Moved --- -## Abstract - -While **E**xternally **O**wned **A**ccounts can validate signed messages with `ecrecover()` and smart contracts can validate signatures using specifications outlined in [EIP-1271](./eip-1271.md), currently there is no standard method to create or validate signatures made by NFTs. We propose a standard way for anyone to validate whether a signature made by an NFT is valid. This is possible via a modified signature validation function originally found in [EIP-1271](./eip-1271.md): `isValidSignature(tokenId, hash, data)`. - -## Motivation - -With billions of ETH in trading volume, the **N**on-**F**ungible **T**oken standard has exploded into tremendous popularity in recent years. Despite the far-reaching implications of having unique tokenized items on-chain, NFTs have mainly been used to represent artwork in the form of avatars or profile pictures. While this is certainly not a trivial use case for the [EIP-721](./eip-721.md) & [EIP-1155](./eip-1155.md) token standards, we reckon more can be done to aid the community in discovering alternative uses for NFTs. - -One of the alternative use cases for NFTs is using them to represent offices in an organization. In this case, tying signatures to transferrable NFTs instead of EOAs or smart contracts becomes crucial. Suppose there exists a DAO that utilizes NFTs as badges that represent certain administrative offices (i.e., CEO, COO, CFO, etc.) with a quarterly democratic election that potentially replaces those who currently occupy said offices. If the sitting COO has previously signed agreements or authorized certain actions, their past signatures would stay with the EOA who used to be the COO instead of the COO's office itself once they are replaced with another EOA as the new COO-elect. Although a multisig wallet for the entire DAO is one way to mitigate this problem, often it is helpful to generate signatures on a more intricate level so detailed separation of responsibilities are established and maintained. It is also feasible to appoint a smart contract instead of an EOA as the COO, but the complexities this solution brings are unnecessary. If a DAO uses ENS to establish their organizational hierarchy, this proposal would allow wrapped ENS subdomains (which are NFTs) to generate signatures. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -``` -pragma solidity ^0.8.0; - -interface IEIP6066 { - /** - * @dev MUST return if the signature provided is valid for the provided tokenId and hash - * @param tokenId Token ID of the signing NFT - * @param hash Hash of the data to be signed - * @param data OPTIONAL arbitrary data that may aid verification - * - * MUST return the bytes4 magic value 0xdff13226 when function passes. - * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) - * MUST allow external calls - * - */ - function isValidSignature( - uint256 tokenId, - bytes32 hash, - bytes calldata data - ) external view returns (bytes4 magicValue); -} -``` - -`isValidSignature` can call arbitrary methods to validate a given signature. - -This function MAY be implemented by [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md) compliant contracts that desire to enable its token holders to sign messages using their NFTs. Compliant callers wanting to support contract signatures MUST call this method if the signer is the holder of an NFT ([EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md)). - -## Rationale - -We have purposefully decided to not include a signature generation standard in this proposal as it would restrict flexibility of such mechanism, just as [EIP-1271](./eip-1271.md) does not enforce a signing standard for smart contracts. We also decided to reference Gnosis Safe's contract signing approach as it is both simplistic and proven to be adequate. The `bytes calldata data` parameter is considered optional if extra data is needed for signature verification, also conforming this EIP to [EIP-5750](./eip-5750.md) for future-proofing purposes. - -## Backwards Compatibility - -This EIP is incompatible with previous work on signature validation as it does not validate any cryptographically generated signatures. Instead, signature is merely a boolean flag indicating consent. This is consistent with Gnosis Safe's contract signature implementation. - -## Reference Implementation - -Example implementation of an [EIP-721](./eip-721.md) compliant contract that conforms to [EIP-6066](./eip-6066.md) with a custom signing function: - -``` -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./interfaces/draft-IEIP6066.sol"; - -contract EIP6066Reference is ERC721, IEIP6066 { - bytes4 public constant MAGICVALUE = 0xdff13226; - bytes4 public constant BADVALUE = 0xffffffff; - - mapping(uint256 => mapping(bytes32 => bool)) internal _signatures; - - error ENotTokenOwner(); - - /** - * @dev Checks if the sender owns NFT with ID tokenId - * @param tokenId Token ID of the signing NFT - */ - modifier onlyTokenOwner(uint256 tokenId) { - if (ownerOf(tokenId) != _msgSender()) revert ENotTokenOwner(); - _; - } - - constructor(string memory name_, string memory symbol_) - ERC721(name_, symbol_) - {} - - /** - * @dev SHOULD sign the provided hash with NFT of tokenId given sender owns said NFT - * @param tokenId Token ID of the signing NFT - * @param hash Hash of the data to be signed - */ - function sign(uint256 tokenId, bytes32 hash) - external - onlyTokenOwner(tokenId) - { - _signatures[tokenId][hash] = true; - } - - /** - * @dev MUST return if the signature provided is valid for the provided tokenId, hash, and optionally data - */ - function isValidSignature(uint256 tokenId, bytes32 hash, bytes calldata data) - external - view - override - returns (bytes4 magicValue) - { - // The data parameter is unused in this example - return _signatures[tokenId][hash] ? MAGICVALUE : BADVALUE; - } -} -``` - -## Security Considerations - -The revokable nature of contract-based signatures carries over to this EIP. Developers and users alike should take it into consideration. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6066.md diff --git a/EIPS/eip-6093.md b/EIPS/eip-6093.md index b932c65be7c375..53de6ceec958ac 100644 --- a/EIPS/eip-6093.md +++ b/EIPS/eip-6093.md @@ -1,370 +1,7 @@ --- eip: 6093 -title: Custom errors for commonly-used tokens -description: Lists custom errors for common token implementations -author: Ernesto García (@ernestognw), Francisco Giordano (@frangio), Hadrien Croubois (@Amxx) -discussions-to: https://ethereum-magicians.org/t/eip-6093-custom-errors-for-erc-tokens/12043 -status: Draft -type: Standards Track category: ERC -created: 2022-12-06 -requires: 20, 721, 1155 +status: Moved --- -## Abstract - -This EIP defines a standard set of custom errors for commonly-used tokens, which are defined as [EIP-20](./eip-20.md), [EIP-721](./eip-721.md), and [EIP-1155](./eip-1155.md) tokens. - -Ethereum applications and wallets have historically relied on revert reason strings to display the cause of transaction errors to users. Recent Solidity versions offer rich revert reasons with error-specific decoding (sometimes called "custom errors"). This EIP defines a standard set of errors designed to give at least the same relevant information as revert reason strings, but in a structured and expected way that clients can implement decoding for. - -## Motivation - -Since the introduction of Solidity custom errors in v0.8.4, these have provided a way to show failures in a more expressive and gas efficient manner with dynamic arguments, while reducing deployment costs. - -However, [EIP-20](./eip-20.md), [EIP-721](./eip-721.md), [EIP-1155](./eip-1155.md) were already finalized when custom errors were released, so no errors are included in their specification. - -Standardized errors allow users to expect more consistent error messages across applications or testing environments, while exposing pertinent arguments and overall reducing the need of writing expensive revert strings in the deployment bytecode. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -The following errors were designed according to the criteria described in [Rationale](#rationale). - -This EIP defines standard errors that may be used by implementations in certain scenarios, but does not specify whether implementations should revert in those scenarios, which remains up to the implementers, unless a revert is mandated by the corresponding EIPs. - -The names of the error arguments are defined in the [Parameter Glossary](#parameter-glossary), and MUST be used according to those definitions. - -### [EIP-20](./eip-20.md) - -#### `ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)` - -Indicates an error related to the current `balance` of a `sender`. -Used in transfers. - -- MUST be used when `balance` is less than `needed`. -- MUST NOT be used if `balance` is greater than or equal to `needed`. - -#### `ERC20InvalidSender(address sender)` - -Indicates a failure with the token `sender`. -Used in transfers. - -- MUST be used for disallowed transfers from the zero address. -- MUST NOT be used for approval operations. -- MUST NOT be used for balance or allowance requirements. - - Use `ERC20InsufficientBalance` or `ERC20InsufficientAllowance` instead. - -#### `ERC20InvalidReceiver(address receiver)` - -Indicates a failure with the token `receiver`. -Used in transfers. - -- MUST be used for disallowed transfers to the zero address. -- MUST be used for disallowed transfers to non-compatible addresses (eg. contract addresses). -- MUST NOT be used for approval operations. - -#### `ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)` - -Indicates a failure with the `spender`'s `allowance`. -Used in transfers. - -- MUST be used when `allowance` is less than `needed`. -- MUST NOT be used if `allowance` is greater than or equal to `needed`. - -#### `ERC20InvalidApprover(address approver)` - -Indicates a failure with the `approver` of a token to be approved. -Used in approvals. - -- MUST be used for disallowed approvals from the zero address. -- MUST NOT be used for transfer operations. - -#### `ERC20InvalidSpender(address spender)` - -Indicates a failure with the `spender` to be approved. -Used in approvals. - -- MUST be used for disallowed approvals to the zero address. -- MUST be used for disallowed approvals to the owner itself. -- MUST NOT be used for transfer operations. - - Use `ERC20InsufficientAllowance` instead. - -### [EIP-721](./eip-721.md) - -#### `ERC721InvalidOwner(address sender, uint256 tokenId, address owner)` - -Indicates an error related to the ownership over a particular token. -Used in transfers. - -- MUST be used when `sender` is not `owner`. -- MUST NOT be used for approval operations. - -#### `ERC721InvalidSender(address sender)` - -Indicates a failure with the token sender. -Used in transfers. - -- MUST be used for disallowed transfers from the zero address. -- MUST NOT be used for approval operations. -- MUST NOT be used for ownership or approval requirements. - - Use `ERC721InvalidOwner` or `ERC721InsufficientApproval` instead. - -#### `ERC721InvalidReceiver(address receiver)` - -Indicates a failure with the token receiver. -Used in transfers. - -- MUST be used for disallowed transfers to the zero address. -- MUST be used for disallowed transfers to non-`ERC721TokenReceiver` contracts or those that reject a transfer. (eg. returning an invalid response in `onERC721Received`). -- MUST NOT be used for approval operations. - -#### `ERC721InsufficientApproval(address operator, uint256 tokenId)` - -Indicates a failure with the `operator`'s approval. -Used in transfers. - -- MUST be used when operator `isApprovedForAll(owner, operator)` is false. -- MUST be used when operator `getApproved(tokenId)` is not `operator`. - -#### `ERC721InvalidApprover(address approver)` - -Indicates a failure with the `owner` of a token to be approved. -Used in approvals. - -- MUST be used for disallowed approvals from the zero address. -- MUST NOT be used for transfer operations. - -#### `ERC721InvalidOperator(address operator)` - -Indicates a failure with the `operator` to be approved. -Used in approvals. - -- MUST be used for disallowed approvals to the zero address. -- MUST be used for disallowed approvals to the owner itself. -- MUST NOT be used for transfer operations. - - Use `ERC721InsufficientApproval` instead. - -### [EIP-1155](./eip-1155.md) - -#### `ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId)` - -Indicates an error related to the current `balance` of a sender. -Used in transfers. - -- MUST be used when `balance` is less than `needed` for a `tokenId`. -- MUST NOT be used if `balance` is greater than or equal to `needed` for a `tokenId`. - -#### `ERC1155InvalidSender(address sender)` - -Indicates a failure with the token sender. -Used in transfers. - -- MUST be used for disallowed transfers from the zero address. -- MUST NOT be used for approval operations. -- MUST NOT be used for balance or allowance requirements. - - Use `ERC1155InsufficientBalance` or `ERC1155InsufficientApproval` instead. - -#### `ERC1155InvalidReceiver(address receiver)` - -Indicates a failure with the token receiver. -Used in transfers. - -- MUST be used for disallowed transfers to the zero address. -- MUST be used for disallowed transfers to non-`ERC1155TokenReceiver` contracts or those that reject a transfer. (eg. returning an invalid response in `onERC1155Received`). -- MUST NOT be used for approval operations. - -#### `ERC1155InsufficientApproval(address operator, uint256 tokenId)` - -Indicates a failure with the `operator`'s approval in a transfer. -Used in transfers. - -- MUST be used when operator `isApprovedForAll(owner, operator, tokenId)` is false. - -#### `ERC1155InvalidApprover(address approver)` - -Indicates a failure with the `approver` of a token to be approved. -Used in approvals. - -- MUST be used for disallowed approvals from the zero address. -- MUST NOT be used for transfer operations. - -#### `ERC1155InvalidOperator(address operator)` - -Indicates a failure with the `operator` to be approved. -Used in approvals. - -- MUST be used for disallowed approvals to the zero address. -- MUST be used for disallowed approvals to the owner itself. -- MUST NOT be used for transfer operations. - - Use `ERC1155InsufficientApproval` instead. - -#### `ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength)` - -Indicates an array length mismatch between `ids` and `values` in a `safeBatchTransferFrom` operation. -Used in batch transfers. - -- MUST be used only if `idsLength` is different from `valuesLength` - -### Parameter Glossary - -| Name | Description | -| ----------- | --------------------------------------------------------------------------- | -| `sender` | Address whose tokens are being transferred. | -| `balance` | Current balance for the interacting account. | -| `needed` | Minimum amount required to perform an action. | -| `receiver` | Address to which tokens are being transferred. | -| `spender` | Address that may be allowed to operate on tokens without being their owner. | -| `allowance` | Amount of tokens a `spender` is allowed to operate with. | -| `approver` | Address initiating an approval operation. | -| `tokenId` | Identifier number of a token. | -| `owner` | Address of the current owner of a token. | -| `operator` | Same as `spender`. | -| `*Length` | Array length for the prefixed parameter. | - -### Error additions - -Any addition to this EIP or implementation-specific errors (such as extensions) SHOULD follow the guidelines presented in the [rationale](#rationale) section to keep consistency. - -## Rationale - -The chosen objectives for a standard for token errors are to provide context about the error, and to make moderate use of meaningful arguments (to maintain the code size benefits with respect to strings). - -Considering this, the error names are designed following a basic grammatical structure based on the standard actions that can be performed on each token and the [subjects](#actions-and-subjects) involved. - -### Actions and subjects - -The main actions that can be performed within a token are: - -- **Transfer**: An operation in which a _sender_ moves to a _receiver_ any number of tokens (fungible _balance_ and/or non-fungible _token ids_). -- **Approval**: An operation in which an _approver_ grants any form of _approval_ to an _operator_. - -The subjects outlined above are expected to exhaustively represent _what_ can go wrong in a token transaction, deriving a specific error by adding an [error prefix](#error-prefixes). - -Note that the action is never seen as the subject of an error. Additionally, the token itself is not seen as the subject of an error but rather the context in which it happens, as identified in the domain. - -If a subject is called different on a particular token standard, the error should be consistent with the standard's naming convention. - -### Error prefixes - -An error prefix is added to a subject to derive a concrete error condition. -Developers can think about an error prefix as the _why_ an error happened. - -A prefix can be `Invalid` for general incorrectness, or more specific like `Insufficient` for amounts. - -### Domain - -Each error's arguments may vary depending on the token domain. If there are errors with the same name and different arguments, the Solidity compiler currently fails with a `DeclarationError`. - -An example of this is: - -```solidity -InsufficientApproval(address spender, uint256 allowance, uint256 needed); -InsufficientApproval(address operator, uint256 tokenId); -``` - -For that reason, a domain prefix is proposed to avoid declaration clashing, which is the name of the ERC and its corresponding number appended at the beginning. - -Example: - -```solidity -ERC20InsufficientApproval(address spender, uint256 allowance, uint256 needed); -ERC721InsufficientApproval(address operator, uint256 tokenId); -``` - -### Arguments - -The selection of arguments depends on the subject involved, and it should follow the order presented below: - -1. _Who_ is involved with the error (eg. `address sender`) -2. _What_ failed (eg. `uint256 allowance`) -3. _Why_ it failed, expressed in additional arguments (eg. `uint256 needed`) - -A particular argument may fall into overlapping categories (eg. _Who_ may also be _What_), so not all of these will be present but the order shouldn't be broken. - -Some tokens may need a `tokenId`. This is suggested to include at the end as additional information instead of as a subject. - -### Error grammar rules - -Given the above, we can summarize the construction of error names with a grammar that errors will follow: - -``` -(); -``` - -Where: - -- _Domain_: `ERC20`, `ERC721` or `ERC1155`. Although other token standards may be suggested if not considered in this EIP. -- _ErrorPrefix_: `Invalid`, `Insufficient`, or another if it's more appropriate. -- _Subject_: `Sender`, `Receiver`, `Balance`, `Approver`, `Operator`, `Approval` or another if it's more appropriate, and must make adjustments based on the domain's naming convention. -- _Arguments_: Follow the [_who_, _what_ and _why_ order](#arguments). - -## Backwards Compatibility - -Tokens already deployed rely mostly on revert strings and make use of `require` instead of custom errors. Even most of the newly deployed tokens since Solidity's v0.8.4 release inherit from implementations using revert strings. - -This EIP can not be enforced on non-upgradeable already deployed tokens, however, these tokens generally use similar conventions with small variations such as: - -- including/removing the [domain](#domain). -- using different [error prefixes](#error-prefixes). -- including similar [subjects](#actions-and-subjects). -- changing the grammar order. - -Upgradeable contracts MAY be upgraded to implement this EIP. - -Implementers and DApp developers that implement special support for tokens that are compliant with this EIP, SHOULD tolerate different errors emitted by non-compliant contracts, as well as classic revert strings. - -## Reference Implementation - -### Solidity - -```solidity -pragma solidity ^0.8.4; - -/// @title Standard ERC20 Errors -/// @dev See https://eips.ethereum.org/EIPS/eip-20 -/// https://eips.ethereum.org/EIPS/eip-6093 -interface ERC20Errors { - error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); - error ERC20InvalidSender(address sender); - error ERC20InvalidReceiver(address receiver); - error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); - error ERC20InvalidApprover(address approver); - error ERC20InvalidSpender(address spender); -} - -/// @title Standard ERC721 Errors -/// @dev See https://eips.ethereum.org/EIPS/eip-721 -/// https://eips.ethereum.org/EIPS/eip-6093 -interface ERC721Errors { - error ERC721InvalidOwner(address sender, uint256 tokenId, address owner); - error ERC721InvalidSender(address sender); - error ERC721InvalidReceiver(address receiver); - error ERC721InsufficientApproval(address operator, uint256 tokenId); - error ERC721InvalidApprover(address approver); - error ERC721InvalidOperator(address operator); -} - -/// @title Standard ERC1155 Errors -/// @dev See https://eips.ethereum.org/EIPS/eip-1155 -/// https://eips.ethereum.org/EIPS/eip-6093 -interface ERC1155Errors { - error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); - error ERC1155InvalidSender(address sender); - error ERC1155InvalidReceiver(address receiver); - error ERC1155InsufficientApproval(address operator, uint256 tokenId); - error ERC1155InvalidApprover(address approver); - error ERC1155InvalidOperator(address operator); - error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); -} -``` - -## Security Considerations - -There are no known signature hash collisions for the specified errors. - -Tokens upgraded to implement this EIP may break assumptions in other systems relying on revert strings. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6093.md diff --git a/EIPS/eip-6105.md b/EIPS/eip-6105.md index d673f53dd439bc..7abf309a49fe7e 100644 --- a/EIPS/eip-6105.md +++ b/EIPS/eip-6105.md @@ -1,291 +1,7 @@ --- eip: 6105 -title: Marketplace Extension for EIP-721 -description: Adds a basic marketplace functionality to EIP-721. -author: 5660-eth (@5660-eth), Silvere Heraudeau (@lambdalf-dev), Martin McConnell (@offgridgecko), Abu , Wizard Wang -discussions-to: https://ethereum-magicians.org/t/eip6105-no-intermediary-nft-trading-protocol/12171 -status: Draft -type: Standards Track category: ERC -created: 2022-12-02 -requires: 165, 721, 2981 +status: Moved --- -## Abstract - -Add a basic marketplace functionality to [EIP-721](./eip-721.md) -to enable non-fungible token trading without relying on an intermediary trading platform. - - -## Motivation - -Most current NFT trading relies on an NFT trading platform acting as an intermediary, which has the following problems: - -1. Security concerns arise from authorization via the `setApprovalForAll` function. The permissions granted to NFT trading platforms expose unnecessary risks. Should a problem occur with the trading platform contract, it would result in significant losses to the industry as a whole. Additionally, if a user has authorized the trading platform to handle their NFTs, it allows a phishing scam to trick the user into signing a message that allows the scammer to place an order at a low price on the NFT trading platform and designate themselves as the recipient. This can be difficult for ordinary users to guard against. -2. High trading costs are a significant issue. On one hand, as the number of trading platforms increases, the liquidity of NFTs becomes dispersed. If a user needs to make a deal quickly, they must authorize and place orders on multiple platforms, which increases the risk exposure and requires additional gas expenditures for each authorization. For example, taking BAYC as an example, with a total supply of 10,000 and over 6,000 current holders, the average number of BAYC held by each holder is less than 2. While `setApprovalForAll` saves on gas expenditure for pending orders on a single platform, authorizing multiple platforms results in an overall increase in gas expenditures for users. On the other hand, trading service fees charged by trading platforms must also be considered as a cost of trading, which are often much higher than the required gas expenditures for authorization. -3. Aggregators provide a solution by aggregating liquidity, but the decision-making process is centralized. Furthermore, as order information on trading platforms is off-chain, the aggregator's efficiency in obtaining data is affected by the frequency of the trading platform's API and, at times, trading platforms may suspend the distribution of APIs and limit their frequency. -4. The project parties' copyright tax income is dependent on centralized decision-making by NFT trading platforms. Some trading platforms disregard the interests of project parties and implement zero copyright tax, which is a violation of their interests. -5. NFT trading platforms are not resistant to censorship. Some platforms have delisted a number of NFTs and the formulation and implementation of delisting rules are centralized and not transparent enough. In the past, some NFT trading platforms have failed and wrongly delisted certain NFTs, leading to market panic. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL -NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", -and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 -and RFC 8174. - -Compliant contracts MUST implement the following interface: - -```solidity -interface IERC6105 { - - /// @notice Emitted when a token is listed for sale or delisted. - /// @dev The zero price indicates that the token is not for sale - /// The zero expires indicates that the token is not for sale - /// @param tokenId - identifier of the token being listed - /// @param from - address of who is selling the token - /// @param to - address of who this listing is for, - /// can be address zero for a public listing, - /// or non zero address for a private listing - /// @param price - the price the token is being sold for - /// @param expires - UNIX timestamp, the buyer could buy the token before expires - event LogUpdateListing(uint256 indexed tokenId, address indexed from, address indexed to, uint256 price, uint64 expires); - - /// @notice Emitted when a token that was listed for sale is being purchased. - /// @param tokenId - identifier of the token being purchased - /// @param from - address of who is selling the token - /// @param to - address of who is buying the token - /// @param price - the price the token is being sold for - event LogPurchased(uint256 indexed tokenId, address indexed from, address indexed to, uint256 price); - - /// @notice Create or update a listing for `tokenId` - /// Setting `buyer` to the NULL address will create a public listing - /// `price` MUST NOT be set to zero - /// @param tokenId - identifier of the token being listed - /// @param price - the price the token is being sold for - /// @param expires - UNIX timestamp, the buyer could buy the token before expires - /// @param to - optional address of who this listing is for, - /// can be address zero for a public listing, - /// or non zero address for a private listing - /// Requirements: - /// - `tokenId` must exist - /// - Caller must be owner, authorised operators or approved address of the token - /// - `price` must not be zero - /// - Must emit a {LogUpdateListing} event. - function listItem(uint256 tokenId, uint256 price, uint64 expires, address to) external; - - /// @notice Removes the listing for `tokenId` - /// @param tokenId - identifier of the token being delisted - /// Requirements: - /// - `tokenId` must exist and be listed for sale - /// - Caller must be owner, authorised operators or approved address of the token - /// - Must emit a {LogUpdateListing} event - function delistItem(uint256 tokenId) external; - - /// @notice Purchases the listed token `tokenId` - /// @param tokenId - identifier of the token being purchased - /// Requirements: - /// - `tokenId` must exist and be listed for sale - /// - Caller must be able to pay the listed price for `tokenId` - /// - Must emit a {LogPurchased} event. - function buyItem(uint256 tokenId) external payable; - - /// @notice Returns the listing for `tokenId` - /// @dev The zero price indicates that the token is not for sale - /// The zero expires indicates that the token is not for sale - /// The zero address indicates that the token is for a public listing - /// @param tokenId - identifier of the token whose listing is being queried - /// @return the specified listing (price, expires, intended recipient) - function getListing(uint256 tokenId) external view returns (uint256, uint64, address); -} -``` - -The `listItem(uint256 tokenId, uint256 price, uint64 expires, address to)` function MAY be implemented as `public` or `external`.And the `price` in this function MUST NOT be set to zero. - -The `delistItem(uint256 tokenId)` function MAY be implemented as `public` or `external`. - -The `buyItem(uint256 tokenId)` function MUST be implemented as `payable` and MAY be implemented as `public` or `external`. - -The `getListing(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `LogUpdateListing` event MUST be emitted when a token is listed for sale or delisted. - -The `LogPurchased` event MUST be emitted when a token is traded. - -The `supportsInterface` method MUST return `true` when called with `0x6de8e04d`. - -## Rationale - -Out of consideration for the safety and efficiency of buyer' assets, it does not provide bidding functions and auction functions, but only adds listing funcitons. - -The `price` in the `listItem` function cannot be set to zero. Firstly, it is a rare occurrence for a caller to set the price to 0, and when it happens, it is often due to an operational error which can result in loss of assets. Secondly, a caller needs to spend gas to call this function, so if he can set the token price to 0, his income would be actually negative at this time, which does not conform to the concept of 'economic man' in economics. Additionally, a token price of 0 indicates that the item is not for sale, making the reference implementation more concise. - -Setting `expires` in the `listItem` function allows callers to better manage their listings. If a listing expires automatically, the token owner will no longer need to manually `delistItem`, thus saving gas. - -## Backwards Compatibility - -This standard is compatible with [EIP-721](./eip-721.md) and [EIP-2981](./eip-2981.md). - -## Reference Implementation - -```solidity - // SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.8; -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/token/common/ERC2981.sol"; -import "./IERC6105.sol"; - -contract ERC6105 is ERC721, ERC2981, IERC6105 { - - /// @dev A structure representing a listed token - /// The zero price indicates that the token is not for sale - /// The zero expires indicates that the token is not for sale - /// @param price - the price the token is being sold for - /// @param expires - UNIX timestamp, the buyer could buy the token before expires - /// @param to - address of who this listing is for, - /// can be address zero for a public listing, - /// or non zero address for a private listing - struct Listing { - uint256 price; - uint64 expires; - address to; - } - - // Mapping from token Id to listing index - mapping(uint256 => Listing) private _listings; - - constructor(string memory name_, string memory symbol_) - ERC721(name_, symbol_) - { - } - - /// @notice Create or update a listing for `tokenId` - /// Setting `buyer` to the NULL address will create a public listing - /// `price` MUST NOT be set to zero - /// @param tokenId - identifier of the token being listed - /// @param price - the price the token is being sold for - /// @param expires - UNIX timestamp, the buyer could buy the token before expires - /// @param to - optional address of who this listing is for, - /// can be address zero for a public listing, - /// or non zero address for a private listing - function listItem (uint256 tokenId, uint256 price, uint64 expires, address to) external virtual { - address tokenOwner = ownerOf(tokenId); - require(price > 0,"ERC6105: token sale price MUST NOT be set to zero"); - require(_isApprovedOrOwner(_msgSender(), tokenId),"ERC6105: caller is not owner nor approved"); - - _listItem(tokenId, price, tokenOwner, expires, to); - } - - /// @notice Removes the listing for `tokenId` - /// @param tokenId - identifier of the token being delisted - function delistItem(uint256 tokenId) external virtual { - require(_isApprovedOrOwner(_msgSender(), tokenId),"ERC6105: caller is not owner nor approved"); - require(_isForSale(tokenId), "ERC6105: invalid listing" ); - - _removeListing(tokenId); - } - - /// @notice Purchases the listed token `tokenId` - /// @param tokenId - identifier of the token being purchased - function buyItem(uint256 tokenId) external virtual payable { - address tokenOwner = ownerOf(tokenId); - address buyer = msg.sender; - uint256 value = msg.value; - uint256 price = _listings[tokenId].price; - require(_isForSale(tokenId), "ERC6105: invalid listing"); - require( - buyer == _listings[tokenId].to || - _listings[tokenId].to == address(0), - "ERC6105: invalid sale address" - ); - require(value == price, "ERC6105: incorrect price"); - - _transfer(tokenOwner, buyer, tokenId); - emit LogPurchased(tokenId, tokenOwner, buyer, price); - - /// @dev Handle royalties - (address royaltyRecipient, uint256 royalties) = royaltyInfo(tokenId, msg.value); - - uint256 payment = msg.value - royalties; - _processEthPayment(royalties, royaltyRecipient); - _processEthPayment(payment, tokenOwner); - } - - /// @notice Returns the listing for `tokenId` - /// @dev The zero price indicates that the token is not for sale - /// The zero expires indicates that the token is not for sale - /// The zero address indicates that the token is for a public listing - /// @param tokenId - identifier of the token whose listing is being queried - /// @return the specified listing (price, expires, intended recipient) - function getListing(uint256 tokenId) external view virtual returns (uint256, uint64, address) { - uint256 price = _listings[tokenId].price; - uint64 expires = _listings[tokenId].expires; - address to = _listings[tokenId].to; - return (price, expires, to); - } - - ///@dev check if the token `tokenId` is for sale - function _isForSale(uint256 tokenId) internal virtual returns(bool){ - if(_listings[tokenId].price > 0 && _listings[tokenId].expires >= block.timestamp){ - return true; - } - else{ - return false; - } - } - - /// @dev Create or update a listing for `tokenId` - /// Setting `buyer` to the NULL address will create a public listing - /// `price` MUST NOT be set to zero - /// @param tokenId - identifier of the token being listed - /// @param price - the price the token is being sold for - /// @param tokenOwner - current owner of the token - /// @param expires - UNIX timestamp, the buyer could buy the token before expires - /// @param to - optional address of who this listing is for, - /// can be address zero for a public listing, - /// or non zero address for a private listing - function _listItem(uint256 tokenId, uint256 price, address tokenOwner, uint64 expires, address to) internal virtual { - _listings[tokenId].price = price; - _listings[tokenId].expires = expires; - _listings[tokenId].to = to; - emit LogUpdateListing(tokenId, tokenOwner, to, price, expires); - } - - /// @dev Removes the listing for `tokenId` - /// @param tokenId - identifier of the token being delisted - function _removeListing(uint256 tokenId) internal virtual { - address tokenOwner = ownerOf(tokenId); - delete _listings[tokenId]; - emit LogUpdateListing(tokenId, tokenOwner, address(0), 0, 0); - } - - /// @dev Processes an ether of `amount` payment to `recipient`. - /// @param amount - the amount to send - /// @param recipient - the payment recipient - function _processEthPayment(uint256 amount, address recipient) internal virtual { - (bool success,) = payable(recipient).call{value: amount}(""); - require(success, "Ether Transfer Fail"); - } - - /// @dev See {IERC165-supportsInterface}. - function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981) returns (bool) { - return interfaceId == type(IERC6105).interfaceId || super.supportsInterface(interfaceId); - } - - function _beforeTokenTransfer(address from, address to, uint256 tokenId, uint256 batchSize) internal virtual override{ - super._beforeTokenTransfer(from, to, tokenId, batchSize); - if(_isForSale(tokenId)){ - delete _listings[tokenId]; - emit LogUpdateListing(tokenId, to, address(0), 0, 0); - } - } -} -``` - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6105.md diff --git a/EIPS/eip-6110.md b/EIPS/eip-6110.md index 64dfa7a9302234..e6328d399ea94d 100644 --- a/EIPS/eip-6110.md +++ b/EIPS/eip-6110.md @@ -2,17 +2,18 @@ eip: 6110 title: Supply validator deposits on chain description: Provides validator deposits as a list of deposit operations added to the Execution Layer block -author: Mikhail Kalinin (@mkalinin), Danny Ryan (@djrtwo) +author: Mikhail Kalinin (@mkalinin), Danny Ryan (@djrtwo), Peter Davies (@petertdavies) discussions-to: https://ethereum-magicians.org/t/eip-6110-supply-validator-deposits-on-chain/12072 -status: Draft +status: Review type: Standards Track category: Core created: 2022-12-09 +requires: 7685 --- ## Abstract -Appends validator deposits to the Execution Layer block structure. This shifts responsibliity of deposit inclusion and validation to the Execution Layer and removes the need for deposit (or `eth1data`) voting from the Consensus Layer. +Appends validator deposits to the Execution Layer block structure. This shifts responsibility of deposit inclusion and validation to the Execution Layer and removes the need for deposit (or `eth1data`) voting from the Consensus Layer. Validator deposits list supplied in a block is obtained by parsing deposit contract log events emitted by each deposit transaction included in a given block. @@ -30,13 +31,16 @@ Advantages of in-protocol deposit processing consist of but are not limit to the ## Specification -### Constants +### Execution Layer + +#### Constants | Name | Value | Comment | | - | - | - | |`FORK_TIMESTAMP` | *TBD* | Mainnet | +|`DEPOSIT_REQUEST_TYPE` | `b'0'` | The [EIP-7685](./eip-7685.md) request type byte for deposit operation | -### Configuration +#### Configuration | Name | Value | Comment | | - | - | - | @@ -44,11 +48,11 @@ Advantages of in-protocol deposit processing consist of but are not limit to the `DEPOSIT_CONTRACT_ADDRESS` parameter **MUST** be included into client software binary distribution. -### Definitions +#### Definitions * **`FORK_BLOCK`** -- the first block in a blockchain with the `timestamp` greater or equal to `FORK_TIMESTAMP`. -### Deposit +#### Deposit The structure denoting the new deposit operation consists of the following fields: @@ -58,103 +62,94 @@ The structure denoting the new deposit operation consists of the following field 4. `signature: Bytes96` 5. `index: uint64` -RLP encoding of deposit structure **MUST** be computed in the following way: - -```python -rlp_encoded_deposit = RLP([ - RLP(pubkey), - RLP(withdrawal_credentials), - RLP(amount), - RLP(signature), - RLP(index) -]) -``` - -### Block structure - -Beginning with the `FORK_BLOCK`, the block body **MUST** be appended with a list of deposit operations. RLP encoding of an extended block body structure **MUST** be computed as follows: +Deposits are a type of [EIP-7685](./eip-7685.md) request, therefore the encoding of the structure must be computed using the `DEPOSIT_REQUEST_TYPE` byte: ```python -block_body_rlp = RLP([ - rlp_encoded_field_0, - ..., - # Latest block body field before `deposits` - rlp_encoded_field_n, - - RLP([rlp_encoded_deposit_0, ..., rlp_encoded_deposit_k]) +deposit_request_rlp = DEPOSIT_REQUEST_TYPE + rlp([ + pubkey, + withdrawal_credentials, + amount, + signature, + index ]) ``` -Beginning with the `FORK_BLOCK`, the block header **MUST** be appended with the new **`deposits_root`** field. The value of this field is the trie root committing to the list of deposits in the block body. **`deposits_root`** field value **MUST** be computed as follows: +The encoded deposits will be included in the header and body as generic requests following the format defined by EIP-7685. -```python -def compute_trie_root_from_indexed_data(data): - trie = Trie.from([(i, obj) for i, obj in enumerate(data)]) - return trie.root - -block.header.deposits_root = compute_trie_root_from_indexed_data(block.body.deposits) -``` - -### Block validity +#### Block validity Beginning with the `FORK_BLOCK`, client software **MUST** extend block validity rule set with the following conditions: -1. Value of **`deposits_root`** block header field equals to the trie root committing to the list of deposit operations contained in the block. To illustrate: - -```python -def compute_trie_root_from_indexed_data(data): - trie = Trie.from([(i, obj) for i, obj in enumerate(data)]) - return trie.root - -assert block.header.deposits_root == compute_trie_root_from_indexed_data(block.body.deposits) -``` +1. The list of deposit operations contained in the block **MUST** be equivalent to the list of log events emitted by each deposit transaction of the given block. -2. The list of deposit operations contained in the block **MUST** be equivalent to the list of log events emitted by each deposit transaction of the given block, respecting the order of transaction inclusion. To illustrate: +2. Each deposit accumulated in the block must appear in the EIP-7685 requests list in the order they appear in the logs. To illustrate: ```python -def parse_deposit_data(deposit_event_data): bytes[] +def parse_deposit_data(deposit_event_data) -> bytes[]: """ Parses Deposit operation from DepositContract.DepositEvent data """ pass -def little_endian_to_uint64(data: bytes): uint64 +def little_endian_to_uint64(data: bytes) -> uint64: return uint64(int.from_bytes(data, 'little')) -class Deposit(object): - pubkey: Bytes48 - withdrawal_credentials: Bytes32 - amount: uint64 - signature: Bytes96 - index: uint64 - -def event_data_to_deposit(deposit_event_data): Deposit - deposit_data = parse_deposit_data(deposit_event_data) - return Deposit( - pubkey=Bytes48(deposit_data[0]), - withdrawal_credentials=Bytes32(deposit_data[1]), - amount=little_endian_to_uint64(deposit_data[2]), - signature=Bytes96(deposit_data[3]), - index=little_endian_to_uint64(deposit_data[4]) - ) +def event_data_to_deposit_request_rlp(deposit_event_data) -> bytes: + deposit_data = parse_deposit_data(deposit_event_data) + pubkey = Bytes48(deposit_data[0]) + withdrawal_credentials = Bytes32(deposit_data[1]) + amount = little_endian_to_uint64(deposit_data[2]) + signature = Bytes96(deposit_data[3]) + index = little_endian_to_uint64(deposit_data[4]) + + return DEPOSIT_REQUEST_TYPE + rlp([ + pubkey, withdrawal_credentials, amount, signature, index + ]) # Obtain receipts from block execution result receipts = block.execution_result.receipts # Retrieve all deposits made in the block -expected_deposits = [] +expected_deposit_requests = [] for receipt in receipts: for log in receipt.logs: if log.address == DEPOSIT_CONTRACT_ADDRESS: - deposit = event_data_to_deposit(log.data) - expected_deposits.append(deposit) + deposit_request_rlp = event_data_to_deposit_request_rlp(log.data) + expected_deposit_requests.append(deposit_request_rlp) + +deposit_requests = [req for req in block.body.requests if req[:1] == DEPOSIT_REQUEST_TYPE] -# Compare retrieved deposits to the list in the block body -assert block.body.deposits == expected_deposits +# Compare retrieved deposits to the list of deposit operations in the block +assert deposit_requests == expected_deposit_requests ``` A block that does not satisfy the above conditions **MUST** be deemed invalid. +### Consensus layer + +Consensus layer changes can be summarized into the following list: + +1. `ExecutionPayload` is extended with a new `deposit_receipts` field to accommodate deposit operations list. +2. `BeaconState` is appended with `deposit_receipts_start_index` used to switch from the former deposit mechanism to the new one. +3. As a part of transition logic a new beacon block validity condition is added to constrain the usage of `Eth1Data` poll. +4. A new `process_deposit_receipt` function is added to the block processing routine to handle `deposit_receipts` processing. + +Detailed consensus layer specification can be found in following documents: + +* [`eip6110/beacon-chain.md`](https://github.com/ethereum/consensus-specs/blob/2660af05390aa61f06142e1c6311a3a3c633f720/specs/_features/eip6110/beacon-chain.md) -- state transition. +* [`eip6110/validator.md`](https://github.com/ethereum/consensus-specs/blob/2660af05390aa61f06142e1c6311a3a3c633f720/specs/_features/eip6110/validator.md) -- validator guide. +* [`eip6110/fork.md`](https://github.com/ethereum/consensus-specs/blob/2660af05390aa61f06142e1c6311a3a3c633f720/specs/_features/eip6110/fork.md) -- EIP activation. + +#### Validator index invariant + +Due to the large follow distance of `Eth1Data` poll an index of a new validator assigned during deposit processing remains the same across different branches of a block tree, i.e. with existing mechanism `(pubkey, index)` cache utilized by consensus layer clients is re-org resilient. The new deposit machinery breaks this invariant and consensus layer clients will have to deal with a fact that a validator index becomes fork dependent, i.e. a validator with the same `pubkey` can have different indexes in different block tree branches. + +Detailed [analysis](../assets/eip-6110/pubkey_to_index_cache_analysis.md) shows that `process_deposit` function is *the only* place requiring a fork dependent `(pubkey, index)` cache. + +#### `Eth1Data` poll deprecation + +Consensus layer clients will be able to remove `Eth1Data` poll mechanism in an uncoordinated fashion once transition period is finished. The transition period is considered as finished when a network reaches the point where `state.eth1_deposit_index == state.deposit_receipts_start_index`. + ## Rationale ### `index` field @@ -177,15 +172,37 @@ This EIP introduces backwards incompatible changes to the block structure and bl ### Data complexity -At the time of writing this document, the total number of submitted deposits is 478,402 which is 88MB of deposit data. Assuming frequency of deposit transactions remains the same, historic chain data complexity induced by this EIP can be estimated as 50MB per year which is negligible in comparison to other historic data. +At the time of the latest update of this document, the total number of submitted deposits is 824,598 which is 164MB of deposit data. Assuming frequency of deposit transactions remains the same, historic chain data complexity induced by this EIP can be estimated as 60MB per year which is negligible in comparison to other historical data. -After the beacon chain launch in December 2020, the biggest observed spike in a number of submitted deposits was on March 15, 2022. More than 6000 deposit transactions were submitted during 24 hours which on average is less than 1 deposit, or 192 bytes of data, per block. +After the beacon chain launch in December 2020, the biggest observed spike in a number of submitted deposits was on June 1, 2023. More than 12,000 deposit transactions were submitted during 24 hours which on average is less than 2 deposit, or 384 bytes of data, per block. Considering the above, we conclude that data complexity introduced by this proposal is negligible. ### DoS vectors -With 1 ETH as a minimum deposit amount, the lowest cost of a byte of deposit data is 1 ETH/192 ~ 5,208,333 Gwei. This is several orders of magnitude higher than the cost of a byte of transaction's calldata, thus adding deposit operations to a block does not increase Execution Layer DoS attack surface. +The code in the deposit contract costs 15,650 gas to run in the cheapest case (when all storage slots are hot and only a single leaf has to be modified). Some deposits in a batch deposit are more expensive, but those costs, when amortized over a large number of deposits, are small at around ~1,000 gas per deposit. Under current gas pricing rules an extra 6,900 gas is charged to make a `CALL` that transfers ETH, this is a case of inefficient gas pricing and may be reduced in the future. For future robustness the beacon chain needs to be able to withstand 1,916 deposits in a 30M gas block (15,650 gas per deposit). The limit under current rules is less than 1,271 deposits in a 30M gas block. + +#### Execution layer + +With 1 ETH as a minimum deposit amount, the lowest cost of a byte of deposit data is 1 ETH/192 ~ 5,208,333 Gwei. This is several orders of magnitude higher than the cost of a byte of transaction's calldata, thus adding deposit operations to a block does not increase DoS attack surface of the execution layer. + +#### Consensus layer + +The most consuming computation of deposit processing is signature verification. Its complexity is bounded by a maximum number of deposits per block which is around 1,271 with 30M gas block at the moment. So, it is ~1,271 signature verifications which is roughly ~1.2 seconds of processing (without optimisations like batched signatures verification). An attacker would need to spend 1,000 ETH to slow down block processing by a second which isn't sustainable and viable attack long term. + +An optimistically syncing node may be susceptible to a more severe attack scenario. Such a node can't validate a list of deposits provided in a payload which makes it possible for attacker to include as many deposits as the limitation allows to. Currently, it is 8,192 deposits (1.5MB of data) with rough processing time of 8s. Considering an attacker would need to sign off on this block with its crypto economically viable signature (which requires building an alternative chain and feeding it to a syncing node), this attack vector is not considered as viable as it can't result in a significant slow down of a sync process. + +### Optimistic sync + +An optimistically syncing node have to rely on the honest majority assumption. That is, if adversary is powerful enough to finalize a deposit sequence, a syncing node will have to apply these deposits disregarding the validity of deposit receipts with respect to the execution of a given block. Thus, an adversary that can finalize an invalid chain can also convince an honest node to accept fake deposits. The same is applicable to the validity of execution layer world state today and a new deposit processing design is within boundaries of the existing security model in that regard. + +Online nodes can't be tricked into this situation because their execution layer validates supplied deposits with respect to the block execution. + +### Weak subjectivity period + +This EIP removes a hard limit on a number of deposits per epoch and makes a block gas limit the only limitation on this number. That is, the limit on deposits per epoch shifts from `MAX_DEPOSITS * SLOTS_PER_EPOCH = 512` to `max_deposits_per_30m_gas_block * SLOTS_PER_EPOCH ~ 32,768` at 30M gas block (we consider `max_deposits_per_30m_gas_block = 1,024` for simplicity). + +This change affects a number of top ups per epoch which is one of the inputs to the weak subjectivity period computation. One can top up own validators to instantly increase a portion of stake it owns with respect to those validators that are leaking. [The analysis](../assets/eip-6110/ws_period_analysis.md) does not demonstrate significant reduction of a weak subjectivity period sizes. Moreover, such an attack is not considered as viable because it requires a decent portion of stake to be burned as one of preliminaries. ## Copyright diff --git a/EIPS/eip-6120.md b/EIPS/eip-6120.md index 39c470c2a8cfb6..daeb828b493590 100644 --- a/EIPS/eip-6120.md +++ b/EIPS/eip-6120.md @@ -1,844 +1,7 @@ --- eip: 6120 -title: Universal Token Router -description: A single router contract enables tokens to be sent to application contracts in the transfer-and-call manner instead of approve-then-call. -author: Zergity (@Zergity), Ngo Quang Anh (@anhnq82), BerlinP (@BerlinP) -discussions-to: https://ethereum-magicians.org/t/eip-6120-universal-token-router/12142 -status: Review -type: Standards Track category: ERC -created: 2022-12-12 -requires: 20, 721, 1014, 1155 +status: Moved --- -## Abstract - -ETH is designed with transfer-and-call as the default behavior in a transaction. Unfortunately, [EIP-20](./eip-20.md) is not designed with that pattern in mind and newer standards are too late to replace it as the de facto standard. - -Application and router contracts have to use the approve-then-call pattern which costs additional `n*m*l` `allow` (or `permit`) transactions, for `n` contracts, `m` tokens, and `l` user addresses. These allowance transactions not only cost enormous amounts of user gas, waste network storage and throughput, and worsen user experience, but also put users at serious security risks as they often have to approve unaudited, unverified and upgradable proxy contracts. - -The Universal Token Router (UTR) separates the token allowance from the application logic, allowing any token to be spent in a contract call the same way with ETH, without approving any other application contracts. - -Tokens approved to the Universal Token Router can only be spent in transactions directly signed by their owner, and they have clearly visible token transfer behavior, including token types (ETH, [EIP-20](./eip-20.md), [EIP-721](./eip-721.md) or [EIP-1155](./eip-1155.md)), `amountInMax`, `amountOutMin`, and `recipient`. - -The Universal Token Router contract is counter-factually deployed using [EIP-1014](./eip-1014.md) at a single address across all EVM-compatible networks, so new token contracts can pre-configure it as a trusted spender and no approval transaction is necessary ever again. - -## Motivation - -When users approve their tokens to a contract, they trust that: - -* it only spends the tokens with their permission (from `msg.sender` or `ecrecover`) -* it does not use `delegatecall` (e.g. upgradable proxies) - -By performing the same security conditions above, the Universal Token Router can be shared by all applications, saving `(n-1)*m*l` approval transactions for old tokens and **ALL** approval transactions for new tokens. - -Before this EIP, when users sign transactions to spend their approved tokens, they trust the front-end code entirely to construct those transactions honestly and correctly. This puts them at great risk of phishing sites. - -The Universal Token Router function arguments can act as a manifest for users when signing a transaction. With the support from wallets, users can see and review their expected token behavior instead of blindly trusting the application contracts and front-end code. Phishing sites will be much easier to detect and avoid for users. - -Application contracts follow this standard can use the Universal Token Router to have the following benefits: - -* Safely share the user token allowance with all other applications. -* Freely update their helper contract logic. -* Save development and security audit costs on router contracts. - -The Universal Token Router promotes the **security-by-result** model in decentralized applications instead of **security-by-process**. By directly querying token balance change for output verification, user transactions can be secured even when interacting with erroneous or malicious contracts. With non-token results, application helper contracts can provide additional result-checking functions for UTR's output verification. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -The main interface of the UTR contract: - -```solidity -interface IUniversalTokenRouter { - function exec( - Output[] memory outputs, - Action[] memory actions - ) external payable; - ... -} -``` - -### Output Verification - -`Output` defines the expected token balance change for verification. - -```solidity -struct Output { - address recipient; - uint eip; // token standard: 0 for ETH or EIP number - address token; // token contract address - uint id; // token id for EIP-721 and EIP-1155 - uint amountOutMin; -} -``` - -Token balances of the `recipient` address are recorded at the beginning and the end of the `exec` function for each item in `outputs`. Transaction will revert with `INSUFFICIENT_OUTPUT_AMOUNT` if any of the balance changes are less than its `amountOutMin`. - -A special id `ID_721_ALL` is reserved for EIP-721, which can be used in output actions to verify the total amount of all ids owned by the `recipient` address. - -```solidity -ID_721_ALL = keccak256('UniversalTokenRouter.ID_721_ALL') -``` - -### Action - -`Action` defines the token inputs and the contract call. - -```solidity -struct Action { - Input[] inputs; - uint flags; - address code; // contract code address - bytes data; // contract input data -} -``` - -`flags` can take any number of the following bit flags: - -* `0x1 = ACTION_IGNORE_ERROR`: any contract call failure will be ignored. -* `0x2 = ACTION_RECORD_CALL_RESULT`: the contract call result will be recorded in a `bytes` for subsequent actions. -* `0x4 = ACTION_INJECT_CALL_RESULT`: the last call result `bytes` recorded will be injected to the last empty `bytes` param of the contract function `data`. - -### Input - -`Input` defines the input token to transfer or prepare before the action contract is executed. - -```solidity -struct Input { - uint mode; - address recipient; - uint eip; // token standard: 0 for ETH or EIP number - address token; // token contract address - uint id; // token id for EIP721 and EIP1155 - uint amountInMax; - uint amountSource; // where to get the actual amountIn -} -``` - -`mode` can takes one of the following values: - -* `0 = TRANSFER_FROM_SENDER`: the token will be transferred from `msg.sender` to `recipient`. -* `1 = TRANSFER_FROM_ROUTER`: the token will be transferred from `this` UTR contract to `recipient`. -* `2 = TRANSFER_CALL_VALUE`: the token amount will be passed to the action as the call `value`. -* `4 = IN_TX_PAYMENT`: the token will be allowed to be spent in this transaction by calling `UTR.pay`. -* `8 = ALLOWANCE_BRIDGE`: the token will be transferred from `msg.sender` to `this` UTR contract and is allowed to be spent in this transaction. - -`amountSource` defines how the actual token `amountIn` is acquired from: - -* `0 = AMOUNT_EXACT`: the `amountInMax` value is used. -* `1 = AMOUNT_ALL`: the entire balance of the sender (`msg.sender` or `this`) is used. -* otherwise, extracts the `uint256` value starting from the `amountSource`-th byte of the last recorded call result `bytes`. This value is unpredictable if there's no prior action with the `ACTION_RECORD_CALL_RESULT` flag. - -`amountIn` MUST NOT be greater than `amountInMax`, otherwise, the transaction will be reverted with `EXCESSIVE_INPUT_AMOUNT`. - -#### Payment In Callback - -`IN_TX_PAYMENT` is used for application contracts that use the transfer-in-callback pattern. (E.g. flashloan contracts, Uniswap/v3-core, etc.) - -```solidity -interface IUniversalTokenRouter { - ... - - function pay( - address sender, - address recipient, - uint eip, - address token, - uint id, - uint amount - ) external; -} -``` - -For each `Input` with `IN_TX_PAYMENT` mode, at most `amountIn` of the token is allowed to be transferred from `msg.sender` to the `recipient` by calling `UTR.pay` from anywhere in the same transaction. - -``` -UTR - | - | IN_TX_PAYMENT - | (payments pended for UTR.pay) - | - | Application Contracts -action.code.call ---------------------> | - | -UTR.pay <----------------------- (call) | - | - | <-------------------------- (return) | - | - | (clear all pending payments) - | -END -``` - -#### Allowance Bridge - -`ALLOWANCE_BRIDGE` is the compatibility mode for application contracts that require token approval directly from `msg.sender`. - -For each `Input` with `ALLOWANCE_BRIDGE` mode: - -* an `amountIn` of token is transferred from `msg.sender` to `this` UTR contract. -* the `recipient` address is allowed to spend the token from `this` UTR contract. - -Before the end of the `exec` function: - -* all allowances are revoked. -* all left-over tokens are transferred back to `msg.sender`. - -### Usage Samples - -#### `UniswapRouter.swapExactTokensForTokens` - -Legacy function: - -```solidity -UniswapV2Router01.swapExactTokensForTokens( - uint amountIn, - uint amountOutMin, - address[] calldata path, - address to, - uint deadline -) -``` - -`UniswapV2Helper01.swapExactTokensForTokens` is a modified version of it without the token transfer part. - -This transaction is signed by users to execute the swap instead of the legacy function: - -```javascript -UniversalTokenRouter.exec([{ - recipient: to, - eip: 20, - token: path[path.length-1], - id: 0, - amountOutMin, -}], [{ - inputs: [{ - mode: TRANSFER_FROM_SENDER, - recipient: UniswapV2Library.pairFor(factory, path[0], path[1]), - eip: 20, - token: path[0], - id: 0, - amountInMax: amountIn, - amountSource: AMOUNT_EXACT, - }], - flags: 0, - code: UniswapV2Helper01.address, - data: encodeFunctionData("swapExactTokensForTokens", [ - amountIn, - amountOutMin, - path, - to, - deadline, - ]), -}]) -``` - -#### `UniswapRouter.swapTokensForExactTokens` - -Legacy function: - -```solidity -UniswapV2Router01.swapTokensForExactTokens( - uint amountOut, - uint amountInMax, - address[] calldata path, - address to, - uint deadline -) -``` - -This function accepts the `uint[] amounts` as the last `bytes` param, decode and pass to the internal function `_swap` of `UniswapV2Helper01`. - -```solidity -UniswapV2Helper01.swap( - address[] calldata path, - address to, - bytes calldata amountsBytes -) external { - uint[] memory amounts = abi.decode(amountsBytes, (uint[])); - _swap(amounts, path, to); -} -``` - -This transaction is signed by users to execute the swap instead of the legacy function: - -```javascript -UniversalTokenRouter.exec([{ - eip: 20, - token: path[path.length-1], - id: 0, - amountOutMin: amountOut, - recipient: to, -}], [{ - inputs: [], - flags: ACTION_RECORD_CALL_RESULT, - code: UniswapV2Helper01.address, - data: encodeFunctionData("getAmountIns", [amountOut, path]), -}, { - inputs: [{ - mode: TRANSFER_FROM_SENDER, - eip: 20, - token: path[0], - id: 0, - amountInMax, - amountSource: 32*3, // first item of getAmountIns result array - recipient: UniswapV2Library.pairFor(factory, path[0], path[1]), - }], - flags: ACTION_INJECT_CALL_RESULT, - code: UniswapV2Helper01.address, - data: encodeFunctionData("swap", [path, to, '0x']), -}]) -``` - -The result of `getAmountIns` is recorded and injected into the empty `bytes`, save the transaction from calculating twice with the same data. - -#### `UniswapRouter.addLiquidity` - -Legacy function: - -```solidity -UniswapV2Router01.addLiquidity( - address tokenA, - address tokenB, - uint amountADesired, - uint amountBDesired, - uint amountAMin, - uint amountBMin, - address to, - uint deadline -) -``` - -This transaction is signed by users instead of the legacy function: - -```javascript -UniversalTokenRouter.exec([{ - eip: 20, - token: UniswapV2Library.pairFor(factory, tokenA, tokenB), - id: 0, - amountOutMin: 1, // just enough to verify the correct recipient - recipient: to, -}], [{ - inputs: [], - flags: ACTION_RECORD_CALL_RESULT, - code: UniswapV2Helper01.address, - data: encodeFunctionData("_addLiquidity", [ - tokenA, - tokenB, - amountADesired, - amountBDesired, - amountAMin, - amountBMin, - ]), -}, { - inputs: [{ - mode: TRANSFER_FROM_SENDER, - eip: 20, - token: tokenA, - id: 0, - amountSource: 32, // first item of _addLiquidity results - amountInMax: amountADesired, - recipient: UniswapV2Library.pairFor(factory, tokenA, tokenB), - }, { - mode: TRANSFER_FROM_SENDER, - eip: 20, - token: tokenB, - id: 0, - amountSource: 64, // second item of _addLiquidity results - amountInMax: amountBDesired, - recipient: UniswapV2Library.pairFor(factory, tokenA, tokenB), - }], - flags: 0, - code: UniswapV2Library.pairFor(factory, tokenA, tokenB), - data: encodeFunctionData("mint", [to]), -}]) -``` - -The output token verification is not performed by Uniswap's legacy function and can be skipped. But it SHOULD always be done for the `UniversalTokenRouter` so user can see and review the token behavior instead of blindly trust the front-end code. - -#### Uniswap V3 `SwapRouter` - -Legacy router contract: - -```solidity -contract SwapRouter { - // this function is called by pool to pay the input tokens - function pay( - address token, - address payer, - address recipient, - uint256 value - ) internal { - ... - // pull payment - TransferHelper.safeTransferFrom(token, payer, recipient, value); - } -} -``` - -The helper contract to use with the `UTR`: - -```solidity -contract SwapHelper { - // this function is called by pool to pay the input tokens - function pay( - address token, - address payer, - address recipient, - uint256 value - ) internal { - ... - // pull payment - UTR.pay( - payer, - recipient, - 20, // EIP - token, - 0, // id - value - ); - } -} -``` - -This transaction is signed by users to execute the `exactInput` functionality using `IN_TX_PAYMENT` mode: - -```javascript -UniversalTokenRouter.exec([{ - eip: 20, - token: tokenOut, - id: 0, - amountOutMin: 1, - recipient: to, -}], [{ - inputs: [{ - mode: IN_TX_PAYMENT, - eip: 20, - token: tokenIn, - id: 0, - amountSource: AMOUNT_EXACT, - amountInMax: amountIn, - recipient: pool.address, - }], - flags: 0, - code: SwapHelper.address, - data: encodeFunctionData("exactInput", [...]), -}]) -``` - -This transaction is signed by users to execute the `mint` functionality using `ALLOWANCE_BRIDGE` mode: - -```javascript -UniversalTokenRouter.exec([{ - eip: 721, - token: PositionManager.address, - id: ID_721_ALL, - amountOutMin: 1, // expect one more liquidity NFT - recipient: to, -}], [{ - inputs: [{ - mode: ALLOWANCE_BRIDGE, - eip: 20, - token: tokenA, - id: 0, - amountSource: AMOUNT_EXACT, - amountInMax: amountADesired, - recipient: PositionManager.address, - }, { - mode: ALLOWANCE_BRIDGE, - eip: 20, - token: tokenB, - id: 0, - amountSource: AMOUNT_EXACT, - amountInMax: amountBDesired, - recipient: PositionManager.address, - }], - flags: 0, - code: PositionManager.address, - data: encodeFunctionData("mint", [...]), -}]) -``` - -## Rationale - -The `Permit` type signature is not supported since the purpose of the Universal Token Router is to eliminate all `approve` signatures for new tokens, and *most* for old tokens. - -## Backwards Compatibility - -### Tokens - -Old token contracts (EIP-20, EIP-721 and EIP-1155) require approval for the Universal Token Router once for each account. - -New token contracts can pre-configure the Universal Token Router as a trusted spender, and no approval transaction is required. - -### Application Contracts - -Application contracts that use `msg.sender` as the beneficiary address in their internal storage without any function for ownership transfer are the only cases that are **INCOMPATIBLE** with the UTR. - -All application contracts that accept `recipient` (or `to`) argument instead of using `msg.sender` as the beneficiary address are compatible with the UTR out of the box. - -Application contracts that transfer tokens (EIP-20, EIP-721, and EIP-1155) to `msg.sender` can use the UTR output token transfer sub-action to re-direct tokens to another `recipient` address. - -```javascript -// sample code to deposit WETH and transfer them out -UniversalTokenRouter.exec([{ - eip: 20, - token: WETH.address, - id: 0, - amountOutMin: 1, - recipient: SomeRecipient, -}], [{ - inputs: [{ - mode: TRANSFER_CALL_VALUE, - eip: 0, // ETH - token: AddressZero, - id: 0, - amountInMax: 123, - amountSource: AMOUNT_EXACT, - recipient: AddressZero, // pass it as the value for the next output action - }], - flags: 0, - code: WETH.address, - data: encodeFunctionData('deposit', []), // WETH.deposit returns WETH token to the UTR contract -}, { - inputs: [{ - mode: TRANSFER_FROM_ROUTER, - eip: 20, - token: WETH.address, - id: 0, - amountInMax: 0, // no limit - amountSource: AMOUNT_ALL, // entire WETH balance of this UTR contract - recipient: SomeRecipient, - }], - // ... continue to use WETH in SomeRecipient - flags: 0, - code: AddressZero, - data: '0x', -}], {value: 123}) -``` - -Applications can also deploy additional adapter contracts to add a `recipient` to their functions. - -```solidity -// sample adapter contract for WETH -contract WethAdapter { - address immutable WETH = 0x....; - function deposit(address recipient) external payable { - IWETH(WETH).deposit(){value: msg.value}; - TransferHelper.safeTransfer(WETH, recipient, msg.value); - } -} -``` - -## Reference Implementation - -```solidity -contract UniversalTokenRouter is IUniversalTokenRouter { - // values with a single 1-bit are preferred - uint constant TRANSFER_FROM_SENDER = 0; - uint constant TRANSFER_FROM_ROUTER = 1; - uint constant TRANSFER_CALL_VALUE = 2; - uint constant IN_TX_PAYMENT = 4; - uint constant ALLOWANCE_BRIDGE = 8; - - uint constant AMOUNT_EXACT = 0; - uint constant AMOUNT_ALL = 1; - - uint constant EIP_ETH = 0; - - uint constant ID_721_ALL = uint(keccak256('UniversalTokenRouter.ID_721_ALL')); - - uint constant ACTION_IGNORE_ERROR = 1; - uint constant ACTION_RECORD_CALL_RESULT = 2; - uint constant ACTION_INJECT_CALL_RESULT = 4; - - // non-persistent in-transaction pending payments - mapping(bytes32 => uint) s_payments; - - // accepting ETH for WETH.withdraw - receive() external payable {} - - function exec( - Output[] memory outputs, - Action[] memory actions - ) override external payable { - unchecked { - // track the expected balances before any action is executed - for (uint i = 0; i < outputs.length; ++i) { - Output memory output = outputs[i]; - uint balance = _balanceOf(output.recipient, output.eip, output.token, output.id); - uint expected = output.amountOutMin + balance; - require(expected >= balance, 'UniversalTokenRouter: OVERFLOW'); - output.amountOutMin = expected; - } - - bool dirty = false; - - bytes memory callResult; - for (uint i = 0; i < actions.length; ++i) { - Action memory action = actions[i]; - uint value; - for (uint j = 0; j < action.inputs.length; ++j) { - Input memory input = action.inputs[j]; - uint mode = input.mode; - address sender = mode == TRANSFER_FROM_ROUTER ? address(this) : msg.sender; - uint amount; - if (input.amountSource == AMOUNT_EXACT) { - amount = input.amountInMax; - } else { - if (input.amountSource == AMOUNT_ALL) { - amount = _balanceOf(sender, input.eip, input.token, input.id); - } else { - amount = _sliceUint(callResult, input.amountSource); - } - require(amount <= input.amountInMax, "UniversalTokenRouter: EXCESSIVE_INPUT_AMOUNT"); - } - if (mode == TRANSFER_CALL_VALUE) { - value = amount; - continue; - } - if (mode == TRANSFER_FROM_SENDER || mode == TRANSFER_FROM_ROUTER) { - _transferToken(sender, input.recipient, input.eip, input.token, input.id, amount); - continue; - } - if (mode == IN_TX_PAYMENT) { - bytes32 key = keccak256(abi.encodePacked(msg.sender, input.recipient, input.eip, input.token, input.id)); - s_payments[key] += amount; // overflow: harmless - dirty = true; - continue; - } - if (mode == ALLOWANCE_BRIDGE) { - _approve(input.recipient, input.eip, input.token, type(uint).max); - _transferToken(msg.sender, address(this), input.eip, input.token, input.id, amount); - dirty = true; - } - } - if (action.data.length > 0) { - if (action.flags & ACTION_INJECT_CALL_RESULT != 0) { - action.data = _concat(action.data, action.data.length, callResult); - } - (bool success, bytes memory result) = action.code.call{value: value}(action.data); - if (!success && action.flags & ACTION_IGNORE_ERROR == 0) { - assembly { - revert(add(result,32),mload(result)) - } - } - // delete value; // clear the ETH value after call - if (action.flags & ACTION_RECORD_CALL_RESULT != 0) { - callResult = result; - } - } - } - - // verify balance changes - for (uint i = 0; i < outputs.length; ++i) { - Output memory output = outputs[i]; - uint balance = _balanceOf(output.recipient, output.eip, output.token, output.id); - require(balance >= output.amountOutMin, 'UniversalTokenRouter: INSUFFICIENT_OUTPUT_AMOUNT'); - } - - // clear all in-transaction storages - if (dirty) { - for (uint i = 0; i < actions.length; ++i) { - Action memory action = actions[i]; - for (uint j = 0; j < action.inputs.length; ++j) { - Input memory input = action.inputs[j]; - if (input.mode == IN_TX_PAYMENT) { - bytes32 key = keccak256(abi.encodePacked(msg.sender, input.recipient, input.eip, input.token, input.id)); - delete s_payments[key]; - continue; - } - if (input.mode == ALLOWANCE_BRIDGE) { - _approve(input.recipient, input.eip, input.token, 0); - uint balance = _balanceOf(address(this), input.eip, input.token, input.id); - if (balance > 0) { - _transferToken(address(this), msg.sender, input.eip, input.token, input.id, balance); - } - } - } - } - } - - // refund any left-over ETH - uint leftOver = address(this).balance; - if (leftOver > 0) { - TransferHelper.safeTransferETH(msg.sender, leftOver); - } - } } - - function pay( - address sender, - address recipient, - uint eip, - address token, - uint id, - uint amount - ) public { - unchecked { - bytes32 key = keccak256(abi.encodePacked(sender, recipient, eip, token, id)); - require(s_payments[key] >= amount, 'UniversalTokenRouter: INSUFFICIENT_ALLOWANCE'); - s_payments[key] -= amount; - _transferToken(sender, recipient, eip, token, id, amount); - } } - - function _transferToken( - address sender, - address recipient, - uint eip, - address token, - uint id, - uint amount - ) internal { - if (eip == 20) { - if (sender == address(this)) { - TransferHelper.safeTransfer(token, recipient, amount); - } else { - TransferHelper.safeTransferFrom(token, sender, recipient, amount); - } - } else if (eip == 1155) { - IERC1155(token).safeTransferFrom(sender, recipient, id, amount, ""); - } else if (eip == 721) { - IERC721(token).safeTransferFrom(sender, recipient, id); - } else if (eip == EIP_ETH) { - require(sender == address(this), 'UniversalTokenRouter: INVALID_ETH_SENDER'); - TransferHelper.safeTransferETH(recipient, amount); - } else { - revert("UniversalTokenRouter: INVALID_EIP"); - } - } - - function _approve( - address recipient, - uint eip, - address token, - uint amount - ) internal { - if (eip == 20) { - TransferHelper.safeApprove(token, recipient, amount); - } else if (eip == 1155) { - IERC1155(token).setApprovalForAll(recipient, amount > 0); - } else if (eip == 721) { - IERC721(token).setApprovalForAll(recipient, amount > 0); - } else { - revert("UniversalTokenRouter: INVALID_EIP"); - } - } - - function _balanceOf( - address owner, - uint eip, - address token, - uint id - ) internal view returns (uint balance) { - if (eip == 20) { - return IERC20(token).balanceOf(owner); - } - if (eip == 1155) { - return IERC1155(token).balanceOf(owner, id); - } - if (eip == 721) { - if (id == ID_721_ALL) { - return IERC721(token).balanceOf(owner); - } - try IERC721(token).ownerOf(id) returns (address currentOwner) { - return currentOwner == owner ? 1 : 0; - } catch { - return 0; - } - } - if (eip == EIP_ETH) { - return owner.balance; - } - revert("UniversalTokenRouter: INVALID_EIP"); - } - - function _sliceUint(bytes memory bs, uint start) internal pure returns (uint x) { - // require(bs.length >= start + 32, "slicing out of range"); - assembly { - x := mload(add(bs, start)) - } - } - - /// https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol - /// @param length length of the first preBytes - function _concat( - bytes memory preBytes, - uint length, - bytes memory postBytes - ) internal pure returns (bytes memory bothBytes) { - assembly { - // Get a location of some free memory and store it in bothBytes as - // Solidity does for memory variables. - bothBytes := mload(0x40) - - // Store the length of the first bytes array at the beginning of - // the memory for bothBytes. - mstore(bothBytes, length) - - // Maintain a memory counter for the current write location in the - // temp bytes array by adding the 32 bytes for the array length to - // the starting location. - let mc := add(bothBytes, 0x20) - // Stop copying when the memory counter reaches the length of the - // first bytes array. - let end := add(mc, length) - - for { - // Initialize a copy counter to the start of the preBytes data, - // 32 bytes into its memory. - let cc := add(preBytes, 0x20) - } lt(mc, end) { - // Increase both counters by 32 bytes each iteration. - mc := add(mc, 0x20) - cc := add(cc, 0x20) - } { - // Write the preBytes data into the bothBytes memory 32 bytes - // at a time. - mstore(mc, mload(cc)) - } - - // Add the length of postBytes to the current length of bothBytes - // and store it as the new length in the first 32 bytes of the - // bothBytes memory. - length := mload(postBytes) - mstore(bothBytes, add(length, mload(bothBytes))) - - // Move the memory counter back from a multiple of 0x20 to the - // actual end of the preBytes data. - mc := sub(end, 0x20) - // Stop copying when the memory counter reaches the new combined - // length of the arrays. - end := add(end, length) - - for { - let cc := postBytes - } lt(mc, end) { - mc := add(mc, 0x20) - cc := add(cc, 0x20) - } { - mstore(mc, mload(cc)) - } - - // Update the free-memory pointer by padding our last write location - // to 32 bytes: add 31 bytes to the end of bothBytes to move to the - // next 32 byte block, then round down to the nearest multiple of - // 32. If the sum of the length of the two arrays is zero then add - // one before rounding down to leave a blank 32 bytes (the length block with 0). - // mstore(0x40, and( - // add(add(end, iszero(add(length, mload(preBytes)))), 31), - // not(31) // Round down to the nearest 32 bytes. - // )) - } - } -} -``` - -## Security Considerations - -`ACTION_INJECT_CALL_RESULT` SHOULD only be used for gas optimization, not as trusted conditions. Application contract code MUST always expect arbitruary, malformed or mallicious data can be passed in where the call result `bytes` is expected. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6120.md diff --git a/EIPS/eip-6122.md b/EIPS/eip-6122.md index 79f81422c19f69..c30fd6049bac8f 100644 --- a/EIPS/eip-6122.md +++ b/EIPS/eip-6122.md @@ -4,7 +4,7 @@ title: Forkid checks based on timestamps description: Modifies the forkid checks to work with timestamps and block numbers author: Marius van der Wijden (@MariusVanDerWijden) discussions-to: https://ethereum-magicians.org/t/eip-6122-forkid-checks-based-on-timestamps/12130 -status: Draft +status: Final type: Standards Track category: Networking created: 2022-12-13 @@ -34,7 +34,7 @@ Each node maintains the following values: - Block timestamps are regarded as `uint64` integers, encoded in big endian format when checksumming. - If a chain is configured to start with a non-Frontier ruleset already in its genesis, that is NOT considered a fork. - **`FORK_NEXT`**: Block number or timestamp (`uint64`) of the next upcoming fork, or `0` if no next fork is known. - - Note that it is not important to distinguish between a timestamp or a block for `FROK_NEXT`. + - Note that it is not important to distinguish between a timestamp or a block for `FORK_NEXT`. A `FORK_HASH` for a timestamp based fork at `1668000000` on top of homestead would be: diff --git a/EIPS/eip-6123.md b/EIPS/eip-6123.md index be7f54b0e883d9..3bb135fce3fc8c 100644 --- a/EIPS/eip-6123.md +++ b/EIPS/eip-6123.md @@ -1,236 +1,7 @@ --- eip: 6123 -title: Smart Derivative Contract -description: A deterministic protocol for frictionless post-trade processing of OTC financial contracts -author: Christian Fries (@cfries), Peter Kohl-Landgraf (@pekola), Alexandros Korpis (@kourouta) -discussions-to: https://ethereum-magicians.org/t/eip-6123-smart-derivative-contract-frictionless-processing-of-financial-derivatives/12134 -status: Draft -type: Standards Track category: ERC -created: 2022-12-13 +status: Moved --- -## Abstract - -The Smart Derivative Contract is a deterministic protocol to trade and process -financial derivative contracts frictionless and scalable in a completely automated way. Counterparty credit risk ís removed. -Known operational risks and complexities in post-trade processing are removed by construction as all process states -are fully specified and are known to the counterparties. - -## Motivation - -### Rethinking Financial Derivatives - -By their very nature, so-called "over-the-counter (OTC)" financial contracts are bilateral contractual agreements on the exchange of long-dated cash flow schedules. -Since these contracts change their intrinsic market value due to changing market environments, they are subject to counterparty credit risk when one counterparty is subject to default. -The initial white paper describes the concept of a Smart Derivative Contract with the central aim -to detach bilateral financial transactions from counterparty credit risk and to remove complexities -in bilateral post-trade processing by a complete redesign. - -### Concept of a Smart Derivative Contract - -A Smart Derivative Contract is a deterministic settlement protocol which has the same economic behaviour as a collateralized OTC -Derivative. Every process state is specified; therefore, the entire post-trade process is known in advance. -A Smart Derivative Contract (SDC) settles outstanding net present value of the underlying financial contract on a frequent basis. With each settlement cycle net present value of the underlying contract is -exchanged, and the value of the contract is reset to zero. Pre-Agreed margin buffers are locked at the beginning of each settlement cycle such that settlement will be guaranteed up to a certain amount. -If a counterparty fails to obey contract rules, e.g. not provide sufficient prefunding, SDC will terminate automatically with the guaranteed transfer of a termination fee by the causing party. -These features enable two counterparties to process their financial contract fully decentralized without relying on a third central intermediary agent. -The process logic of SDC can be implemented as a finite state machine on solidity. An [EIP-20](./eip-20.md) token can be used for frictionless decentralized settlement, see reference implementation. -Combined with an appropriate external market data and valuation oracle which calculates net present values, each known OTC derivative contract is able to be processed using this standard protocol. - - -## Specification - -### Methods - -The following methods specify inception and post-trade live cycle of a Smart Derivative Contract. For futher information also please look at the interface documentation ISDC.sol. - -#### inceptTrade - -A counterparty can initiate a trade by providing trade data as string and calling inceptTrade and initial settlement data. Only registered counteparties are allowed to use that function. - -```solidity -function inceptTrade(string memory _tradeData, string memory _initialSettlementData) external; -``` - -#### confirmTrade - -A counterparty can confirm a trade by providing the identical trade data and initial settlement information, which are already stored from inceptTrade call. - -```solidity -function confirmTrade(string memory _tradeData, string memory _initialSettlementData) external; -``` - -#### initiatePrefunding - -This method checks whether contractual prefunding is provided by both counterparties as agreed in the contract terms. Triggers a contract termination if not. - -```solidity -function initiatePrefunding() external; -``` - -#### initiateSettlement - -Allows eligible participants (such as counterparties or a delegated agent) to initiate a settlement. - -```solidity -function initiateSettlement() external; -``` - -#### performSettlement - -Valuation may be provided off-chain via an external oracle service that calculates net present value and uses external market data. -Method serves as callback called from an external oracle providing settlement amount and used settlement data which also get stored. -Settlement amount will be checked according to contract terms resulting in either a reqular settlement or a termination of the trade. - -```solidity -function performSettlement(int256 settlementAmount, string memory settlementData) external; -``` - -#### requestTermination - -Allows an eligible party to request a mutual termination - -```js -function requestTradeTermination(string memory tradeId) external; -``` - -#### confirmTradeTermination - -Allows eligible parties to confirm a formerly-requested mutual trade termination. - -```solidity -function confirmTradeTermination(string memory tradeId) external; -``` - -### Trade Events - -The following events are emitted during an SDC trade livecycle. - -#### TradeIncepted - -Emitted on trade inception - method 'inceptTrade' - -```solidity -event TradeIncepted(address initiator, string tradeId, string tradeData); -``` - -#### TradeConfirmed - -Emitted on trade confirmation - method 'confirmTrade' - -```solidity -event TradeConfirmed(address confirmer, string tradeId); -``` - -#### TradeActivated - -Emitted when trade is activated - -```solidity -event TradeActivated(string tradeId); -``` - -#### TradeTerminationRequest - -Emitted when termination request is initiated by a counterparty - -```solidity -event TradeTerminationRequest(address cpAddress, string tradeId); -``` - -#### TradeTerminationConfirmed - -Emitted when termination request is confirmed by a counterparty - -```solidity -event TradeTerminationConfirmed(address cpAddress, string tradeId); -``` - -#### TradeTerminated - -Emitted when trade is terminated - -```solidity -event TradeTerminated(string cause); -``` - -### Process Events - -The following events are emitted during SDC's process livecycle. - -#### ProcessAwaitingFunding - -Emitted when funding phase is initiated - -```solidity -event ProcessAwaitingFunding(); -``` - -#### ProcessFunded - -Emitted when funding has completed successfully - method 'initiatePrefunding' - -```solidity -event ProcessFunded(); -``` - -#### ProcessSettlementRequest - -Emitted when a settlement is initiated - method 'initiateSettlement' - -```solidity -event ProcessSettlementRequest(string tradeData, string lastSettlementData); -``` - -#### ProcessSettled - -Emitted when settlement was processed successfully - method 'performSettlement' - -```solidity -event ProcessSettled(); -``` - -## Rationale - -The interface design and reference implementation are based on the following considerations: - -- A SDC protocol is supposed to be used by two counterparties and enables them to initiate and process a derivative transaction in a bilateral and digital manner. -- The provided interface specification is supposed to completely reflect the entire trade livecycle. -- The interface specification is generic enough to handle the case that two counterparties process one or even multiple derivative transactions (on a netted base) -- Usually, the valuation of an OTC trade will require advanced valuation methodology. This is why the concept will in most cases rely on external market data and valuation algorithms -- A pull-based valuation based oracle pattern is specified by a simple callback pattern (methods: initiateSettlement, performSettlement) -- The reference implementation `SDC.sol` is based on a state-machine pattern where the states also serve as guards (via modifiers) to check which method is allowed to be called at a particular given process and trade state -- Java based state machine and contract implementations are also available. See the github repo link below. - -### State diagram of trade and process states - -![image info](../assets/eip-6123/doc/sdc_trade_and_process_states.png) - -### Sequence diagram of trade initiation and settlement livecycle - -![image info](../assets/eip-6123/doc/sdc_livecycle_sequence_diagram.png) - -## Test Cases - -Live-cycle unit tests based on the sample implementation and usage of [EIP-20](./eip-20.md) token is provided. See file [test/SDC.js](../assets/eip-6123/test/SDC.js) -). - -## Reference Implementation - -A reference implementation SDC.sol is provided and is based on the [EIP-20](./eip-20.md) token standard. -See folder /assets/contracts, more explanation on the implementation is provided inline. - -### Trade Data Specification (suggestion) - -Please take a look at the provided xml file as a suggestion on how trade parameters could be stored. - -## Security Considerations - -No known security issues up to now. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6123.md diff --git a/EIPS/eip-6147.md b/EIPS/eip-6147.md index f45e5cbd099529..18ba25babf8eb5 100644 --- a/EIPS/eip-6147.md +++ b/EIPS/eip-6147.md @@ -1,286 +1,7 @@ --- eip: 6147 -title: Guard of NFT/SBT, an Extension of EIP-721 -description: A new management role of NFT/SBT is defined, which realizes the separation of transfer right and holding right of NFT/SBT. -author: 5660-eth (@5660-eth), Wizard Wang -discussions-to: https://ethereum-magicians.org/t/guard-of-nft-sbt-an-extension-of-eip-721/12052 -status: Review -type: Standards Track category: ERC -created: 2022-12-07 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension of [EIP-721](./eip-721.md). It separates the holding right and transfer right of non-fungible tokens (NFTs) and Soulbound Tokens (SBTs) and defines a new role, `guard`. The flexibility of the `guard` setting enables the design of NFT anti-theft, NFT lending, NFT leasing, SBT, etc. - -## Motivation - -NFTs are assets that have both use and financial value. - -Many cases of NFT theft currently exist, and current NFT anti-theft schemes, such as transferring NFTs to cold wallets, make NFTs inconvenient to be used. - -In current NFT lending, the NFT owner needs to transfer the NFT to the NFT lending contract, and the NFT owner no longer has the right to use the NFT while he or she has obtained the loan. In the real world, for example, if a person takes out a mortgage on his own house, he still has the right to use that house. - -For SBT, the current mainstream view is that an SBT is not transferable, which makes an SBT bound to an Ether address. However, when the private key of the user address is leaked or lost, retrieving SBT will become a complicated task and there is no corresponding specification. The SBTs essentially realizes the separation of NFT holding right and transfer right. When the wallet where SBT is located is stolen or unavailable, SBT should be able to be recoverable. - -In addition, SBTs still need to be managed in use. For example, if a university issues diploma SBTs to its graduates, and if the university later finds that a graduate has committed academic misconduct or jeopardized the reputation of the university, it should have the ability to retrieve the diploma SBT. - - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY" and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -EIP-721 compliant contracts MAY implement this EIP. - -When a token has no guard, owner, authorised operators and approved address of the token MUST have permission to set guard. - -When a token has no guard, `guardOf` MUST return `address(0)`. - -When a token has a guard, owner, authorised operators and approved address of the token MUST NOT be able to change guard, and they MUST NOT be able to transfer the token. - -When a token has a guard, `guardOf` MUST return the address of the guard. - -When a token has a guard, the guard must be able to remove guard, change guard and transfer the token. - -When a token has a guard, if the token burns, the guard MUST be deleted. - -If issuing or minting SBTs, the guard MAY be uniformly set to the designated address to facilitate management. - -### Contract Interface - -```solidity - interface IERC6147 { - - /// Logged when the guard of an NFT is changed - /// @notice Emitted when the `guard` is changed - /// The zero address for guard indicates that there is no guard address - event UpdateGuardLog(uint256 indexed tokenId, address indexed newGuard, address oldGuard); - - /// @notice Owner, authorised operators and approved address of the NFT can set guard of the NFT and guard can modifiy guard of the NFT - /// If the NFT has a guard role, the owner, authorised operators and approved address of the NFT cannot modify guard - /// @dev The newGuard can not be zero address - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to get the guard address for - /// @param newGuard The new guard address of the NFT - function changeGuard(uint256 tokenId, address newGuard) external; - - /// @notice Remove the guard of the NFT - /// Only guard can remove its own guard role - /// @dev The guard address is set to 0 address - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to remove the guard address for - function removeGuard(uint256 tokenId) external; - - /// @notice Transfer the NFT and remove its guard role - /// @dev The NFT is transferred to `to` and the guard address is set to 0 address - /// Throws if `tokenId` is not valid NFT - /// @param from The address of the previous owner of the NFT - /// @param to The address of NFT recipient - /// @param tokenId The NFT to get transferred for - function transferAndRemove(address from, address to, uint256 tokenId) external; - - /// @notice Get the guard address of the NFT - /// @dev The zero address indicates that there is no guard - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to get the guard address for - /// @return The guard address for the NFT - function guardOf(uint256 tokenId) external view returns (address); -} - ``` - -The `changeGuard(uint256 tokenId, address newGuard)` function MAY be implemented as `public` or `external`. - -The `removeGuard(uint256 tokenId)` function MAY be implemented as `public` or `external`. - -The `transferAndRemove(address from,address to,uint256 tokenId)` function MAY be implemented as `public` or `external`. - -The `guardOf(uint256 tokenId)` function MAY be implemented as `pure` or `view`. - -The `UpdateGuardLog` event MUST be emitted when a guard is changed. - -The `supportsInterface` method MUST return `true` when called with `0xc0655ef1`. - -## Rationale - -### Universality - -There are many application scenarios for NFT/SBT, and there is no need to propose a dedicated EIP for each one, which would make the overall number of EIPS inevitably increase and add to the burden of developers. The standard is based on the analysis of the right attached to assets in the real world, and abstracts the right attached to NFT/SBT into holding right and transfer right making the standard more universal. - -For example, the standard has and has more than the following use cases: - -SBTs. The SBTs issuer can assign a uniform role of `guard` to the SBTs before they are minted, so that the SBTs cannot be transferred by the corresponding holders and can be managed by the SBTs issuer through the `guard`. - -NFT anti-theft. If an NFT holder sets a `guard` address of an NFT as his or her own cold wallet address, the NFT can still be used by the NFT holder, but the risk of theft is greatly reduced. - -NFT lending. The borrower sets the `guard` of his or her own NFT as the lender's address, the borrower still has the right to use the NFT while obtaining the loan, but at the same time cannot transfer or sell the NFT. If the borrower defaults on the loan, the lender can transfer and sell the NFT. - -### Simplicity - -Improvements to the ETH protocol should be as simple as possible. Entities should not be multiplied beyond necessity. - -### Extensibility - -This standard only defines a `guard`, for the complex functions required by NFTs and SBTs, such as social recovery, multi-signature, expires management, according to the specific application scenarios, the `guard` can be set as a third-party protocol address, through the third-party protocol to achieve more flexible and diverse functions. - -### Naming - -The alternative names are `guardian` and `guard`, both of which basically match the permissions corresponding to the role: protection of NFT or necessary management according to its application scenarios. The `guard` has fewer characters than the `guardian` and is more concise. - -## Backwards Compatibility - -This standard can be fully EIP-721 compatible by adding an extension function set. - -If an NFT issued based on the above standard does not set a `guard` , then it is no different in the existing functions from the current NFT issued based on the EIP-721 standard. - -## Reference Implementation - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.8; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "./IERC6147.sol"; - -abstract contract ERC6147 is ERC721, IERC6147 { - - mapping(uint256 => address) internal token_guard_map; - - /// @notice Owner, authorised operators and approved address of the NFT can set guard of the NFT and guard can modifiy guard of the NFT - /// If the NFT has a guard role, the owner, authorised operators and approved address of the NFT cannot modify guard - /// @dev The newGuard can not be zero address - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to get the guard address for - /// @param newGuard The new guard address of the NFT - function changeGuard(uint256 tokenId, address newGuard) public virtual{ - _updateGuard(tokenId, newGuard, false); - } - - /// @notice Remove the guard of the NFT - /// Only guard can remove its own guard role - /// @dev The guard address is set to 0 address - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to remove the guard address for - function removeGuard(uint256 tokenId) public virtual { - _updateGuard(tokenId, address(0), true); - } - - /// @notice Transfer the NFT and remove its guard role - /// @dev The NFT is transferred to `to` and the guard address is set to 0 address - /// Throws if `tokenId` is not valid NFT - /// @param from The address of the previous owner of the NFT - /// @param to The address of NFT recipient - /// @param tokenId The NFT to get transferred for - function transferAndRemove(address from, address to, uint256 tokenId) public virtual { - safeTransferFrom(from, to, tokenId); - removeGuard(tokenId); - } - - /// @notice Get the guard address of the NFT - /// @dev The zero address indicates that there is no guard - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to get the guard address for - /// @return The guard address for the NFT - function guardOf(uint256 tokenId) public view virtual returns (address) { - return token_guard_map[tokenId]; - } - - /// @notice Update the guard of the NFT - /// @dev Delete function: set guard to 0 address; and update function: set guard to new address - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to update the guard address for - /// @param newGuard The newGuard address - /// @param allowNull Allow 0 address - function _updateGuard(uint256 tokenId, address newGuard, bool allowNull) internal { - address guard = guardOf(tokenId); - if (!allowNull) { - require(newGuard != address(0), "ERC6147: new guard can not be null"); - } - if (guard != address(0)) { - require(guard == _msgSender(), "ERC6147: only guard can change it self"); - } else { - require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC6147: caller is not owner nor approved"); - } - - if (guard != address(0) || newGuard != address(0)) { - token_guard_map[tokenId] = newGuard; - emit UpdateGuardLog(tokenId, newGuard, guard); - } - } - - /// @notice Check the guard address - /// @dev The zero address indicates there is no guard - /// Throws if `tokenId` is not valid NFT - /// @param tokenId The NFT to check the guard address for - /// @return The guard address - function _checkGuard(uint256 tokenId) internal view returns (address) { - address guard = guardOf(tokenId); - address sender = _msgSender(); - if (guard != address(0)) { - require(guard == sender, "ERC6147: sender is not guard of the token"); - return guard; - }else{ - return address(0); - } - } - - /// @dev Before transferring the NFT, need to check the gurard address - function transferFrom(address from, address to, uint256 tokenId) public virtual override { - address guard; - address new_from = from; - if (from != address(0)) { - guard = _checkGuard(tokenId); - new_from = ownerOf(tokenId); - } - if (guard == address(0)) { - require( - _isApprovedOrOwner(_msgSender(), tokenId), - "ERC721: transfer caller is not owner nor approved" - ); - } - _transfer(new_from, to, tokenId); - } - - /// @dev Before safe transferring the NFT, need to check the gurard address - function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { - address guard; - address new_from = from; - if (from != address(0)) { - guard = _checkGuard(tokenId); - new_from = ownerOf(tokenId); - } - if (guard == address(0)) { - require( - _isApprovedOrOwner(_msgSender(), tokenId), - "ERC721: transfer caller is not owner nor approved" - ); - } - _safeTransfer(from, to, tokenId, _data); - } - - /// @dev When burning, delete `token_guard_map[tokenId]` - /// This is an internal function that does not check if the sender is authorized to operate on the token. - function _burn(uint256 tokenId) internal virtual override { - address guard=guardOf(tokenId); - super._burn(tokenId); - delete token_guard_map[tokenId]; - emit UpdateGuardLog(tokenId, address(0), guard); - } - - /// @dev See {IERC165-supportsInterface}. - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC6147).interfaceId || super.supportsInterface(interfaceId); - } -} -``` - -## Security Considerations - -When an NFT has a `guard`, even if an address is authorized as an operator through `approve` or `setApprovalForAll`, the operator still has no right to transfer the NFT. - -When an NFT has a `guard`, the `owner` cannot sell the NFT. Some trading platforms list NFTs through `setApprovalForAll` and owners' signature. It is recommended to prevent listing these NFTs by checking `guardOf`. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6147.md diff --git a/EIPS/eip-615.md b/EIPS/eip-615.md index 7e356609a7d013..c5d1ae156b351f 100644 --- a/EIPS/eip-615.md +++ b/EIPS/eip-615.md @@ -510,11 +510,11 @@ There is a large and growing ecosystem of researchers, authors, teachers, audito * [Ethereum 2.0 Specifications](https://github.com/ethereum/eth2.0-specs) * [Formal Verification of Smart Contracts](https://www.cs.umd.edu/~aseem/solidetherplas.pdf) * [JelloPaper: Human Readable Semantics of EVM in K](https://jellopaper.org/) -* [KEVM: A Complete Semantics of the Ethereum Virtual Machine.](https://www.ideals.illinois.edu/bitstream/handle/2142/97207/hildenbrandt-saxena-zhu-rodrigues-guth-daian-rosu-2017-tr.pdf) +* [KEVM: A Complete Semantics of the Ethereum Virtual Machine.](https://www.ideals.illinois.edu/items/102260) * [Making Smart Contracts Smarter](https://eprint.iacr.org/2016/633.pdf) * [Securify: Practical Security Analysis of Smart Contracts](https://arxiv.org/pdf/1806.01143.pdf) * [The Thunder Protocol](https://docs.thundercore.com/thunder-whitepaper.pdf) -* [Towards Verifying Ethereum Smart Contract Bytecode in Isabelle/HOL](https://ts.data61.csiro.au/publications/csiro_full_text//Amani_BBS_18.pdf) +* [Towards Verifying Ethereum Smart Contract Bytecode in Isabelle/HOL](https://trustworthy.systems/publications/full_text/Amani_BBS_18.pdf) *[A Lem formalization of EVM 1.5](https://github.com/seed/eth-isabelle/tree/evm15) diff --git a/EIPS/eip-6150.md b/EIPS/eip-6150.md index 32fd6f19a69fa8..22cc72f018f8e8 100644 --- a/EIPS/eip-6150.md +++ b/EIPS/eip-6150.md @@ -1,291 +1,7 @@ --- eip: 6150 -title: Hierarchical NFTs -description: Hierarchical NFTs, an extension to EIP-721. -author: Keegan Lee (@keeganlee), msfew , Kartin , qizhou (@qizhou) -discussions-to: https://ethereum-magicians.org/t/eip-6150-hierarchical-nfts-an-extension-to-erc-721/12173 -status: Final -type: Standards Track category: ERC -created: 2022-12-15 -requires: 165, 721 +status: Moved --- -## Abstract - -This standard is an extension to [EIP-721](./eip-721.md). It proposes a multi-layer filesystem-like hierarchical NFTs. This standard provides interfaces to get parent NFT or children NFTs and whether NFT is a leaf node or root node, maintaining the hierarchical relationship among them. - -## Motivation - -This EIP standardizes the interface of filesystem-like hierarchical NFTs and provides a reference implementation. - -Hierarchy structure is commonly implemented for file systems by operating systems such as Linux Filesystem Hierarchy (FHS). - -![Linux Hierarchical File Structure](../assets/eip-6150/linux-hierarchy.png) - -Websites often use a directory and category hierarchy structure, such as eBay (Home -> Electronics -> Video Games -> Xbox -> Products), and Twitter (Home -> Lists -> List -> Tweets), and Reddit (Home -> r/ethereum -> Posts -> Hot). - -![Website Hierarchical Structure](../assets/eip-6150/website-hierarchy.png) - -A single smart contract can be the `root`, managing every directory/category as individual NFT and hierarchy relations of NFTs. Each NFT's `tokenURI` may be another contract address, a website link, or any form of metadata. - -The advantages and the advancement of the Ethereum ecosystem of using this standard include: - -- Complete on-chain storage of hierarchy, which can also be governed on-chain by additional DAO contract -- Only need a single contract to manage and operate the hierarchical relations -- Transferrable directory/category ownership as NFT, which is great for use cases such as on-chain forums -- Easy and permissionless data access to the hierarchical structure by front-end -- Ideal structure for traditional applications such as e-commerce, or forums -- Easy-to-understand interfaces for developers, which are similar to Linux filesystem commands in concept - -The use cases can include: - -- On-chain forum, like Reddit -- On-chain social media, like Twitter -- On-chain corporation, for managing organizational structures -- On-chain e-commerce platforms, like eBay or individual stores -- Any application with tree-like structures - -In the future, with the development of the data availability solutions of Ethereum and an external permissionless data retention network, the content (posts, listed items, or tweets) of these platforms can also be entirely stored on-chain, thus realizing fully decentralized applications. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -Every compliant contract must implement this proposal, [EIP-721](./eip-721.md) and [EIP-165](./eip-165.md) interfaces. - -```solidity -pragma solidity ^0.8.0; - -// Note: the ERC-165 identifier for this interface is 0x897e2c73. -interface IERC6150 /* is IERC721, IERC165 */ { - /** - * @notice Emitted when `tokenId` token under `parentId` is minted. - * @param minter The address of minter - * @param to The address received token - * @param parentId The id of parent token, if it's zero, it means minted `tokenId` is a root token. - * @param tokenId The id of minted token, required to be greater than zero - */ - event Minted( - address indexed minter, - address indexed to, - uint256 parentId, - uint256 tokenId - ); - - /** - * @notice Get the parent token of `tokenId` token. - * @param tokenId The child token - * @return parentId The Parent token found - */ - function parentOf(uint256 tokenId) external view returns (uint256 parentId); - - /** - * @notice Get the children tokens of `tokenId` token. - * @param tokenId The parent token - * @return childrenIds The array of children tokens - */ - function childrenOf( - uint256 tokenId - ) external view returns (uint256[] memory childrenIds); - - /** - * @notice Check the `tokenId` token if it is a root token. - * @param tokenId The token want to be checked - * @return Return `true` if it is a root token; if not, return `false` - */ - function isRoot(uint256 tokenId) external view returns (bool); - - /** - * @notice Check the `tokenId` token if it is a leaf token. - * @param tokenId The token want to be checked - * @return Return `true` if it is a leaf token; if not, return `false` - */ - function isLeaf(uint256 tokenId) external view returns (bool); -} -``` - -Optional Extension: Enumerable - -```solidity -// Note: the ERC-165 identifier for this interface is 0xba541a2e. -interface IERC6150Enumerable is IERC6150 /* IERC721Enumerable */ { - /** - * @notice Get total amount of children tokens under `parentId` token. - * @dev If `parentId` is zero, it means get total amount of root tokens. - * @return The total amount of children tokens under `parentId` token. - */ - function childrenCountOf(uint256 parentId) external view returns (uint256); - - /** - * @notice Get the token at the specified index of all children tokens under `parentId` token. - * @dev If `parentId` is zero, it means get root token. - * @return The token ID at `index` of all chlidren tokens under `parentId` token. - */ - function childOfParentByIndex( - uint256 parentId, - uint256 index - ) external view returns (uint256); - - /** - * @notice Get the index position of specified token in the children enumeration under specified parent token. - * @dev Throws if the `tokenId` is not found in the children enumeration. - * If `parentId` is zero, means get root token index. - * @param parentId The parent token - * @param tokenId The specified token to be found - * @return The index position of `tokenId` found in the children enumeration - */ - function indexInChildrenEnumeration( - uint256 parentId, - uint256 tokenId - ) external view returns (uint256); -} -``` - -Optional Extension: Burnable - -```solidity -// Note: the ERC-165 identifier for this interface is 0x4ac0aa46. -interface IERC6150Burnable is IERC6150 { - /** - * @notice Burn the `tokenId` token. - * @dev Throws if `tokenId` is not a leaf token. - * Throws if `tokenId` is not a valid NFT. - * Throws if `owner` is not the owner of `tokenId` token. - * Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this token. - * @param tokenId The token to be burnt - */ - function safeBurn(uint256 tokenId) external; - - /** - * @notice Batch burn tokens. - * @dev Throws if one of `tokenIds` is not a leaf token. - * Throws if one of `tokenIds` is not a valid NFT. - * Throws if `owner` is not the owner of all `tokenIds` tokens. - * Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for all `tokenIds`. - * @param tokenIds The tokens to be burnt - */ - function safeBatchBurn(uint256[] memory tokenIds) external; -} -``` - -Optional Extension: ParentTransferable - -```solidity -// Note: the ERC-165 identifier for this interface is 0xfa574808. -interface IERC6150ParentTransferable is IERC6150 { - /** - * @notice Emitted when the parent of `tokenId` token changed. - * @param tokenId The token changed - * @param oldParentId Previous parent token - * @param newParentId New parent token - */ - event ParentTransferred( - uint256 tokenId, - uint256 oldParentId, - uint256 newParentId - ); - - /** - * @notice Transfer parentship of `tokenId` token to a new parent token - * @param newParentId New parent token id - * @param tokenId The token to be changed - */ - function transferParent(uint256 newParentId, uint256 tokenId) external; - - /** - * @notice Batch transfer parentship of `tokenIds` to a new parent token - * @param newParentId New parent token id - * @param tokenIds Array of token ids to be changed - */ - function batchTransferParent( - uint256 newParentId, - uint256[] memory tokenIds - ) external; -} -``` - -Optional Extension: Access Control - -```solidity -// Note: the ERC-165 identifier for this interface is 0x1d04f0b3. -interface IERC6150AccessControl is IERC6150 { - /** - * @notice Check the account whether a admin of `tokenId` token. - * @dev Each token can be set more than one admin. Admin have permission to do something to the token, like mint child token, - * or burn token, or transfer parentship. - * @param tokenId The specified token - * @param account The account to be checked - * @return If the account has admin permission, return true; otherwise, return false. - */ - function isAdminOf(uint256 tokenId, address account) - external - view - returns (bool); - - /** - * @notice Check whether the specified parent token and account can mint children tokens - * @dev If the `parentId` is zero, check whether account can mint root nodes - * @param parentId The specified parent token to be checked - * @param account The specified account to be checked - * @return If the token and account has mint permission, return true; otherwise, return false. - */ - function canMintChildren( - uint256 parentId, - address account - ) external view returns (bool); - - /** - * @notice Check whether the specified token can be burnt by specified account - * @param tokenId The specified token to be checked - * @param account The specified account to be checked - * @return If the tokenId can be burnt by account, return true; otherwise, return false. - */ - function canBurnTokenByAccount(uint256 tokenId, address account) - external - view - returns (bool); -} -``` - -## Rationale - -As mentioned in the abstract, this EIP's goal is to have a simple interface for supporting Hierarchical NFTs. Here are a few design decisions and why they were made: - -### Relationship between NFTs - -All NFTs will make up a hierarchical relationship tree. Each NFT is a node of the tree, maybe as a root node or a leaf node, as a parent node or a child node. - -This proposal standardizes the event `Minted` to indicate the parent and child relationship when minting a new node. When a root node is minted, parentId should be zero. That means a token id of zero could not be a real node. So a real node token id must be greater than zero. - -In a hierarchical tree, it's common to query upper and lower nodes. So this proposal standardizes function `parentOf` to get the parent node of the specified node and standardizes function `childrenOf` to get all children nodes. - -Functions `isRoot` and `isLeaf` can check if one node is a root node or a leaf node, which would be very useful for many cases. - -### Enumerable Extension - -This proposal standardizes three functions as an extension to support enumerable queries involving children nodes. Each function all have param `parentId`, for compatibility, when the `parentId` specified zero means query root nodes. - -### ParentTransferable Extension - -In some cases, such as filesystem, a directory or a file could be moved from one directory to another. So this proposal adds ParentTransferable Extension to support this situation. - -### Access Control - -In a hierarchical structure, usually, there is more than one account has permission to operate a node, like mint children nodes, transfer node, burn node. This proposal adds a few functions as standard to check access control permissions. - -## Backwards Compatibility - -This proposal is fully backward compatible with [EIP-721](./eip-721.md). - -## Reference Implementation - -Implementation: [EIP-6150](../assets/eip-6150/contracts/ERC6150.sol) - -## Security Considerations - -No security considerations were found. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6150.md diff --git a/EIPS/eip-6170.md b/EIPS/eip-6170.md index f6e6f70bcff3bb..d321c85af1d602 100644 --- a/EIPS/eip-6170.md +++ b/EIPS/eip-6170.md @@ -1,90 +1,7 @@ --- eip: 6170 -title: Cross-Chain Messaging Interface -description: A common smart contract interface for interacting with messaging protocols. -author: Sujith Somraaj (@sujithsomraaj) -discussions-to: https://ethereum-magicians.org/t/cross-chain-messaging-standard/12197 -status: Draft -type: Standards Track category: ERC -created: 2022-12-19 +status: Moved --- -## Abstract - -This EIP standardizes an interface for cross-chain messengers, providing basic functionality to send and receive a cross-chain message (state). - -## Motivation - -Cross-chain messaging protocols lack standardization, resulting in unnecessarily complex competing implementations: Layerzero, Hyperlane & Wormhole each use a different interface. This makes integration difficult at the aggregator or plugin layer for protocols that must conform to any standards and forces each protocol to implement its adapter, which might be error-prone. - -Even chain-native arbitrary messaging protocols like the MATIC State Tunnel have an application-specific interface. - -## Specification - -The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -Every compliant messaging tunnel must implement the following interface. - -``` solidity -pragma solidity >=0.8.0; - -/// @title Cross-Chain Messaging interface -/// @dev Allows seamless interchain messaging. -/// @author Sujith Somraaj -/// Note: Bytes are used throughout the implementation to support non-evm chains. - -interface EIP6170 { - /// @dev This emits when a cross-chain message is sent. - /// Note: MessageSent MUST trigger when a message is sent, including zero bytes transfers. - event MessageSent(bytes _from, bytes _to, bytes _toChainId, bytes _message, bytes _extraData); - - /// @dev This emits when a cross-chain message is received. - /// MessageReceived MUST trigger on any successful call to receiveMessage(bytes chainId, bytes sender, bytes message) function. - event MessageReceived(bytes _from, bytes _fromChainId, bytes message); - - - /// @dev Sends a message to a receiving address on a different blockchain. - /// @param chainId is the unique identifier of receiving blockchain. - /// @param receiver is the address of the receiver. - /// @param message is the arbitrary message to be delivered. - /// @param data is a bridge-specific encoded data for off-chain relayer infrastructure. - /// @return the status of the process on the sending chain. - /// Note: this function is designed to support both evm and non-evm chains - /// Note: proposing chain-ids be the bytes encoding their native token name string. For eg., abi.encode("ETH"), abi.encode("SOL") imagining they cannot override. - function sendMessage( - bytes memory chainId, - bytes memory receiver, - bytes memory message, - bytes memory data - ) external returns (bool); - - /// @dev Receives a message from a sender on a different blockchain. - /// @param chainId is the unique identifier of the sending blockchain. - /// @param sender is the address of the sender. - /// @param message is the arbitrary message sent by the sender. - /// @return the status of message processing/storage. - /// Note: sender validation (or) message validation should happen before processing the message. - function receiveMessage( - bytes memory chainId, - bytes memory sender, - bytes memory message - ) external returns (bool); -} -``` - -## Rationale - -The Cross-Chain interface is designed to be optimized for interoperability layer integrators with a feature-complete, yet minimal interface. Validations such as sender authentication, receiver whitelisting, relayer mechanisms and cross-chain execution overrides are intentionally not specified, as Messaging protocols are expected to be treated as black boxes on-chain and inspected off-chain before use. - -## Security Considerations - -Fully permissionless messaging could be a security threat to the protocol. It is recommended that all the integrators review the implementation of messaging tunnels before integrating. - -For eg., without sender authentication, anyone could write arbitrary messages into the receiving smart contract. - -This EIP focuses only on the way the messages should be sent and received with a specific standard. But any authentication (or) message tunnel-specific operations can be implemented inside the receive function by integrators. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md) +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6170.md diff --git a/EIPS/eip-6188.md b/EIPS/eip-6188.md index 1e5c982af92a2b..39de8e61fa28da 100644 --- a/EIPS/eip-6188.md +++ b/EIPS/eip-6188.md @@ -2,9 +2,9 @@ eip: 6188 title: Nonce Cap description: Caps the nonce at 2^64-2 -author: Pandapip1 (@Pandapip1) +author: Gavin John (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-6190-functional-selfdestruct/12232 -status: Review +status: Stagnant type: Standards Track category: Core created: 2022-12-20 @@ -37,7 +37,7 @@ Capping a nonce allows for contracts with special properties to be created, with ## Backwards Compatibility -This EIP requires a protocol upgrade, since it modifies consensus rules. The further restriction of nonce should not have an effect on accounts, as reaching a nonce of `2^64-2` is unfeasible. +This EIP requires a protocol upgrade, since it modifies consensus rules. The further restriction of nonce should not have an effect on accounts, as reaching a nonce of `2^64-2` is difficult. ## Security Considerations diff --git a/EIPS/eip-6189.md b/EIPS/eip-6189.md index 4f9414edbf81a0..c32902ce087078 100644 --- a/EIPS/eip-6189.md +++ b/EIPS/eip-6189.md @@ -2,9 +2,9 @@ eip: 6189 title: Alias Contracts description: Allows the creation of contracts that forward calls to other contracts -author: Pandapip1 (@Pandapip1) +author: Gavin John (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-6190-functional-selfdestruct/12232 -status: Review +status: Stagnant type: Standards Track category: Core created: 2022-12-20 @@ -17,7 +17,7 @@ This EIP allows contracts to be turned into "alias contracts" using a magic nonc ## Motivation -This EIP is not terribly useful on its own, as it adds additional computation and gas costs without any useful side effects. However, in conjunction with another EIP, it can be used to make SELFDESTRUCT compatible with Verkle trees. +This EIP is not terribly useful on its own, as it adds additional computation and gas costs without any useful side effects. However, in conjunction with [EIP-6190](./eip-6190.md), it can be used to make SELFDESTRUCT compatible with Verkle trees. ## Specification @@ -37,38 +37,64 @@ A contract is an alias contract if its nonce is `2^64-1`, and its contract code The "callee" refers to the account that is being called or being paid. -If the nonce of the callee is `2^64-1`, the call is forwarded to the address stored in the `0`th storage slot of the callee (as if the callee was the address stored in the `0`th storage slot of the callee). This repeats until a non-alias contract is reached. The `CALLER` remains unchanged. +If the nonce of the callee is `2^64-1`, the call MUST be forwarded to the address stored in the `0`th storage slot of the callee (as if the callee was the address stored in the `0`th storage slot of the callee). This MUST repeat until a non-alias contract is reached. The `CALLER` MUST remain unchanged. -If there is more than one alias contract in the chain, the original callee and all subsequent callees (except the last one) have their `0`th storage slot set to the address of the final non-alias contract. Then, the call is forwarded as usual. **This occurs even in a read-only context.** +If there is more than one alias contract in the chain, the original callee and all subsequent callees (except the last one) MUST have their `0`th storage slot set to the address of the final non-alias contract. Then, the call MUST be forwarded as usual. **This MUST occur, even in a read-only context like `STATICCALL`.** For example, if `A` is an alias contract that forwards calls to `B`, which is an alias contract that forwards calls to `C`, then `A`'s `0`th storage slot is set to `C`'s address. Then, the call is forwarded to `C`. -The `CALL`, `CALLCODE`, `DELEGATECALL`, and `STATICCALL` opcodes and EOA Transactions MUST cost an `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)). For every account whose `0`th storage slot is updated, those opcodes must also cost an additional `5000` gas. +Finally, the opcode MUST proceed as usual, using the final non-alias contract. -If an infinite loop occurs, the transaction runs out of gas and reverts. +The `CALL`, `CALLCODE`, `DELEGATECALL`, and `STATICCALL` opcodes and EOA Transactions MUST cost an `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)). For every account whose `0`th storage slot is updated, those opcodes MUST also cost an additional `5000` gas. + +If an infinite loop occurs, the transaction MUST run out of gas and revert. #### `EXTCODEHASH`, `EXTCODECOPY`, `EXTCODESIZE`, and `BALANCE` The "accessed account" refers to the account that is being accessed (i.e. the account whose code is being accessed, or the account whose balance is being accessed). -Similar to the `CALL` family of opcodes, if the nonce of the accessed account is `2^64-1`, the accessed account is replaced with the address stored in the `0`th storage slot of the accessed account. This repeats until a non-alias contract is reached. +Similar to the `CALL` family of opcodes, if the nonce of the accessed account is `2^64-1`, the accessed account's address MUST be replaced with the address stored in the `0`th storage slot of the accessed account. This MUST repeat until a non-alias contract is reached. -If there is more than one alias contract in the chain, the original accessed account and all subsequent accessed accounts (except the last one) have their `0`th storage slot set to the address of the final non-alias contract. Then, the accessed account is replaced as usual. +If there is more than one alias contract in the chain, the original accessed account and all subsequent accessed accounts (except the last one) MUST have their `0`th storage slot set to the address of the final non-alias contract. Then, the accessed account MUST be replaced as usual. **This MUST occur, even in a read-only context like `STATICCALL`.** -The `EXTCODEHASH`, `EXTCODECOPY`, `EXTCODESIZE`, and `BALANCE` opcodes MUST cost an `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)). For every account whose `0`th storage slot is updated, those opcodes must also cost an additional `5000` gas. +Finally, the opcode MUST proceed as usual, using the final non-alias contract. -If an infinite loop occurs, the transaction runs out of gas and reverts. +The `EXTCODEHASH`, `EXTCODECOPY`, `EXTCODESIZE`, and `BALANCE` opcodes MUST cost an `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)). For every account whose `0`th storage slot is updated, those opcodes MUST also cost an additional `5000` gas. + +If an infinite loop occurs, the transaction MUST run out of gas and revert. #### `CREATE` and `CREATE2` -If `CREATE` or `CREATE2` would fail because there is already a an account at the address, and that contract's code is `0x1`, and its nonce is `2^64-1`, then instead of failing, an attempt should be made to create a contract at the address stored in the `0`th storage slot of the existing contract. This repeats until a non-alias contract is reached, at which point either the creation succeeds, or it fails because there is already an account at the address. +If `CREATE` or `CREATE2` would create (or fail to create, depending on which EIPs are used) an account at an address, and that account's code is `0x1`, and its nonce is `2^64-1`, then instead of reverting, an attempt MUST be made to create a contract at the address stored in the `0`th storage slot of the existing account. This MUST repeat until a non-alias contract is reached. -Regardless of if creation succeeds, if there is more than one alias contract in the chain, the original accessed account and all subsequent accessed accounts (except the last one) have their `0`th storage slot set to the address of the final non-alias contract. Then, the accessed account is replaced as usual. +If there is more than one alias contract in the chain, the original accessed account and all subsequent accessed accounts (except the last one) MUST have their `0`th storage slot set to the address of the final non-alias contract. + +Finally, the opcode MUST proceed as usual, returning the address of the newly-created contract. The `CREATE` and `CREATE2` opcodes MUST cost an `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)). For every account whose `0`th storage slot is updated, those opcodes must also cost an additional `5000` gas. If an infinite loop occurs, the transaction runs out of gas and reverts. +#### `ADDRESS` + +This opcode remains unchanged; `ADDRESS` points to the address that doesn't have a nonce of `2^64-1`.33 + +### Transfers to the zero address + +Transfers to the zero address continue to have the same effect as the `CREATE` opcode, and will cost extra gas as discussed in the [`CREATE` and `CREATE2`](#create-and-create2) section. + +### Transaction Validity + +The "origin" refers to the account that sent the transaction to be validated. + +If the nonce of the origin is `2^64-1`, the origin MUST be updated to the address stored in the `0`th storage slot of the current origin (as if the origin was the address stored in the `0`th storage slot of the current origin). This MUST repeat until a non-alias contract is reached. + +If there is more than one alias contract in the chain, the original origin and all subsequent origins (except the last one) MUST have their `0`th storage slot set to the address of the final non-alias contract. Then, the call MUST be forwarded as usual. + +An additional `25` gas per account accessed in this manner (including the final one, and including if no aliased accounts were used), in addition to all the regular costs incurred by accessing accounts (see [EIP-2929](./eip-2929.md)) is added to the validation costs. For every account whose `0`th storage slot is updated, it also costs an additional `5000` gas. + +Finally, validation proceeds as normal. + ### RPC Endpoint Changes #### `eth_getStorageAt` diff --git a/EIPS/eip-6190.md b/EIPS/eip-6190.md index 61f31f4ecbf518..d83213ff22d4c6 100644 --- a/EIPS/eip-6190.md +++ b/EIPS/eip-6190.md @@ -2,9 +2,9 @@ eip: 6190 title: Verkle-compatible SELFDESTRUCT description: Changes SELFDESTRUCT to only cause a finite number of state changes -author: Pandapip1 (@Pandapip1) +author: Gavin John (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-6190-functional-selfdestruct/12232 -status: Review +status: Stagnant type: Standards Track category: Core created: 2022-12-20 diff --git a/EIPS/eip-6206.md b/EIPS/eip-6206.md index 8f9a24ed13dec0..c9784946082421 100644 --- a/EIPS/eip-6206.md +++ b/EIPS/eip-6206.md @@ -1,10 +1,10 @@ --- eip: 6206 -title: EOF - JUMPF instruction +title: EOF - JUMPF and non-returning functions description: Introduces instruction for chaining function calls. author: Andrei Maiboroda (@gumb0), Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Matt Garnett (@lightclient) discussions-to: https://ethereum-magicians.org/t/eip-4750-eof-functions/8195 -status: Draft +status: Review type: Standards Track category: Core created: 2022-12-21 @@ -15,35 +15,63 @@ requires: 4750, 5450 This EIP allows for tail call optimizations in EOF functions ([EIP-4750](./eip-4750.md)) by introducing a new instruction `JUMPF`, which jumps to a code section without adding a new return stack frame. +Additionally the format of the type sections is extended to allow declaring sections as non-returning, with simplified stack validation for `JUMPF` to such section. + ## Motivation It is common for functions to make a call at the end of the routine only to then return. `JUMPF` optimizes this behavior by changing code sections without needing to update the return stack. +Knowing at validation time that a function will never return control allows for `JUMPF` to such function to be treated similar to terminating instructions, where extra items may be left on the operand stack at execution termination. This provides opportunities for compilers to generate more optimal code, both in code size and in spent gas. It is particularly beneficial for small error handling helpers, that end execution with `REVERT`: they are commonly reused in multiple branches and extracting them into a helper function is efficient, when there is no need to pop extra stack items before `JUMPF` to such helper. + ## Specification -A new instruction, `JUMPF (0xb2)`, is introduced. +### Type section changes + +We define non-returning section as the one that can not return control (via `RETF` instruction) to the caller section. + +Type section `outputs` field contains a special value `0x80` when corresponding code section is non-returning. See [Non-returning status validation](#non-returning-status-validation) below for validation details. + +The first code section MUST have 0 inputs and be non-returning. ### Execution Semantics -1. `JUMPF` has one immediate argument, `code_section_index`, encoded as a 16-bit unsigned big-endian value. -2. If the operand stack size exceeds `1024 - type[code_section_index].max_stack_height` (i.e. if the called function may exceed the global stack height limit), execution results in an exceptional halt. This guarantees that the stack height after the call is within the limits. -3. `JUMPF` costs 5 gas. -4. `JUMPF` neither pops nor pushes anything to the operand stack. +A new instruction, `JUMPF (0xe5)`, is introduced. + +1. `JUMPF` has one immediate argument, `target_section_index`, encoded as a 16-bit unsigned big-endian value. +2. If the operand stack size exceeds `1024 - type[target_section_index].max_stack_height + type[target_section_index].inputs` (i.e. if the called function may exceed the global stack height limit), execution results in an exceptional halt. This guarantees that the target function does not exceed global stack height limit. +3. `JUMPF` sets `current_section_index` to `target_section_index` and `PC` to `0`, but does not change the return stack. Execution continues in the target section. +4. `JUMPF` costs 5 gas. +5. `JUMPF` neither pops nor pushes anything to the operand stack. ### Code Validation -Let the definition of `type[i]` be inherited from [EIP-4750](./eip-4750.md) and define `stack_height` to be the height of the stack at a certain instruction during the instruction flow traversal if the operand stack at the start of the function were equal to `type[i].inputs`. +Let the definition of `type[i]` be inherited from [EIP-4750](./eip-4750.md) and define `stack_height_min` and `stack_height_max` to be the stack height bounds at a certain instruction during the instruction flow traversal. * The immediate argument of `JUMPF` MUST be less than the total number of code sections. -* For each `JUMPF` instruction `type[current_section_index].outputs` MUST be greater or equal `type[code_section_index].outputs`. -* The stack height at `JUMPF` MUST be equal to `type[current_section_index].outputs + type[code_section_index].inputs - type[code_section_index].outputs`. This means that `code_section_index` can output less stack elements than the original code section called by the top element on the return stack, if the `current_section_index` code section leaves the delta `type[current_section_index].outputs - type[code_section_index].outputs` element(s) on the stack. +* For each `JUMPF` instruction: + * either `type[current_section_index].outputs` MUST be greater or equal `type[target_section_index].outputs`, + * or `type[target_section_index].outputs` MUST be `0x80` +* The stack height validation at `JUMPF` depends on whether the target section is non-returning: + * `JUMPF` into returning section (`type[target_section_index].outputs` does not equal `0x80`): `stack_height_min` and `stack_height_max` MUST be equal to `type[current_section_index].outputs + type[target_section_index].inputs - type[target_section_index].outputs`. This means that target section can output less stack elements than the original code section called by the top element on the return stack, if the current code section leaves the delta `type[current_section_index].outputs - type[target_section_index].outputs` element(s) on the stack. + * `JUMPF` into non-returning section (`type[target_section_index].outputs` equals `0x80`): `stack_height_min` MUST be greater than or equal to `type[target_section_index].inputs`. +* Stack overflow check at `JUMPF`: `stack_height_max` MUST be less than or equal to `1024 - types[target_section_index].max_stack_height + types[target_section_index].inputs`. +* `JUMPF` is considered terminating instruction, i.e. does not have successor instructions in code validation and MAY be final instruction in the section. * The code validation defined in [EIP-4200](./eip-4200.md) also fails if any `RJUMP*` offset points to one of the two bytes directly following a `JUMPF` instruction. +`CALLF` instruction validation is extended to include the rule: + +* Code section is invalid in case an immediate argument `target_section_index` of any `CALLF` targets a non-returning section, i.e. `type[target_section_index]` equals `0x80`. + +#### Non-returning status validation + +Section type MUST be non-returning in case the section contains no `RETF` instructions and no `JUMPF` instructions targeting returning sections (target section's status is checked via its output value in type section.) +*Note: This implies that section containing only `JUMPF`s into non-returning sections is non-returning itself.* + ## Rationale ### Allowing `JUMPF` to section with less outputs -As long as `JUMPF` prepares the delta `type[current_section_index].outputs - type[code_section_index].outputs` stack elements before changing code sections, it is possible to jump to a section with less outputs than was originally entered via `CALLF`. This will reduce duplicated code as it will allow compilers more flexibility during code generation such that certain helpers can be used generically by functions, regardless of their output values. +As long as `JUMPF` prepares the delta `type[current_section_index].outputs - type[target_section_index].outputs` stack elements before changing code sections, it is possible to jump to a section with less outputs than was originally entered via `CALLF`. This will reduce duplicated code as it will allow compilers more flexibility during code generation such that certain helpers can be used generically by functions, regardless of their output values. ## Backwards Compatibility diff --git a/EIPS/eip-6220.md b/EIPS/eip-6220.md index d1d215785e14ed..607258bad63955 100644 --- a/EIPS/eip-6220.md +++ b/EIPS/eip-6220.md @@ -1,477 +1,7 @@ --- eip: 6220 -title: Composable NFTs utilizing Equippable Parts -description: An interface for Composable non-fungible tokens through fixed and slot parts equipping. -author: Bruno Škvorc (@Swader), Cicada (@CicadaNCR), Steven Pineda (@steven2308), Stevan Bogosavljevic (@stevyhacker), Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/eip-6220-composable-nfts-utilizing-equippable-parts/12289 -status: Review -type: Standards Track category: ERC -created: 2022-12-20 -requires: 165, 721, 5773, 6059 +status: Moved --- -## Abstract - -The Composable NFTs utilizing equippable parts standard extends [EIP-721](./eip-721.md) by allowing the NFTs to selectively add parts to themselves via equipping. - -Tokens can be composed by cherry picking the list of parts from a Catalog for each NFT instance, and are able to equip other NFTs into slots, which are also defined within the Catalog. Catalogs contain parts from which NFTs can be composed. - -This proposal introduces two types of parts; slot type of parts and fixed type of parts. The slot type of parts allow for other NFT collections to be equipped into them, while fixed parts are full components with their own metadata. - -Equipping a part into an NFT doesn't generate a new token, but rather adds another component to be rendered when retrieving the token. - -## Motivation - -With NFTs being a widespread form of tokens in the Ethereum ecosystem and being used for a variety of use cases, it is time to standardize additional utility for them. Having the ability for tokens to equip other tokens and be composed from a set of available parts allows for greater utility, usability and forward compatibility. - -In the four years since [EIP-721](./eip-721.md) was published, the need for additional functionality has resulted in countless extensions. This EIP improves upon EIP-721 in the following areas: - -- [Composing](#composing) -- [Token progression](#token-progression) -- [Merit tracking](#merit-tracking) -- [Provable Digital Scarcity](#provable-digital-scarcity) - -### Composing - -NFTs can work together to create a greater construct. Prior to this proposal, multiple NFTs could be composed into a single construct either by checking all of the compatible NFTs associated with a given account and used indiscriminately (which could result in unexpected result if there was more than one NFT intended to be used in the same slot), or by keeping a custom ledger of parts to compose together (either in a smart contract or an off-chain database). This proposal establishes a standardized framework for composable NFTs, where a single NFT can select which parts should be a part of the whole, with the information being on chain. Composing NFTs in such a way allows for virtually unbounded customization of the base NFT. An example of this could be a movie NFT. Some parts, like credits, should be fixed. Other parts, like scenes, should be interchangeable, so that various releases (base version, extended cuts, anniversary editions,...) can be replaced. - -### Token progression - -As the token progresses through various stages of its existence, it can attain or be awarded various parts. This can be explained in terms of gaming. A character could be represented by an NFT utilizing this proposal and would be able to equip gear acquired through the gameplay activities and as it progresses further in the game, better items would be available. In stead of having numerous NFTs representing the items collected through its progression, equippable parts can be unlocked and the NFT owner would be able to decide which items to equip and which to keep in the inventory (not equipped) without need of a centralized party. - -### Merit tracking - -An equippable NFT can also be used to track merit. An example of this is academic merit. The equippable NFT in this case would represent a sort of digital portfolio of academic achievements, where the owner would be able to equip their diplomas, published articles and awards for all to see. - -### Provable Digital Scarcity - -The majority of current NFT projects are only mock-scarce. Even with a limited supply of tokens, the utility of these (if any) is uncapped. As an example, you can log into 500 different instances of the same game using the same wallet and the same NFT. You can then equip the same hat onto 500 different in-game avatars at the same time, because its visual representation is just a client-side mechanic. - -This proposal adds the ability to enforce that, if a hat is equipped on one avatar (by being sent into it and then equipped), it cannot be equipped on another. This provides real digital scarcity. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -### Equippable tokens - -The interface of the core smart contract of the equippable tokens. - -```solidity -/// @title EIP-6220 Composable NFTs utilizing Equippable Parts -/// @dev See https://eips.ethereum.org/EIPS/eip-6220 -/// @dev Note: the ERC-165 identifier for this interface is 0x28bc9ae4. - -pragma solidity ^0.8.16; - -import "./IERC5773.sol"; - -interface IEquippable is IERC5773 { - /** - * @notice Used to store the core structure of the `Equippable` component. - * @return assetId The ID of the asset equipping a child - * @return childAssetId The ID of the asset used as equipment - * @return childId The ID of token that is equipped - * @return childEquippableAddress Address of the collection to which the child asset belongs to - */ - struct Equipment { - uint64 assetId; - uint64 childAssetId; - uint256 childId; - address childEquippableAddress; - } - - /** - * @notice Used to provide a struct for inputing equip data. - * @dev Only used for input and not storage of data. - * @return tokenId ID of the token we are managing - * @return childIndex Index of a child in the list of token's active children - * @return assetId ID of the asset that we are equipping into - * @return slotPartId ID of the slot part that we are using to equip - * @return childAssetId ID of the asset that we are equipping - */ - struct IntakeEquip { - uint256 tokenId; - uint256 childIndex; - uint64 assetId; - uint64 slotPartId; - uint64 childAssetId; - } - - /** - * @notice Used to notify listeners that a child's asset has been equipped into one of its parent assets. - * @param tokenId ID of the token that had an asset equipped - * @param assetId ID of the asset associated with the token we are equipping into - * @param slotPartId ID of the slot we are using to equip - * @param childId ID of the child token we are equipping into the slot - * @param childAddress Address of the child token's collection - * @param childAssetId ID of the asset associated with the token we are equipping - */ - event ChildAssetEquipped( - uint256 indexed tokenId, - uint64 indexed assetId, - uint64 indexed slotPartId, - uint256 childId, - address childAddress, - uint64 childAssetId - ); - - /** - * @notice Used to notify listeners that a child's asset has been unequipped from one of its parent assets. - * @param tokenId ID of the token that had an asset unequipped - * @param assetId ID of the asset associated with the token we are unequipping out of - * @param slotPartId ID of the slot we are unequipping from - * @param childId ID of the token being unequipped - * @param childAddress Address of the collection that a token that is being unequipped belongs to - * @param childAssetId ID of the asset associated with the token we are unequipping - */ - event ChildAssetUnequipped( - uint256 indexed tokenId, - uint64 indexed assetId, - uint64 indexed slotPartId, - uint256 childId, - address childAddress, - uint64 childAssetId - ); - - /** - * @notice Used to notify listeners that the assets belonging to a `equippableGroupId` have been marked as - * equippable into a given slot and parent - * @param equippableGroupId ID of the equippable group being marked as equippable into the slot associated with - * `slotPartId` of the `parentAddress` collection - * @param slotPartId ID of the slot part of the catalog into which the parts belonging to the equippable group - * associated with `equippableGroupId` can be equipped - * @param parentAddress Address of the collection into which the parts belonging to `equippableGroupId` can be - * equipped - */ - event ValidParentEquippableGroupIdSet( - uint64 indexed equippableGroupId, - uint64 indexed slotPartId, - address parentAddress - ); - - /** - * @notice Used to equip a child into a token. - * @dev The `IntakeEquip` stuct contains the following data: - * [ - * tokenId, - * childIndex, - * assetId, - * slotPartId, - * childAssetId - * ] - * @param data An `IntakeEquip` struct specifying the equip data - */ - function equip( - IntakeEquip memory data - ) external; - - /** - * @notice Used to unequip child from parent token. - * @dev This can only be called by the owner of the token or by an account that has been granted permission to - * manage the given token by the current owner. - * @param tokenId ID of the parent from which the child is being unequipped - * @param assetId ID of the parent's asset that contains the `Slot` into which the child is equipped - * @param slotPartId ID of the `Slot` from which to unequip the child - */ - function unequip( - uint256 tokenId, - uint64 assetId, - uint64 slotPartId - ) external; - - /** - * @notice Used to check whether the token has a given child equipped. - * @dev This is used to prevent from transferring a child that is equipped. - * @param tokenId ID of the parent token for which we are querying for - * @param childAddress Address of the child token's smart contract - * @param childId ID of the child token - * @return bool The boolean value indicating whether the child token is equipped into the given token or not - */ - function isChildEquipped( - uint256 tokenId, - address childAddress, - uint256 childId - ) external view returns (bool); - - /** - * @notice Used to verify whether a token can be equipped into a given parent's slot. - * @param parent Address of the parent token's smart contract - * @param tokenId ID of the token we want to equip - * @param assetId ID of the asset associated with the token we want to equip - * @param slotId ID of the slot that we want to equip the token into - * @return bool The boolean indicating whether the token with the given asset can be equipped into the desired - * slot - */ - function canTokenBeEquippedWithAssetIntoSlot( - address parent, - uint256 tokenId, - uint64 assetId, - uint64 slotId - ) external view returns (bool); - - /** - * @notice Used to get the Equipment object equipped into the specified slot of the desired token. - * @dev The `Equipment` struct consists of the following data: - * [ - * assetId, - * childAssetId, - * childId, - * childEquippableAddress - * ] - * @param tokenId ID of the token for which we are retrieving the equipped object - * @param targetCatalogAddress Address of the `Catalog` associated with the `Slot` part of the token - * @param slotPartId ID of the `Slot` part that we are checking for equipped objects - * @return struct The `Equipment` struct containing data about the equipped object - */ - function getEquipment( - uint256 tokenId, - address targetCatalogAddress, - uint64 slotPartId - ) external view returns (Equipment memory); - - /** - * @notice Used to get the asset and equippable data associated with given `assetId`. - * @param tokenId ID of the token for which to retrieve the asset - * @param assetId ID of the asset of which we are retrieving - * @return metadataURI The metadata URI of the asset - * @return equippableGroupId ID of the equippable group this asset belongs to - * @return catalogAddress The address of the catalog the part belongs to - * @return partIds An array of IDs of parts included in the asset - */ - function getAssetAndEquippableData(uint256 tokenId, uint64 assetId) - external - view - returns ( - string memory metadataURI, - uint64 equippableGroupId, - address catalogAddress, - uint64[] calldata partIds - ); -} -``` - -### Catalog - -The interface of the Catalog containing the equippable parts. Catalogs are collections of equippable fixed and slot parts and are not restricted to a single collection, but can support any number of NFT collections. - -```solidity -/** - * @title ICatalog - * @notice An interface Catalog for equippable module. - * @dev Note: the ERC-165 identifier for this interface is 0xd912401f. - */ - -pragma solidity ^0.8.16; - -import "./IERC165.sol"; - -interface ICatalog is IERC165 { - /** - * @notice Event to announce addition of a new part. - * @dev It is emitted when a new part is added. - * @param partId ID of the part that was added - * @param itemType Enum value specifying whether the part is `None`, `Slot` and `Fixed` - * @param zIndex An uint specifying the z value of the part. It is used to specify the depth which the part should - * be rendered at - * @param equippableAddresses An array of addresses that can equip this part - * @param metadataURI The metadata URI of the part - */ - event AddedPart( - uint64 indexed partId, - ItemType indexed itemType, - uint8 zIndex, - address[] equippableAddresses, - string metadataURI - ); - - /** - * @notice Event to announce new equippables to the part. - * @dev It is emitted when new addresses are marked as equippable for `partId`. - * @param partId ID of the part that had new equippable addresses added - * @param equippableAddresses An array of the new addresses that can equip this part - */ - event AddedEquippables( - uint64 indexed partId, - address[] equippableAddresses - ); - - /** - * @notice Event to announce the overriding of equippable addresses of the part. - * @dev It is emitted when the existing list of addresses marked as equippable for `partId` is overwritten by a new - * one. - * @param partId ID of the part whose list of equippable addresses was overwritten - * @param equippableAddresses The new, full, list of addresses that can equip this part - */ - event SetEquippables(uint64 indexed partId, address[] equippableAddresses); - - /** - * @notice Event to announce that a given part can be equipped by any address. - * @dev It is emitted when a given part is marked as equippable by any. - * @param partId ID of the part marked as equippable by any address - */ - event SetEquippableToAll(uint64 indexed partId); - - /** - * @notice Used to define a type of the item. Possible values are `None`, `Slot` or `Fixed`. - * @dev Used for fixed and slot parts. - */ - enum ItemType { - None, - Slot, - Fixed - } - - /** - * @notice The integral structure of a standard RMRK catalog item defining it. - * @dev Requires a minimum of 3 storage slots per catalog item, equivalent to roughly 60,000 gas as of Berlin hard fork - * (April 14, 2021), though 5-7 storage slots is more realistic, given the standard length of an IPFS URI. This - * will result in between 25,000,000 and 35,000,000 gas per 250 assets--the maximum block size of Ethereum - * mainnet is 30M at peak usage. - * @return itemType The item type of the part - * @return z The z value of the part defining how it should be rendered when presenting the full NFT - * @return equippable The array of addresses allowed to be equipped in this part - * @return metadataURI The metadata URI of the part - */ - struct Part { - ItemType itemType; //1 byte - uint8 z; //1 byte - address[] equippable; //n Collections that can be equipped into this slot - string metadataURI; //n bytes 32+ - } - - /** - * @notice The structure used to add a new `Part`. - * @dev The part is added with specified ID, so you have to make sure that you are using an unused `partId`, - * otherwise the addition of the part vill be reverted. - * @dev The full `IntakeStruct` looks like this: - * [ - * partID, - * [ - * itemType, - * z, - * [ - * permittedCollectionAddress0, - * permittedCollectionAddress1, - * permittedCollectionAddress2 - * ], - * metadataURI - * ] - * ] - * @return partId ID to be assigned to the `Part` - * @return part A `Part` to be added - */ - struct IntakeStruct { - uint64 partId; - Part part; - } - - /** - * @notice Used to return the metadata URI of the associated catalog. - * @return string Base metadata URI - */ - function getMetadataURI() external view returns (string memory); - - /** - * @notice Used to return the `itemType` of the associated catalog - * @return string `itemType` of the associated catalog - */ - function getType() external view returns (string memory); - - /** - * @notice Used to check whether the given address is allowed to equip the desired `Part`. - * @dev Returns true if a collection may equip asset with `partId`. - * @param partId The ID of the part that we are checking - * @param targetAddress The address that we are checking for whether the part can be equipped into it or not - * @return bool The status indicating whether the `targetAddress` can be equipped into `Part` with `partId` or not - */ - function checkIsEquippable(uint64 partId, address targetAddress) - external - view - returns (bool); - - /** - * @notice Used to check if the part is equippable by all addresses. - * @dev Returns true if part is equippable to all. - * @param partId ID of the part that we are checking - * @return bool The status indicating whether the part with `partId` can be equipped by any address or not - */ - function checkIsEquippableToAll(uint64 partId) external view returns (bool); - - /** - * @notice Used to retrieve a `Part` with id `partId` - * @param partId ID of the part that we are retrieving - * @return struct The `Part` struct associated with given `partId` - */ - function getPart(uint64 partId) external view returns (Part memory); - - /** - * @notice Used to retrieve multiple parts at the same time. - * @param partIds An array of part IDs that we want to retrieve - * @return struct An array of `Part` structs associated with given `partIds` - */ - function getParts(uint64[] calldata partIds) - external - view - returns (Part[] memory); -} -``` - -## Rationale - -Designing the proposal, we considered the following questions: - -1. **Why are we using a Catalog in stead of supporting direct NFT equipping?**\ -If NFTs could be directly equipped into other NFTs without any oversight, the resulting composite would be unpredictable. Catalog allows for parts to be pre-verified in order to result in a composite that composes as expected. Another benefit of Catalog is the ability of defining reusable fixed parts. -2. **Why do we propose two types of parts?**\ -Some parts, that are the same for all of the tokens, don't make sense to be represented by individual NFTs, so they can be represented by fixed parts. This reduces the clutter of the owner's wallet as well as introduces an efficient way of disseminating repetitive assets tied to NFTs.\ -The slot parts allow for equipping NFTs into them. This provides the ability to equip unrelated NFT collections into the base NFT after the unrelated collection has been verified to compose properly.\ -Having two parts allows for support of numerous use cases and, since the proposal doesn't enforce the use of both it can be applied in any configuration needed. -3. **Why is a method to get all of the equipped parts not included?**\ -Getting all parts might not be an operation necessary for all implementers. Additionally, it can be added either as an extension, doable with hooks, or can be emulated using an indexer. -4. **Should Catalog be limited to support one NFT collection at a time or be able to support any nunmber of collections?**\ -As the Catalog is designed in a way that is agnostic to the use case using it. It makes sense to support as wide reusability as possible. Having one Catalog supporting multiple collections allows for optimized operation and reduced gas prices when deploying it and setting fixed as well as slot parts. - -### Fixed parts - -Fixed parts are defined and contained in the Catalog. They have their own metadata and are not meant to change through the lifecycle of the NFT. - -A fixed part cannot be replaced. - -The benefit of fixed parts is that they represent equippable parts that can be equipped by any number of tokens in any number of collections and only need to be defined once. - -### Slot parts - -Slot parts are defined and contained in the Catalog. They don't have their own metadata, but rather support equipping of selected NFT collections into them. The tokens equipped into the slots however, contain their own metadata. This allows for an equippable modifialbe content of the base NFT controlled by its owner. As they can be equipped into any number of tokens of any number of collections, they allow for reliable composing of the final tokens by vetting which NFTs can be equipped by a given slot once and then reused any number of times. - -## Backwards Compatibility - -The Equippable token standard has been made compatible with [EIP-721](./eip-721.md) in order to take advantage of the robust tooling available for implementations of EIP-721 and to ensure compatibility with existing EIP-721 infrastructure. - -## Test Cases - -Tests are included in [`equippableFixedParts.ts`](../assets/eip-6220/test/equippableFixedParts.ts) and [`equippableSlotParts.ts`](../assets/eip-6220/test/equippableSlotParts.ts). - -To run them in terminal, you can use the following commands: - -``` -cd ../assets/eip-6220 -npm install -npx hardhat test -``` - -## Reference Implementation - -See [`EquippableToken.sol`](../assets/eip-6220/contracts/EquippableToken.sol). - - -## Security Considerations - -The same security considerations as with [EIP-721](./eip-721.md) apply: hidden logic may be present in any of the functions, including burn, add resource, accept resource, and more. - -Caution is advised when dealing with non-audited contracts. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6220.md diff --git a/EIPS/eip-6224.md b/EIPS/eip-6224.md index 0f815adc0948bc..1c1ff09216355a 100644 --- a/EIPS/eip-6224.md +++ b/EIPS/eip-6224.md @@ -1,255 +1,7 @@ --- eip: 6224 -title: Contracts Dependencies Registry -description: An interface for managing smart contracts with their dependencies. -author: Artem Chystiakov (@arvolear) -discussions-to: https://ethereum-magicians.org/t/eip-6224-contracts-dependencies-registry/12316 -status: Draft -type: Standards Track category: ERC -created: 2022-12-27 -requires: 1967, 5750 +status: Moved --- -## Abstract - -The EIP standardizes the management of smart contracts within the decentralized application ecosystem. It enables protocols to become upgradeable and reduces their maintenance threshold. This EIP additionally introduces a smart contract dependency injection mechanism to audit dependency usage, to aid larger composite projects. - -## Motivation - -In the ever-growing Ethereum, projects tend to become more and more complex. Modern protocols require portability and agility to satisfy customer needs by continuously delivering new features and staying on pace with the industry. However, the requirement is hard to achieve due to the immutable nature of blockchains and smart contracts. Moreover, the increased complexity and continuous delivery bring bugs and entangle the dependencies between the contracts, making systems less supportable. - -Applications that have a clear facade and transparency upon their dependencies are easier to develop and maintain. The given EIP tries to solve the aforementioned problems by presenting two concepts: the **contracts registry** and the **dependant**. - -The advantages of using the provided pattern might be: - -- Structured smart contracts management via specialized contract. -- Ad-hoc upgradeability provision. -- Runtime smart contracts addition, removal, and substitution. -- Dependency injection mechanism to keep smart contracts' dependencies under control. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -### ContractsRegistry - -The `ContractsRegistry` MUST implement the following interface: - -```solidity -pragma solidity ^0.8.0; - -interface IContractsRegistry { - /** - * @notice REQUIRED The event that is emitted when the contract gets added to the registry - * @param name the name of the contract - * @param contractAddress the address of the added contract - * @param isProxy whether the added contract is a proxy - */ - event AddedContract(string name, address contractAddress, bool isProxy); - - /** - * @notice REQUIRED The event that is emitted when the contract get removed from the registry - * @param name the name of the removed contract - */ - event RemovedContract(string name); - - /** - * @notice REQUIRED The function that returns an associated contract by the name - * @param name the name of the contract - * @return the address of the contract - */ - function getContract(string memory name) external view returns (address); - - /** - * @notice OPTIONAL The function that checks if a contract with a given name has been added - * @param name the name of the contract - * @return true if the contract is present in the registry - */ - function hasContract(string memory name) external view returns (bool); - - /** - * @notice RECOMMENDED The function that returns the admin of the added proxy contracts - * @return the proxy admin address - */ - function getProxyUpgrader() external view returns (address); - - /** - * @notice RECOMMENDED The function that returns an implementation of the given proxy contract - * @param name the name of the contract - * @return the implementation address - */ - function getImplementation(string memory name) external view returns (address); - - /** - * @notice REQUIRED The function that injects dependencies into the given contract. - * MUST call the setDependencies() with address(this) and bytes("") as arguments on the substituted contract - * @param name the name of the contract - */ - function injectDependencies(string memory name) external; - - /** - * @notice REQUIRED The function that injects dependencies into the given contract with extra data. - * MUST call the setDependencies() with address(this) and given data as arguments on the substituted contract - * @param name the name of the contract - * @param data the extra context data - */ - function injectDependenciesWithData( - string calldata name, - bytes calldata data - ) external; - - /** - * @notice REQUIRED The function that upgrades added proxy contract with a new implementation - * @param name the name of the proxy contract - * @param newImplementation the new implementation the proxy will be upgraded to - * - * It is the Owner's responsibility to ensure the compatibility between implementations - */ - function upgradeContract(string memory name, address newImplementation) external; - - /** - * @notice RECOMMENDED The function that upgrades added proxy contract with a new implementation, providing data - * @param name the name of the proxy contract - * @param newImplementation the new implementation the proxy will be upgraded to - * @param data the data that the new implementation will be called with. This can be an ABI encoded function call - * - * It is the Owner's responsibility to ensure the compatibility between implementations - */ - function upgradeContractAndCall( - string memory name, - address newImplementation, - bytes memory data - ) external; - - /** - * @notice REQUIRED The function that adds pure (non-proxy) contracts to the ContractsRegistry. The contracts MAY either be - * the ones the system does not have direct upgradeability control over or the ones that are not upgradeable by design - * @param name the name to associate the contract with - * @param contractAddress the address of the contract - */ - function addContract(string memory name, address contractAddress) external; - - /** - * @notice REQUIRED The function that adds the contracts and deploys the Transaprent proxy above them. - * It MAY be used to add contract that the ContractsRegistry has to be able to upgrade - * @param name the name to associate the contract with - * @param contractAddress the address of the implementation - */ - function addProxyContract(string memory name, address contractAddress) external; - - /** - * @notice RECOMMENDED The function that adds an already deployed proxy to the ContractsRegistry. It MAY be used - * when the system migrates to the new ContractRegistry. In that case, the new ProxyUpgrader MUST have the - * credentials to upgrade the newly added proxies - * @param name the name to associate the contract with - * @param contractAddress the address of the proxy - */ - function justAddProxyContract(string memory name, address contractAddress) external; - - /** - * @notice REQUIRED The function to remove contracts from the ContractsRegistry - * @param name the associated name with the contract - */ - function removeContract(string memory name) external; -} -``` - -- The `ContractsRegistry` MUST deploy the `ProxyUpgrader` contract in the constructor that MUST be set as an admin of `Transparent` proxies deployed via `addProxyContract` method. -- It MUST NOT be possible to add the zero address to the `ContractsRegistry`. -- The `ContractsRegistry` MUST use the `IDependant` interface in the `injectDependencies` and `injectDependenciesWithData` methods. - -### Dependant - -The `Dependant` contract is the one that depends on other contracts present in the system. In order to support dependency injection mechanism, the dependant contract MUST implement the following interface: - -```solidity -pragma solidity ^0.8.0; - -interface IDependant { - /** - * @notice The function that is called from the ContractsRegistry (or factory) to inject dependencies. - * @param contractsRegistry the registry to pull dependencies from - * @param data the extra data that might provide additional application-specific context/behavior - * - * The Dependant MUST perform a dependency injector access check to this method - */ - function setDependencies(address contractsRegistry, bytes calldata data) external; - - /** - * @notice The function that sets the new dependency injector. - * @param injector the new dependency injector - * - * The Dependant MUST perform a dependency injector access check to this method - */ - function setInjector(address injector) external; - - /** - * @notice The function that gets the current dependency injector - * @return the current dependency injector - */ - function getInjector() external view returns (address); -} -``` - -- The `Dependant` contract MUST pull its dependencies in the `setDependencies` method from the passed `contractsRegistry` address. -- The `Dependant` contract MAY store the dependency injector address in the special slot `0x3d1f25f1ac447e55e7fec744471c4dab1c6a2b6ffb897825f9ea3d2e8c9be583` (obtained as `bytes32(uint256(keccak256("eip6224.dependant.slot")) - 1)`). - - -## Rationale - -There are a few design decisions that have to be specified explicitly: - -### ContractsRegistry Rationale - -#### Usage - -The extensions of this EIP SHOULD add proper access control checks to the described non-view methods. - -The `getContract` and `getImplementation` methods MUST revert if the nonexistent contracts are queried. - -The `ContractsRegistry` MAY be set behind the proxy to enable runtime addition of custom methods. Applications MAY also leverage the pattern to develop custom tree-like `ContractsRegistry` data structures. - -#### Contracts identifier - -The `string` contracts identifier is chosen over the `uint256` and `bytes32` to maintain code readability and reduce the human-error chances when interacting with the `ContractsRegistry`. Being the topmost smart contract, it MAY be typical for the users to interact with it via block explorers or DAOs. Clarity was prioritized over gas usage. - -#### Proxy - -The `Transparent` proxy is chosen over the `UUPS` proxy to hand the upgradeability responsibility to the `ContractsRegistry` itself. The extensions of this EIP MAY use the proxy of their choice. - -### Dependant Rationale - -#### Dependencies - -The required dependencies MUST be set in the overridden `setDependencies` method, not in the `constructor` or `initializer` methods. - -The `data` parameter is provided to carry additional application-specific context. It MAY be used to extend the method's behavior. - -#### Injector - -Only the injector MUST be able to call the `setDependencies` and `setInjector` methods. The initial injector will be a zero address, in that case, the call MUST NOT revert on access control checks. The `setInjector` function is made `external` to support the dependency injection mechanism for factory-made contracts. However, the method SHOULD be used with extra care. - -The injector address MAY be stored in the dedicated slot `0x3d1f25f1ac447e55e7fec744471c4dab1c6a2b6ffb897825f9ea3d2e8c9be583` to exclude the chances of storage collision. - -## Reference Implementation - -*0xdistributedlab-solidity-library dev-modules* provides a reference implementation. - -## Security Considerations - -The described EIP must be used with extra care as the loss/leakage of credentials to the `ContractsRegistry` leads to the application's point of no return. The `ContractRegistry` is a cornerstone of the protocol, access must be granted to the trusted parties only. - -### ContractsRegistry Security Considerations - -- The non-view methods of `ContractsRegistry` contract MUST be overridden with proper access control checks. -- The `ContractsRegistry` does not perform any upgradeability checks between the proxy upgrades. It is the user's responsibility to make sure that the new implementation is compatible with the old one. - -### Dependant Security Considerations - -- The non-view methods of `Dependant` contract MUST be overridden with proper access control checks. Only the dependency injector MUST be able to call them. -- The `Dependant` contract MUST set its dependency injector no later than the first call to the `setDependencies` function is made. That being said, it is possible to front-run the first dependency injection. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6224.md diff --git a/EIPS/eip-6239.md b/EIPS/eip-6239.md new file mode 100644 index 00000000000000..e2fe2fccf68abd --- /dev/null +++ b/EIPS/eip-6239.md @@ -0,0 +1,7 @@ +--- +eip: 6239 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6239.md diff --git a/EIPS/eip-6268.md b/EIPS/eip-6268.md index 007c07ee693c38..dae74ec8a02677 100644 --- a/EIPS/eip-6268.md +++ b/EIPS/eip-6268.md @@ -1,88 +1,7 @@ --- eip: 6268 -title: Untransferability Indicator for EIP-1155 -description: An extension of EIP-1155 for indicating the transferability of the token. -author: Yuki Aoki (@yuki-js) -discussions-to: https://ethereum-magicians.org/t/sbt-implemented-in-erc1155/12182 -status: Draft -type: Standards Track category: ERC -created: 2022-01-06 -requires: 165, 1155 +status: Moved --- -## Abstract - -This EIP standardizes an interface indicating [EIP-1155](./eip-1155.md)-compatible token non-transferability using [EIP-165](./eip-165.md) feature detection. - -## Motivation - -Soulbound Tokens (SBT) are non-transferable tokens. While [EIP-5192](./eip-5192.md) standardizes non-fungible SBTs, a standard for Soulbound semi-fungible or fungible tokens does not yet exist. The introduction of a standard non-transferability indicator that is agnostic to fungibility promotes the usage of Souldbound semi-fungible or fungible tokens. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. - -Smart contracts implementing this standard MUST comform to the [EIP-1155](./eip-1155.md) specification. - -Smart contracts implementing this standard MUST implement all of the functions in the `IERC6268` interface. - -Smart contracts implementing this standard MUST implement the [EIP-165](./eip-165.md) supportsInterface function and MUST return the constant value true if `0xd87116f3` is passed through the interfaceID argument. - -For the token identifier `_id` that is marked as `locked`, `locked(_id)` MUST return the constant value true and any functions that try transferring the token, including `safeTransferFrom` and `safeBatchTransferFrom` function MUST throw. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.0; - -interface IERC6268 { - /// @notice Either `LockedSingle` or `LockedBatch` MUST emit when the locking status is changed to locked. - /// @dev If a token is minted and the status is locked, this event should be emitted. - /// @param _id The identifier for a token. - event LockedSingle(uint256 _id); - - /// @notice Either `LockedSingle` or `LockedBatch` MUST emit when the locking status is changed to locked. - /// @dev If a token is minted and the status is locked, this event should be emitted. - /// @param _ids The list of identifiers for tokens. - event LockedBatch(uint256[] _ids); - - /// @notice Either `UnlockedSingle` or `UnlockedBatch` MUST emit when the locking status is changed to unlocked. - /// @dev If a token is minted and the status is unlocked, this event should be emitted. - /// @param _id The identifier for a token. - event UnlockedSingle(uint256 _id); - - /// @notice Either `UnlockedSingle` or `UnlockedBatch` MUST emit when the locking status is changed to unlocked. - /// @dev If a token is minted and the status is unlocked, this event should be emitted. - /// @param _ids The list of identifiers for tokens. - event UnlockedBatch(uint256[] _ids); - - - /// @notice Returns the locking status of the token. - /// @dev SBTs assigned to zero address are considered invalid, and queries - /// about them do throw. - /// @param _id The identifier for a token. - function locked(uint256 _id) external view returns (bool); - - /// @notice Returns the locking statuses of the multiple tokens. - /// @dev SBTs assigned to zero address are considered invalid, and queries - /// about them do throw. - /// @param _ids The list of identifiers for tokens - function lockedBatch(uint256[] _ids) external view returns (bool); -} -``` - -## Rationale - -Needs discussion. - -## Backwards Compatibility - -This proposal is fully backward compatible with [EIP-1155](./eip-1155.md). - -## Security Considerations - -Needs discussion. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6268.md diff --git a/EIPS/eip-6315.md b/EIPS/eip-6315.md new file mode 100644 index 00000000000000..bc9b32106c5648 --- /dev/null +++ b/EIPS/eip-6315.md @@ -0,0 +1,7 @@ +--- +eip: 6315 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6315.md diff --git a/EIPS/eip-6327.md b/EIPS/eip-6327.md new file mode 100644 index 00000000000000..ca9bf8c8fdf021 --- /dev/null +++ b/EIPS/eip-6327.md @@ -0,0 +1,7 @@ +--- +eip: 6327 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6327.md diff --git a/EIPS/eip-634.md b/EIPS/eip-634.md index f53462f899c9d0..53d883a873aa60 100644 --- a/EIPS/eip-634.md +++ b/EIPS/eip-634.md @@ -1,129 +1,7 @@ --- eip: 634 -title: Storage of text records in ENS -description: Profiles for ENS resolvers to store arbitrary text key/value pairs. -author: Richard Moore (@ricmoo) -type: Standards Track -discussions-to: https://github.com/ethereum/EIPs/issues/2439 category: ERC -status: Stagnant -created: 2017-05-17 -requires: 137, 165 +status: Moved --- -## Abstract -This EIP defines a resolver profile for ENS that permits the lookup of arbitrary key-value -text data. This allows ENS name holders to associate e-mail addresses, URLs and other -informational data with a ENS name. - - -## Motivation -There is often a desire for human-readable metadata to be associated with otherwise -machine-driven data; used for debugging, maintenance, reporting and general information. - -In this EIP we define a simple resolver profile for ENS that permits ENS names to -associate arbitrary key-value text. - - -## Specification - -### Resolver Profile - -A new resolver interface is defined, consisting of the following method: - -```solidity -interface IERC634 { - /// @notice Returns the text data associated with a key for an ENS name - /// @param node A nodehash for an ENS name - /// @param key A key to lookup text data for - /// @return The text data - function text(bytes32 node, string key) view returns (string text); -} -``` - -The [EIP-165](./eip-165.md) interface ID of this interface is `0x59d1d43c`. - -The `text` data may be any arbitrary UTF-8 string. If the key is not present, the empty string -must be returned. - - -### Global Keys - -Global Keys must be made up of lowercase letters, numbers and -the hyphen (-). - -- **avatar** - a URL to an image used as an avatar or logo -- **description** - A description of the name -- **display** - a canonical display name for the ENS name; this MUST match the ENS name when its case is folded, and clients should ignore this value if it does not (e.g. `"ricmoo.eth"` could set this to `"RicMoo.eth"`) -- **email** - an e-mail address -- **keywords** - A list of comma-separated keywords, ordered by most significant first; clients that interpresent this field may choose a threshold beyond which to ignore -- **mail** - A physical mailing address -- **notice** - A notice regarding this name -- **location** - A generic location (e.g. `"Toronto, Canada"`) -- **phone** - A phone number as an E.164 string -- **url** - a website URL - -### Service Keys - -Service Keys must be made up of a *reverse dot notation* for -a namespace which the service owns, for example, DNS names -(e.g. `.com`, `.io`, etc) or ENS name (i.e. `.eth`). Service -Keys must contain at least one dot. - -This allows new services to start using their own keys without -worrying about colliding with existing services and also means -new services do not need to update this document. - -The following services are common, which is why recommendations are -provided here, but ideally a service would declare its own key. - -- **com.github** - a GitHub username -- **com.peepeth** - a Peepeth username -- **com.linkedin** - a LinkedIn username -- **com.twitter** - a Twitter username -- **io.keybase** - a Keybase username -- **org.telegram** - a Telegram username - -This technique also allows for a service owner to specify a hierarchy -for their keys, such as: - -- **com.example.users** -- **com.example.groups** -- **com.example.groups.public** -- **com.example.groups.private** - - -### Legacy Keys - -The following keys were specified in earlier versions of this EIP, -which is still in draft. - -Their use is not likely very wide, but applications attempting -maximal compatibility may wish to query these keys as a fallback -if the above replacement keys fail. - -- **vnd.github** - a GitHub username (renamed to `com.github`) -- **vnd.peepeth** - a peepeth username (renamced to `com.peepeth`) -- **vnd.twitter** - a twitter username (renamed to `com.twitter`) - - -## Rationale - -### Application-specific vs general-purpose record types - -Rather than define a large number of specific record types (each for generally human-readable -data) such as `url` and `email`, we follow an adapted model of DNS's `TXT` records, which allow -for a general keys and values, allowing future extension without adjusting the resolver, while -allowing applications to use custom keys for their own purposes. - - -## Backwards Compatibility -Not applicable. - - -## Security Considerations -None. - - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-634.md diff --git a/EIPS/eip-6353.md b/EIPS/eip-6353.md index 9233d534f8d185..a27628f237c13d 100644 --- a/EIPS/eip-6353.md +++ b/EIPS/eip-6353.md @@ -1,265 +1,7 @@ --- eip: 6353 -title: Charity token -description: Extension of EIP-20 token that can be partially donated to a charity project -author: Aubay , BOCA Jeabby (@bjeabby1507), EL MERSHATI Laith (@lth-elm), KEMP Elia (@eliakemp) -discussions-to: https://ethereum-magicians.org/t/erc20-charity-token/12617 -status: Draft -type: Standards Track category: ERC -created: 2022-05-13 -requires: 20 +status: Moved --- -## Abstract - -An extension to [EIP-20](./eip-20.md) that can automatically send an additional percentage of each transfer to a third party, and that provides an interface for retrieving this information. This can allow token owners to make donations to a charity with every transfer. This can also be used to allow automated savings programs. - -## Motivation - -There are charity organizations with addresses on-chain, and there are token holders who want to make automated donations. Having a standardized way of collecting and managing these donations helps users and user interface developers. Users can make an impact with their token and can contribute to achieving sustainable blockchain development. Projects can easily retrieve charity donations addresses and rate for a given [EIP-20](./eip-20.md) token, token holders can compare minimum rate donation offers allowed by token contract owners. This standard provides functionality that allows token holders to donate easily. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Owner of the contract **MAY**, after review, register charity address in `whitelistedRate` and set globally a default rate of donation. To register the address, the rate **MUST** not be null. - -Token holders **MAY** choose and specify a default charity address from `_defaultAddress`, this address **SHOULD** be different from the null address for the donation to be activated. - -The donation is a percentage-based rate model, but the calculation can be done differently. Applications and individuals can implement this standard by retrieving information with `charityInfo()` , which specifies an assigned rate for a given address. - -This standard provides functionality that allows token holders to donate easily. The donation when activated is done directly in the overridden `transfer`, `transferFrom`, and `approve` functions. - -When `transfer`, `transferFrom` are called the sender's balance is reduced by the initial amount and a donation amount is deduced. The initial transfered amount is transferred to the recipient's balance and an additional donation amount is transfered to a third party (charity). The two transfer are done at the same time and emit two `Transfer` events. -Also, if the account has an insufficient balance to cover the transfer and the donation the whole transfer would revert. - -```solidity -// SPDX-License-Identifier: CC0-1.0 -pragma solidity ^0.8.4; - -/// -/// @dev Required interface of an ERC20 Charity compliant contract. -/// -interface IERC20charity is IERC165 { - /// The EIP-165 identifier for this interface is 0x557512b6 - - - /** - * @dev Emitted when `toAdd` charity address is added to `whitelistedRate`. - */ - event AddedToWhitelist (address toAdd); - - /** - * @dev Emitted when `toRemove` charity address is deleted from `whitelistedRate`. - */ - event RemovedFromWhitelist (address toRemove); - - /** - * @dev Emitted when `_defaultAddress` charity address is modified and set to `whitelistedAddr`. - */ - event DonnationAddressChanged (address whitelistedAddr); - - /** - * @dev Emitted when `_defaultAddress` charity address is modified and set to `whitelistedAddr` - * and _donation is set to `rate`. - */ - event DonnationAddressAndRateChanged (address whitelistedAddr,uint256 rate); - - /** - * @dev Emitted when `whitelistedRate` for `whitelistedAddr` is modified and set to `rate`. - */ - event ModifiedCharityRate(address whitelistedAddr,uint256 rate); - - /** - *@notice Called with the charity address to determine if the contract whitelisted the address - *and if it is the rate assigned. - *@param addr - the Charity address queried for donnation information. - *@return whitelisted - true if the contract whitelisted the address to receive donnation - *@return defaultRate - the rate defined by the contract owner by default , the minimum rate allowed different from 0 - */ - function charityInfo( - address addr - ) external view returns ( - bool whitelisted, - uint256 defaultRate - ); - - /** - *@notice Add address to whitelist and set rate to the default rate. - * @dev Requirements: - * - * - `toAdd` cannot be the zero address. - * - * @param toAdd The address to whitelist. - */ - function addToWhitelist(address toAdd) external; - - /** - *@notice Remove the address from the whitelist and set rate to the default rate. - * @dev Requirements: - * - * - `toRemove` cannot be the zero address. - * - * @param toRemove The address to remove from whitelist. - */ - function deleteFromWhitelist(address toRemove) external; - - /** - *@notice Get all registered charity addresses. - */ - function getAllWhitelistedAddresses() external ; - - /** - *@notice Display for a user the rate of the default charity address that will receive donation. - */ - function getRate() external view returns (uint256); - - /** - *@notice Set personlised rate for charity address in {whitelistedRate}. - * @dev Requirements: - * - * - `whitelistedAddr` cannot be the zero address. - * - `rate` cannot be inferior to the default rate. - * - * @param whitelistedAddr The address to set as default. - * @param rate The personalised rate for donation. - */ - function setSpecificRate(address whitelistedAddr , uint256 rate) external; - - /** - *@notice Set for a user a default charity address that will receive donation. - * The default rate specified in {whitelistedRate} will be applied. - * @dev Requirements: - * - * - `whitelistedAddr` cannot be the zero address. - * - * @param whitelistedAddr The address to set as default. - */ - function setSpecificDefaultAddress(address whitelistedAddr) external; - - /** - *@notice Set for a user a default charity address that will receive donation. - * The rate is specified by the user. - * @dev Requirements: - * - * - `whitelistedAddr` cannot be the zero address. - * - `rate` cannot be less than to the default rate - * or to the rate specified by the owner of this contract in {whitelistedRate}. - * - * @param whitelistedAddr The address to set as default. - * @param rate The personalised rate for donation. - */ - function setSpecificDefaultAddressAndRate(address whitelistedAddr , uint256 rate) external; - - /** - *@notice Display for a user the default charity address that will receive donation. - * The default rate specified in {whitelistedRate} will be applied. - */ - function specificDefaultAddress() external view returns ( - address defaultAddress - ); - - /** - *@notice Delete The Default Address and so deactivate donnations . - */ - function deleteDefaultAddress() external; -} - -``` - -### Functions - -#### **addToWhitelist** - -Add address to whitelist and set the rate to the default rate. - -| Parameter | Description | -| ---------|-------------| -| toAdd | The address to the whitelist. - -#### **deleteFromWhitelist** - -Remove the address from the whitelist and set rate to the default rate. - -| Parameter | Description | -| ---------|-------------| -| toRemove | The address to remove from whitelist. - -#### **getAllWhitelistedAddresses** - -Get all registered charity addresses. - -#### **getRate** - -Display for a user the rate of the default charity address that will receive donation. - -#### **setSpecificRate** - -Set personalized rate for charity address in {whitelistedRate}. - -| Parameter | Description | -| ---------|-------------| -| whitelistedAddr | The address to set as default. | -| rate | The personalised rate for donation. | - -#### **setSpecificDefaultAddress** - -Set for a user a default charity address that will receive donations. The default rate specified in {whitelistedRate} will be applied. - -| Parameter | Description | -| ---------|-------------| -| whitelistedAddr | The address to set as default. - -#### **setSpecificDefaultAddressAndRate** - -Set for a user a default charity address that will receive donations. The rate is specified by the user. - -| Parameter | Description | -| ---------|-------------| -| whitelistedAddr | The address to set as default. | -| rate | The personalized rate for donation. - -#### **specificDefaultAddress** - -Display for a user the default charity address that will receive donations. The default rate specified in {whitelistedRate} will be applied. - -#### **deleteDefaultAddress** - -Delete The Default Address and so deactivate donations. - -#### **charityInfo** - -Called with the charity address to determine if the contract whitelisted the address and if it is, the rate assigned. - -| Parameter | Description | -| ---------|-------------| -| addr | The Charity address queried for donnation information. - -## Rationale - - This EIP chooses to whitelist charity addresses by using an array and keeping track of the "active" status with a mapping `whitelistedRate` to allow multiple choice of recipient and for transparence. The donation address can also be a single address chosen by the owner of the contract and modified by period. - - If the sender balance is insuficent i.e total amount of token (initial transfer + donation) is insuficent the transfer would revert. Donation are done in the `transfer` function to simplify the usage and to not add an additional function, but the implementation could be donne differently, and for exemple allow a transfer to go through without the donation amount when donation is activated. The token implementer can also choose to store the donation in the contract or in another one and add a withdrawal or claimable function, so the charity can claim the allocated amount of token themselves, the additional transfer will be triggered by the charity and not the token holder. - - Also, donations amount are calculated here as a percentage of the amount of token transfered to allow different case scenario, but the token implementer can decide to opt for another approach instead like rounding up the transaction value. - -## Backwards Compatibility - -This implementation is an extension of the functionality of [EIP-20](./eip-20.md), it introduces new functionality retaining the core interfaces and functionality of the [EIP-20](./eip-20.md) standard. There is a small backwards compatibility issue, indeed if an account has insufficient balance, it's possible for the transfer to fail. - -## Test Cases - -Tests can be found in [`charity.js`](../assets/eip-6353/test/charity.js). - -## Reference Implementation - -The reference implementation of the standard can be found under [`contracts/`](../assets/eip-6353/contracts/ERC20Charity.sol) folder. - -## Security Considerations - -There are no additional security considerations compared to EIP-20. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6353.md diff --git a/EIPS/eip-6357.md b/EIPS/eip-6357.md new file mode 100644 index 00000000000000..df1dc9a06458a4 --- /dev/null +++ b/EIPS/eip-6357.md @@ -0,0 +1,7 @@ +--- +eip: 6357 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6357.md diff --git a/EIPS/eip-6358.md b/EIPS/eip-6358.md new file mode 100644 index 00000000000000..3bb3b5186ba838 --- /dev/null +++ b/EIPS/eip-6358.md @@ -0,0 +1,7 @@ +--- +eip: 6358 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6358.md diff --git a/EIPS/eip-6366.md b/EIPS/eip-6366.md new file mode 100644 index 00000000000000..ebe22a4569fefa --- /dev/null +++ b/EIPS/eip-6366.md @@ -0,0 +1,7 @@ +--- +eip: 6366 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6366.md diff --git a/EIPS/eip-6372.md b/EIPS/eip-6372.md index f78189f1bc04bd..9fe63ffe3cbbec 100644 --- a/EIPS/eip-6372.md +++ b/EIPS/eip-6372.md @@ -1,92 +1,7 @@ --- eip: 6372 -title: Contract clock -description: An interface for exposing a contract's clock value and details -author: Hadrien Croubois (@Amxx), Francisco Giordano (@frangio) -discussions-to: https://ethereum-magicians.org/t/eip-6372-contract-clock/12689 -status: Review -type: Standards Track category: ERC -created: 2023-01-25 +status: Moved --- -## Abstract - -Many contracts rely on some clock for enforcing delays and storing historical data. While some contracts rely on block numbers, others use timestamps. There is currently no easy way to discover which time-tracking function a contract internally uses. This EIP proposes to standardize an interface for contracts to expose their internal clock and thus improve composability and interoperability. - -## Motivation - -Many contracts check or store time-related information. For example, timelock contracts enforce a delay before an operation can be executed. Similarly, DAOs enforce a voting period during which stakeholders can approve or reject a proposal. Last but not least, voting tokens often store the history of voting power using timed snapshots. - -Some contracts do time tracking using timestamps while others use block numbers. In some cases, more exotic functions might be used to track time. - -There is currently no interface for an external observer to detect which clock a contract uses. This seriously limits interoperability and forces devs to make risky assumptions. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -Compliant contracts MUST implement the `clock` and `CLOCK_MODE` functions as specified below. - -```solidity -interface IERC6372 { - function clock() external view returns (uint48); - function CLOCK_MODE() external view returns (string); -} -``` - -### Methods - -#### clock - -This function returns the current timepoint according to the mode the contract is operating on. It MUST be a **non-decreasing** function of the chain, such as `block.timestamp` or `block.number`. - -```yaml -- name: clock - type: function - stateMutability: view - inputs: [] - outputs: - - name: timepoint - type: uint48 -``` - -#### CLOCK_MODE - -This function returns a machine-readable string description of the clock the contract is operating on. - -This string MUST be formatted like a URL query string (a.k.a. `application/x-www-form-urlencoded`), decodable in standard JavaScript with `new URLSearchParams(CLOCK_MODE)`. - -- If operating using **block number**: - - If the block number is that of the `NUMBER` opcode (`0x43`), then this function MUST return `mode=blocknumber&from=default`. - - If it is any other block number, then this function MUST return `mode=blocknumber&from=`, where `` is a CAIP-2 Blockchain ID such as `eip155:1`. -- If operating using **timestamp**, then this function MUST return `mode=timestamp`. -- If operating using any other mode, then this function SHOULD return a unique identifier for the encoded `mode` field. - -```yaml -- name: CLOCK_MODE - type: function - stateMutability: view - inputs: [] - outputs: - - name: descriptor - type: string -``` - -### Expected properties - -- The `clock()` function MUST be non-decreasing. - -## Rationale - -`clock` returns `uint48` as it is largely sufficient for storing realistic values. In timestamp mode, `uint48` will be enough until the year 8921556. Even in block number mode, with 10,000 blocks per second, it would be enough until the year 2861. Using a type smaller than `uint256` allows storage packing of timepoints with other associated values, greatly reducing the cost of writing and reading from storage. - -Depending on the evolution of the blockchain (particularly layer twos), using a smaller type, such as `uint32` might cause issues fairly quickly. On the other hand, anything bigger than `uint48` appears wasteful. - -## Security Considerations - -No known security issues. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6372.md diff --git a/EIPS/eip-6381.md b/EIPS/eip-6381.md index 823e41b7b1642e..a1e776dd316ae6 100644 --- a/EIPS/eip-6381.md +++ b/EIPS/eip-6381.md @@ -1,131 +1,7 @@ --- eip: 6381 -title: Emotable Extension for Non-Fungible Tokens -description: React to Non-Fungible Tokens using Unicode emojis. -author: Bruno Škvorc (@Swader), Steven Pineda (@steven2308), Stevan Bogosavljevic (@stevyhacker), Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/eip-6381-emotable-extension-for-non-fungible-tokens/12710 -status: Draft -type: Standards Track category: ERC -created: 2023-01-22 -requires: 165, 721 +status: Moved --- -## Abstract - -The Emotable Extension for Non-Fungible Tokens standard extends [EIP-721](./eip-721.md) by allowing NFTs to be emoted at. - -This proposal introduces the ability to react to NFTs using Unicode standardized emoji. - -## Motivation - -With NFTs being a widespread form of tokens in the Ethereum ecosystem and being used for a variety of use cases, it is time to standardize additional utility for them. Having the ability for anyone to interact with an NFT introduces an interactive aspect to owning an NFT and unlocks feedback-based NFT mechanics. - -This EIP introduces new utilities for [EIP-721](./eip-721.md) based tokens in the following areas: - -- [Interactivity](#interactivity) -- [Feedback based evolution](#feedback-based-evolution) -- [Valuation](#valuation) - -### Interactivity - -The ability to emote on an NFT introduces the aspect of interactivity to owning an NFT. This can either reflect the admiration for the emoter (person emoting to an NFT) or can be a result of a certain action performed by the token's owner. Accumulating emotes on a token can increase its uniqueness and/or value. - -### Feedback based evolution - -Standardized on-chain reactions to NFTs allow for feedback based evolution. - -Current solutions are either proprietary or off-chain and therefore subject to manipulation and distrust. Having the ability to track the interaction on-chain allows for trust and objective evaluation of a given token. Designing the tokens to evolve when certain emote thresholds are met incentivizes interaction with the token collection. - -### Valuation - -Current NFT market heavily relies on previous values the token has been sold for, the lowest price of the listed token and the scarcity data provided by the marketplace. There is no real time indication of admiration or desirability of a specific token. Having the ability for users to emote to the tokens adds the possibility of potential buyers and sellers gageing the value of the token based on the impressions the token has collected. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// @title EIP-6381 Emotable Extension for Non-Fungible Tokens -/// @dev See https://eips.ethereum.org/EIPS/eip-6381 -/// @dev Note: the ERC-165 identifier for this interface is 0xf8d6854d. - -pragma solidity ^0.8.16; - -interface IEmotable is IERC165 { - /** - * @notice Used to notify listeners that the token with the specified ID has been emoted to or that the reaction has been revoked. - * @dev The event SHOULD only be emitted if the state of the emote is changed. - * @param emoter Address of the account that emoted or revoked the reaction to the token - * @param tokenId ID of the token - * @param emoji Unicode identifier of the emoji - * @param on Boolean value signifying whether the token was emoted to (`true`) or if the reaction has been revoked (`false`) - */ - event Emoted( - address indexed emoter, - uint256 indexed tokenId, - bytes4 emoji, - bool on - ); - - /** - * @notice Used to get the number of emotes for a specific emoji on a token. - * @param tokenId ID of the token to check for emoji count - * @param emoji Unicode identifier of the emoji - * @return Number of emotes with the emoji on the token - */ - function emoteCountOf( - uint256 tokenId, - bytes4 emoji - ) external view returns (uint256); - - /** - * @notice Used to emote or undo an emote on a token. - * @dev Does nothing if attempting to set a pre-existent state. - * @dev When the state is being changed, the Emoted event MUST be emitted. - * @param tokenId ID of the token being emoted - * @param emoji Unicode identifier of the emoji - * @param state Boolean value signifying whether to emote (`true`) or undo (`false`) emote - */ - function emote(uint256 tokenId, bytes4 emoji, bool state) external; -} -``` - -## Rationale - -Designing the proposal, we considered the following questions: - -1. **Does the proposal support custom emotes or only the Unicode specified ones?**\ -The proposal only accepts the Unicode identifier which is a `bytes4` value. This means that while we encourage implementers to add the reactions using standardized emojis, the values not covered by the Unicode standard can be used for custom emotes. The only drawback being that the interface displaying the reactions will have to know what kind of image to render and such additions will probably be limited to the interface or marketplace in which they were made. -2. **Should the proposal use emojis to relay the impressions of NFTs or some other method?**\ -The impressions could have been done using user-supplied strings or numeric values, yet we decided to use emojis since they are a well established mean of relaying impressions and emotions. - -## Backwards Compatibility - -The Emotable token standard is fully compatible with [EIP-721](./eip-721.md) and with the robust tooling available for implementations of EIP-721 as well as with the existing EIP-721 infrastructure. - -## Test Cases - -Tests are included in [`emotable.ts`](../assets/eip-6381/test/emotable.ts). - -To run them in terminal, you can use the following commands: - -``` -cd ../assets/eip-6381 -npm install -npx hardhat test -``` - -## Reference Implementation - -See [`Emotable.sol`](../assets/eip-6381/contracts/Emotable.sol). - -## Security Considerations - -The same security considerations as with [EIP-721](./eip-721.md) apply: hidden logic may be present in any of the functions, including burn, add asset, accept asset, and more. - -Caution is advised when dealing with non-audited contracts. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6381.md diff --git a/EIPS/eip-6384.md b/EIPS/eip-6384.md index 07e4cca774a01c..86710cfa9e1221 100644 --- a/EIPS/eip-6384.md +++ b/EIPS/eip-6384.md @@ -1,144 +1,7 @@ --- eip: 6384 -title: Human-readable offline signatures -description: A method for retrieving a human-readable description of EIP-712 typed and structured data. -author: Tal Be'ery , RoiV (@DeVaz1) -discussions-to: https://ethereum-magicians.org/t/eip-6384-readable-eip-712-signatures/12752 -status: Draft -type: Standards Track category: ERC -created: 2023-01-08 -requires: 712 +status: Moved --- -## Abstract - -This EIP introduces the `evalEIP712Buffer` function, which takes an [EIP-712](./eip-712.md) buffer and returns a human-readable text description. - -## Motivation - -The use case of Web3 off-chain signatures intended to be used within on-chain transaction is gaining traction and being used in multiple leading protocols (e.g. OpenSea) and standards [EIP-2612](./eip-2612.md), mainly as it offers a fee-less experience. -Attackers are known to actively and successfully abuse such off-chain signatures, leveraging the fact that users are blindly signing off-chain messages, since they are not humanly readable. -While [EIP-712](./eip-712.md) originally declared in its title that being ”humanly readable” is one of its goals, it did not live up to its promise eventually and EIP-712 messages are not understandable by an average user. - -In one example, victims browse a malicious phishing website. It requests the victim to sign a message that will put their NFT token for sale on OpenSea platform, virtually for free. - -The user interface for some popular wallet implementations is not conveying the actual meaning of signing such transactions. - -In this proposal we offer a secure and scalable method to bring true human readability to EIP-712 messages by leveraging their bound smart contracts. -As a result, once implemented this EIP wallets can upgrade their user experience from current state: - -![](../assets/eip-6384/media/MiceyMask-non-compliant.png) - -to a much clearer user experience: - -![](../assets/eip-6384/media/ZenGo-EIP-compliant-warning.png) - -The proposed solution solves the readability issues by allowing the wallet to query the `verifyingContract`. The incentives for keeping the EIP-712 message description as accurate as possible are aligned, as the responsibility for the description is now owned by the contract, that: - -- Knows the message meaning exactly (and probably can reuse the code that handles this message when received on chain) -- Natively incentivized to provide the best explanation to prevent a possible fraud -- Not involving a third party that needs to be trusted -- Maintains the fee-less customer experience as the added function is in “view” mode and does not require an on-chain execution and fees. -- Maintains Web3’s composability property - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -EIP-712 already formally binds an off-chain signature to a contract, with the `verifyingContract` parameter. We suggest adding a “view” function (`"stateMutability":"view"`) to such contracts, that returns a human readable description of the meaning of this specific off-chain buffer. - -```solidity -/** - * @dev Returns the expected result of the offchain message. -*/ - - function evalEIP712Buffer(bytes32 domainHash, string memory primaryType, bytes memory typedDataBuffer) - external - view - returns (string[] memory) { - ... - -} -``` - -**Every compliant contract MUST implement this function.** - -Using this function, wallets can submit the proposed off-chain signature to the contract and present the results to the user, allowing them to enjoy an “on-chain simulation equivalent” experience to their off-chain message. - -This function will have a well known name and signature, such that there is no need for updates in the EIP-712 structure. - -### Function's inputs - -The inputs of the function: - -- `domainHash` is the EIP-712's domainSeparator, a hashed `eip712Domain` struct. -- `primaryType`is the EIP-712's `primaryType`. -- `typedDataBuffer` is an ABI encoded message part of the EIP-712 full message. - -### Function's output(s) - -The output of the the function is an array of strings. The wallet SHOULD display them to its end-users. The wallet MAY choose to augment the returned strings with additional data. (e.g. resolve contract addresses to their name) - -The strings SHOULD NOT be formatted (e.g. should not contain HTML code) and wallets SHOULD treat this string as an untrusted input and handle its rendering as such. - -### Support for EIP-712 messages that are not meant to be used on-chain - -If `verifyingContract` is not included in the EIP-712 domain separator, wallets MUST NOT retrieve a human-readable description using this EIP. In this case, wallets SHOULD fallback to their original EIP-712 display. - -## Rationale - -- We chose to implement the `typeDataBuffer` parameter as abi encoded as it is a generic way to pass the data to the contract. The alternative was to pass the `typedData` struct, which is not generic as it requires the contract to specify the message data. -- We chose to return an array of strings and not a single string as there are potential cases where the message is composed of multiple parts. For example, in the case of a multiple assets transfers in the same `typedDataBuffer`, the contract is advised to describe each transfer in a separate string to allow the wallet to display each transfer separately. - -### Alternative solutions - -#### Third party services: - -Currently, the best choice for users is to rely on some 3rd party solutions that get the proposed message as input and explain its intended meaning to the user. This approach is: - -- Not scalable: 3rd party provider needs to learn all such proprietary messages -- Not necessarily correct: the explanation is based on 3rd party interpretation of the original message author -- Introduces an unnecessary dependency of a third party which may have some operational, security, and privacy implications. - -#### Domain name binding - -Alternatively, wallets can bind domain name to a signature. i.e. only accept EIP-712 message if it comes from a web2 domain that its `name` as defined by EIP-712 is included in `eip712Domain`. However this approach has the following disadvantages: - -- It breaks Web3’s composability, as now other dapps cannot interact with such messages -- Does not protect against bad messages coming from the specified web2 domain, e.g. when web2 domain is hacked -- Some current connector, such as WalletConnect do not allow wallets to verify the web2 domain authenticity - -## Backwards Compatibility - -For non-supporting contracts the wallets will default to showing whatever they are showing today. -Non-supporting wallets will not call this function and will default to showing whatever they are showing today. - -## Reference Implementation - -A reference implementation can be found [here](../assets/eip-6384/implementation/src/MyToken/MyToken.sol). -This toy example shows how an [EIP-20](./eip-20.md) contract supporting this EIP implements an EIP-712 support for "transferWithSig" functionality (a non-standard variation on Permit, as the point of this EIP is to allow readability to non-standard EIP-712 buffers). -To illustrate the usability of this EIP to some real world use case, a helper function for the actual OpenSea's SeaPort EIP-712 is implemented too in [here](../assets/eip-6384/implementation/src/SeaPort/SeaPort712ParserHelper.sol). - -## Security Considerations - -### The threat model: - -The attack is facilitated by a rogue web2 interface (“dapp”) that provides bad parameters for an EIP-712 formatted message that is intended to be consumed by a legitimate contract. Therefore, the message is controlled by attackers and cannot be trusted, however the contract is controlled by a legitimate party and can be trusted. - -The attacker intends to use that signed EIP-712 message on-chain later on, with a transaction crafted by the attackers. If the subsequent on-chain transaction was to be sent by the victim, then a regular transaction simulation would have sufficed. - -The case of a rogue contract is irrelevant, as such a rogue contract can already facilitate the attack regardless of the existence of the EIP-712 formatted message. - -Having said that, a rogue contract may try to abuse this functionality in order to send some maliciously crafted string in order to exploit vulnerabilities in wallet rendering of the string. Therefore wallets should treat this string as an untrusted input and handle its renderring it as such. - -### Analysis of the proposed solution - -The explanation is controlled by the relevant contract which is controlled by a legitimate party. The attacker must specify the relevant contract address, as otherwise it will not be accepted by it. Therefore, the attacker cannot create false explanations using this method. -Please note that if the explanation was part of the message to sign it would have been under the control of the attacker and hence irrelevant for security purposes. - -Since the added functionality to the contract has the “view” modifier, it cannot change the on-chain state and harm the existing functionalities of the contract. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6384.md diff --git a/EIPS/eip-6404.md b/EIPS/eip-6404.md index e8ee0fe0579302..86af2035f57f72 100644 --- a/EIPS/eip-6404.md +++ b/EIPS/eip-6404.md @@ -1,561 +1,83 @@ --- eip: 6404 -title: SSZ transactions root +title: SSZ Transactions Root description: Migration of transactions MPT commitment to SSZ author: Etan Kissling (@etan-status), Vitalik Buterin (@vbuterin) discussions-to: https://ethereum-magicians.org/t/eip-6404-ssz-transactions-root/12783 -status: Draft +status: Review type: Standards Track category: Core created: 2023-01-30 -requires: 155, 658, 1559, 2718, 2930, 4844, 6475 +requires: 6493, 7495 --- ## Abstract -This EIP defines a migration process of existing Merkle-Patricia Trie (MPT) commitments for transactions to SSZ. +This EIP defines a migration process of existing Merkle-Patricia Trie (MPT) commitments for transactions to [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md). ## Motivation -While the consensus `ExecutionPayloadHeader` and the execution block header map to each other conceptually, they are encoded differently. This EIP aims to align the encoding of their fields, taking advantage of the more modern SSZ format. This brings several advantages: +While the consensus `ExecutionPayloadHeader` and the execution block header map to each other conceptually, they are encoded differently. This EIP aims to align the encoding of the `transactions_root`, taking advantage of the more modern SSZ format. This brings several advantages: -1. **Reducing complexity:** Merkle-Patricia Tries (MPT) are hard to work with. Replacing them with SSZ leaves only the state trie in the legacy MPT format. +1. **Transaction inclusion proofs:** Changing the transaction representation to [EIP-6493 `Transaction`](./eip-6493.md) commits to the transaction root hash on-chain, allowing verification of the list of all transaction hashes within a block, and allowing compact transaction inclusion proofs. -2. **Better for smart contracts:** The SSZ format is optimized for production and verification of merkle proofs. It allows proving specific fields of containers and allows chunked processing, e.g., to support handling transactions that do not fit into calldata. +2. **Reducing complexity:** The proposed design reduces the number of use cases that require support for Merkle-Patricia Trie (MPT), RLP encoding, keccak hashing, and secp256k1 public key recovery. -3. **Better for light clients:** Light clients with access to the consensus `ExecutionPayload` no longer need to obtain the matching execution block header to verify proofs rooted in `transactions_root`. - -4. **Reducing ambiguity:** The name `transactions_root` is currently used to refer to different roots. The execution block header refers to a MPT root, the consensus `ExecutionPayloadHeader` refers to a SSZ root. +3. **Reducing ambiguity:** The name `transactions_root` is currently used to refer to different roots. While the execution block header refers to a Merkle Patricia Trie (MPT) root, the consensus `ExecutionPayloadHeader` instead refers to an SSZ root. With these changes, `transactions_root` consistently refers to the same SSZ root. ## Specification The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. -### [EIP-2718](./eip-2718.md) transaction types - -The value `0x00` is marked as a reserved [EIP-2718](./eip-2718.md) transaction type. - -- `0x00` represents an [EIP-2718](./eip-2718.md) `LegacyTransaction` in SSZ. - -| Name | SSZ equivalent | Description | -| - | - | - | -| `TransactionType` | `uint8` | [EIP-2718](./eip-2718.md) transaction type, range `[0x00, 0x7F]` | - -| Name | Value | Description | -| - | - | - | -| `TRANSACTION_TYPE_LEGACY` | `TransactionType(0x00)` | [`LegacyTransaction`](./eip-2718.md#transactions) (only allowed in SSZ) | -| `TRANSACTION_TYPE_EIP2930` | `TransactionType(0x01)` | [EIP-2930](./eip-2930.md#definitions) transaction | -| `TRANSACTION_TYPE_EIP1559` | `TransactionType(0x02)` | [EIP-1559](./eip-1559.md#specification) transaction | -| `TRANSACTION_TYPE_EIP4844` | `TransactionType(0x05)` | [EIP-4844](./eip-4844.md#parameters) transaction | - -### [EIP-155](./eip-155.md) Chain IDs - -The value `2^255 - 4` is marked as a reserved [EIP-155](./eip-155.md) chain ID. - -Attempting to use chain ID `2^255 - 4` in an [EIP-155](./eip-155.md) transaction results in a signature `v` value of `{27, 28}`, and would be processed like a pre-[EIP-155](./eip-155.md) `LegacyTransaction` that lacks chain ID. Therefore, [EIP-155](./eip-155.md) transactions do not support this chain ID. - -Reserving this chain ID value prevents confusion between `TRANSACTION_TYPE_LEGACY` transactions that do not support it, and other transactions that would theoretically support it. For the purpose of SSZ, chain ID `2^255 - 4` represents a `LegacyTransaction` lacking chain ID. - -| Name | Value | Description | -| - | - | - | -| `CHAIN_ID_LEGACY` | `uint256(2^255 - 4)` | `LegacyTransaction` that lacks chain ID (only allowed in SSZ) | - ### Consensus `ExecutionPayload` changes -The existing [consensus `Transaction`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/bellatrix/beacon-chain.md#custom-types) container represents transactions as opaque, serialized [`EIP-2718`](./eip-2718.md) typed transactions. This definition is replaced with a new SSZ container. The definition uses the `Optional[T]` SSZ type as defined in [EIP-6475](./eip-6475.md). - -| Name | SSZ equivalent | -| - | - | -| [`VersionedHash`](./eip-4844.md#type-aliases) | `Bytes32` | +When building a consensus `ExecutionPayload`, the [`transactions`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#executionpayload) list is now based on the [`Transaction`](./eip-6493.md) SSZ container. [EIP-6493](./eip-6493.md) defines how RLP transactions can be converted to SSZ. | Name | Value | | - | - | -| [`MAX_VERSIONED_HASHES_LIST_SIZE`](./eip-4844.md#parameters) | `uint64(2**24)` (= 16,777,216) | - -```python -class AccessTuple(Container): - address: Address - storage_keys: List[Hash, MAX_ACCESS_LIST_STORAGE_KEYS] - -class Transaction(Container): - chain_id: uint256 # EIP-155 - nonce: uint64 - max_priority_fee_per_gas: uint256 # EIP-1559 - max_fee_per_gas: uint256 # aka `gasprice` - gas_limit: uint64 # aka `startgas` - to: Optional[Address] # None: deploy contract - value: uint256 - data: ByteList[MAX_CALLDATA_SIZE] - access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] # EIP-2930 - max_fee_per_data_gas: uint256 # EIP-4844 - blob_versioned_hashes: List[VersionedHash, MAX_VERSIONED_HASHES_LIST_SIZE] # EIP-4844 - -class ECDSASignature(Container): - y_parity: boolean # EIP-2930 - r: uint256 - s: uint256 - -class TypedTransaction(Container): - tx_type: TransactionType - payload: Transaction - -class SignedTransaction(Container): - tx: TypedTransaction - signature: ECDSASignature - -class IndexedTransaction(Container): - signed_tx: SignedTransaction - tx_hash: Hash32 -``` - -The [consensus `ExecutionPayload`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/capella/beacon-chain.md#executionpayload) is updated to use the new `IndexedTransaction` SSZ container. - -| Name | Value | Description | -| - | - | - | -| [`MAX_TRANSACTIONS_PER_PAYLOAD`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/bellatrix/beacon-chain.md#execution) | `uint64(2**20)` (= 1,048,576) | Maximum amount of transactions allowed in each block | +| [`MAX_TRANSACTIONS_PER_PAYLOAD`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/bellatrix/beacon-chain.md#execution) | `uint64(2**20)` (= 1,048,576) | ```python class ExecutionPayload(Container): ... - transactions: List[IndexedTransaction, MAX_TRANSACTIONS_PER_PAYLOAD] + transactions: List[Transaction, MAX_TRANSACTIONS_PER_PAYLOAD] ... ``` ### Consensus `ExecutionPayloadHeader` changes -The [consensus `ExecutionPayloadHeader`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/capella/beacon-chain.md#executionpayloadheader) is updated for the new `ExecutionPayload.transactions` definition. +The [consensus `ExecutionPayloadHeader`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#executionpayloadheader) is updated for the new `ExecutionPayload.transactions` definition. ```python -payload_header.transactions_root = hash_tree_root(payload.transactions) +payload_header.transactions_root = payload.transactions.hash_tree_root() ``` ### Execution block header changes -The [execution block header's `txs-root`](https://github.com/ethereum/devp2p/blob/bd17dac4228c69b6379644355f373669f74952cd/caps/eth.md#block-encoding-and-validity) is updated to match the consensus `ExecutionPayloadHeader.transactions_root`. - -### Helpers - -These helpers use `BlobTransaction` and `SignedBlobTransaction` as defined in [EIP-4844](./eip-4844.md). +The [execution block header's `txs-root`](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md#block-encoding-and-validity) is updated to match the consensus `ExecutionPayloadHeader.transactions_root`. -```python -def validate_transaction(tx: TypedTransaction): - if tx.tx_type != TRANSACTION_TYPE_LEGACY: - assert tx.payload.chain_id != CHAIN_ID_LEGACY - - if tx.tx_type == TRANSACTION_TYPE_EIP4844: - return - assert tx.payload.max_fee_per_data_gas == 0 - assert len(tx.payload.blob_versioned_hashes) == 0 - - if tx.tx_type == TRANSACTION_TYPE_EIP1559: - return - assert tx.payload.max_priority_fee_per_gas == tx.payload.max_fee_per_gas - - if tx.tx_type == TRANSACTION_TYPE_EIP2930: - return - assert len(tx.payload.access_list) == 0 - - if tx.tx_type == TRANSACTION_TYPE_LEGACY: - return - assert False -``` +### Transaction indexing -```python -def compute_transaction_sighash(tx: TypedTransaction) -> bytes: - if tx.tx_type != TRANSACTION_TYPE_LEGACY: - assert tx.payload.chain_id != CHAIN_ID_LEGACY - - if tx.tx_type == TRANSACTION_TYPE_EIP4844: - return keccak([0x05] + SSZ.encode(BlobTransaction( - chain_id=tx.payload.chain_id, - nonce=tx.payload.nonce, - max_priority_fee_per_gas=tx.payload.max_priority_fee_per_gas, - max_fee_per_gas=tx.payload.max_fee_per_gas, - gas=tx.payload.gas_limit, - to=tx.payload.to, - value=tx.payload.value, - data=tx.payload.data, - access_list=tx.payload.access_list, - max_fee_per_data_gas=tx.payload.max_fee_per_data_gas, - blob_versioned_hashes=tx.payload.blob_versioned_hashes, - ))) - - assert tx.payload.max_fee_per_data_gas == 0 - assert len(tx.payload.blob_versioned_hashes) == 0 - - if tx.tx_type == TRANSACTION_TYPE_EIP1559: - schema = ( - (big_endian_int, tx.payload.chain_id), - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_priority_fee_per_gas), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (List([Binary[20, 20], List([Binary[32, 32]])]), [ - ( - access_tuple.address, - access_tuple.storage_keys, - ) for access_tuple in tx.payload.access_list - ]), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return keccak([0x02] + rlp.encode(values, sedes)) - - assert tx.payload.max_priority_fee_per_gas == tx.payload.max_fee_per_gas - - if tx.tx_type == TRANSACTION_TYPE_EIP2930: - schema = ( - (big_endian_int, tx.payload.chain_id), - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (List([Binary[20, 20], List([Binary[32, 32]])]), [ - ( - access_tuple.address, - access_tuple.storage_keys, - ) for access_tuple in tx.payload.access_list - ]), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return keccak([0x01] + rlp.encode(values, sedes)) - - assert len(tx.payload.access_list) == 0 - - if tx.tx_type == TRANSACTION_TYPE_LEGACY: - if tx.payload.chain_id != CHAIN_ID_LEGACY: - schema = ( - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (big_endian_int, tx.payload.chain_id), - (big_endian_int, 0), - (big_endian_int, 0), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return keccak(rlp.encode(values, sedes)) - else: - schema = ( - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return keccak(rlp.encode(values, sedes)) - - assert False -``` +While a unique transaction identifier `tx_hash` is defined for each transaction, there is no on-chain commitment to this identifier for RLP transactions. Instead, transactions are ["summarized"](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md#summaries-and-expansions) by their [`hash_tree_root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md#merkleization). ```python -def encode_signed_transaction(signed_tx: SignedTransaction) -> bytes: - tx = signed_tx.tx - if tx.tx_type != TRANSACTION_TYPE_LEGACY: - assert tx.payload.chain_id != CHAIN_ID_LEGACY: - - if tx.tx_type == TRANSACTION_TYPE_EIP4844: - return [0x05] + SSZ.encode(SignedBlobTransaction( - message=BlobTransaction( - chain_id=tx.payload.chain_id, - nonce=tx.payload.nonce, - max_priority_fee_per_gas=tx.payload.max_priority_fee_per_gas, - max_fee_per_gas=tx.payload.max_fee_per_gas, - gas=tx.payload.gas_limit, - to=tx.payload.to, - value=tx.payload.value, - data=tx.payload.data, - access_list=tx.payload.access_list, - max_fee_per_data_gas=tx.payload.max_fee_per_data_gas, - blob_versioned_hashes=tx.payload.blob_versioned_hashes, - signature=signed_tx.signature, - ))) - - assert tx.payload.max_fee_per_data_gas == 0 - assert len(tx.payload.blob_versioned_hashes) == 0 - - if tx.tx_type == TRANSACTION_TYPE_EIP1559: - schema = ( - (big_endian_int, tx.payload.chain_id), - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_priority_fee_per_gas), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (List([Binary[20, 20], List([Binary[32, 32]])]), [ - ( - access_tuple.address, - access_tuple.storage_keys, - ) for access_tuple in tx.payload.access_list - ]), - (big_endian_int, 1 if signed_tx.signature.y_parity else 0), - (big_endian_int, signed_tx.signature.r), - (big_endian_int, signed_tx.signature.s), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return [0x02] + rlp.encode(values, sedes) - - assert tx.payload.max_priority_fee_per_gas == tx.payload.max_fee_per_gas - - if tx.tx_type == TRANSACTION_TYPE_EIP2930: - schema = ( - (big_endian_int, tx.payload.chain_id), - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (List([Binary[20, 20], List([Binary[32, 32]])]), [ - ( - access_tuple.address, - access_tuple.storage_keys, - ) for access_tuple in tx.payload.access_list - ]), - (big_endian_int, 1 if signed_tx.signature.y_parity else 0), - (big_endian_int, signed_tx.signature.r), - (big_endian_int, signed_tx.signature.s), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return [0x01] + rlp.encode(values, sedes) - - assert len(tx.payload.access_list) == 0 - - if tx.tx_type == TRANSACTION_TYPE_LEGACY: - if tx.payload.chain_id != CHAIN_ID_LEGACY: - v = (1 if signed_tx.signature.y_parity else 0) + tx.payload.chain_id * 2 + 35 - else: - v = (1 if signed_tx.signature.y_parity else 0) + 27 - schema = ( - (big_endian_int, tx.payload.nonce), - (big_endian_int, tx.payload.max_fee_per_gas), - (big_endian_int, tx.payload.gas_limit), - (binary, tx.payload.to if tx.payload.to is not None else []), - (big_endian_int, tx.payload.value), - (binary, tx.payload.data), - (big_endian_int, v), - (big_endian_int, signed_tx.signature.r), - (big_endian_int, signed_tx.signature.s), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return rlp.encode(values, sedes) - - assert False +def compute_tx_root(tx: Transaction) -> Root: + return tx.hash_tree_root() ``` -```python -def compute_transaction_hash(signed_tx: SignedTransaction) -> bytes: - return keccak(encode_signed_transaction(signed_tx)) -``` +Note that for SSZ transactions with `tx.signature.type_ == TRANSACTION_TYPE_SSZ`, the `tx_hash` is equivalent to the `tx_root`. Like the `tx_hash`, the `tx_root` remains perpetually [stable](./eip-7495.md) across future upgrades. -```python -def decode_signed_transaction(encoded_signed_tx: bytes) -> SignedTransaction: - eip2718_type = encoded_signed_tx[0] - - if eip2718_type == 0x05: - pre = SSZ.decode_ssz(SignedBlobTransaction, encoded_signed_tx[1:]) - - return SignedTransaction( - tx=TypedTransaction( - tx_type=TRANSACTION_TYPE_EIP4844, - payload=Transaction( - chain_id=pre.message.chain_id, - nonce=premessage.nonce, - max_priority_fee_per_gas=pre.message.max_priority_fee_per_gas, - max_fee_per_gas=premessage.max_fee_per_gas, - gas_limit=pre.message.gas, - to=pre.message.to, - value=pre.message.value, - data=pre.message.data, - access_list=pre.message.access_list, - max_fee_per_data_gas=pre.message.max_fee_per_data_gas, - blob_versioned_hashes=pre.message.blob_versioned_hashes, - ), - ), - signature=pre.signature, - ) - - if eip2718_type == 0x02: - class SignedEIP1559Transaction(rlp.Serializable): - fields = ( - ('chain_id', big_endian_int), - ('nonce', big_endian_int), - ('max_priority_fee_per_gas', big_endian_int), - ('max_fee_per_gas', big_endian_int), - ('gas_limit', big_endian_int), - ('destination', binary), - ('amount', big_endian_int), - ('data', binary), - ('access_list', List([Binary[20, 20], List([Binary[32, 32]])])), - ('signature_y_parity', big_endian_int), - ('signature_r', big_endian_int), - ('signature_s', big_endian_int), - ) - pre = SignedEIP1559Transaction.deserialize(encoded_signed_tx[1:]) - - return SignedTransaction( - tx=TypedTransaction( - tx_type=TRANSACTION_TYPE_EIP1559, - payload=Transaction( - chain_id=pre.chain_id, - nonce=pre.nonce, - max_priority_fee_per_gas=pre.max_priority_fee_per_gas, - max_fee_per_gas=pre.max_fee_per_gas, - gas_limit=pre.gas_limit, - to=Address(pre.destination) if len(pre.destination) > 0 else None, - value=pre.amount, - data=pre.data, - access_list=[AccessTuple( - address=access_tuple[0], - storage_keys=access_tuple[1], - ) for access_tuple in pre.access_list], - ), - ), - signature=ECDSASignature( - y_parity=pre.signature_y_parity != 0, - r=pre.signature_r, - s=pre.signature_s, - ), - ) - - if eip2718_type == 0x01: - class SignedEIP2930Transaction(rlp.Serializable): - fields = ( - ('chainId', big_endian_int), - ('nonce', big_endian_int), - ('gasPrice', big_endian_int), - ('gasLimit', big_endian_int), - ('to', binary), - ('value', big_endian_int), - ('data', binary), - ('accessList', List([Binary[20, 20], List([Binary[32, 32]])])), - ('signatureYParity', big_endian_int), - ('signatureR', big_endian_int), - ('signatureS', big_endian_int), - ) - pre = SignedEIP2930Transaction.deserialize(encoded_signed_tx[1:]) - - return SignedTransaction( - tx=TypedTransaction( - tx_type=TRANSACTION_TYPE_EIP2930, - payload=Transaction( - chain_id=pre.chainId, - nonce=pre.nonce, - max_priority_fee_per_gas=pre.gasPrice, - max_fee_per_gas=pre.gasPrice, - gas_limit=pre.gasLimit, - to=Address(pre.to) if len(pre.to) > 0 else None, - value=pre.value, - data=pre.data, - access_list=[AccessTuple( - address=access_tuple[0], - storage_keys=access_tuple[1], - ) for access_tuple in pre.accessList], - ), - ), - signature=ECDSASignature( - y_parity=pre.signatureYParity != 0, - r=pre.signatureR, - s=pre.signatureS, - ), - ) - - if 0xc0 <= eip2718_type <= 0xfe: - class SignedLegacyTransaction(rlp.Serializable): - fields = ( - ('nonce', big_endian_int), - ('gasprice', big_endian_int), - ('startgas', big_endian_int), - ('to', binary), - ('value', big_endian_int), - ('data', binary), - ('v', big_endian_int), - ('r', big_endian_int), - ('s', big_endian_int), - ) - pre = SignedLegacyTransaction.deserialize(encoded_signed_tx) - - if pre.v not in (27, 28): - chain_id = (uint256(pre.v) - 35) >> 1 - y_parity = ((uint256(pre.v) - 35) & 0x1) != 0 - else: - chain_id = CHAIN_ID_LEGACY - y_parity = ((uint256(pre.v) - 27) & 0x1) != 0 - - return SignedTransaction( - tx=TypedTransaction( - tx_type=TRANSACTION_TYPE_LEGACY, - payload=Transaction( - chain_id=chain_id, - nonce=pre.nonce, - max_priority_fee_per_gas=pre.gasprice, - max_fee_per_gas=pre.gasprice, - gas_limit=pre.startgas, - to=Address(pre.to) if len(pre.to) > 0 else None, - value=pre.value, - data=pre.data, - ), - ), - signature=ECDSASignature( - y_parity=y_parity, - r=pre.r, - s=pre.s, - ), - ) - - assert False -``` +It is RECOMMENDED that implementations introduce indices for tracking transactions by `tx_root`. ## Rationale -### Why not multiple `Transaction` containers? - -- **Superset of all existing transaction types:** The new `Transaction` container supports all existing transaction types. There is no new functionality that was previously disallowed. `Transaction` containers that are created from importing legacy transaction types use default values for fields that were added later. - -- **Static merkle tree shape:** Compared to approaches based on SSZ `Union`, it is not necessary to branch on `tx_type` to determine the `GeneralizedIndex` for common fields. For example, a proof for a `Transaction`'s `value` field always has the exact same structure. - -- **Prior art:** Multiple modules of Ethereum already process common fields in a unified way. The consensus pytests use `is_post_fork` to conditionally enable logic. The execution JSON-RPC reports transaction fields under the same name regardless of type. The consensus light client protocol incorporates a very similar mechanism for upgrading consensus `ExecutionPayloadHeader` to later formats: [`compute_transaction_sighash` equivalent](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/eip4844/light-client/sync-protocol.md#modified-get_lc_execution_root) / [`upgrade_to_latest` equivalent](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/eip4844/light-client/full-node.md#modified-block_to_light_client_header). - -### Why `tx_hash`? - -The perpetual transaction hash is used by many applications to uniquely identify a transaction. The `tx_hash` allows smart contracts to verify proofs about structures that are linked to the perpetual transaction hash, without having to re-hash the entire transaction according to the original `TransactionType`. +This change enables the use of SSZ transactions as defined in [EIP-6493](./eip-6493.md). ## Backwards Compatibility -Applications that solely rely on the `TypedTransaction` RLP encoding but do not rely on the `transactions_root` commitment in the block header can still be used through a re-encoding proxy. - -Applications that rely on the replaced `transactions_root` in the block header can no longer find that information. Analysis is required whether affected applications have a migration path available to use the SSZ root commitments instead. - -The perpetual transaction hash is commonly used by block explorers. A helper function `compute_transaction_hash` is specified to replicate historic transaction hashes. - -`TRANSACTION_TYPE_LEGACY` is already similarly used in the execution JSON-RPC API. It is unlikely to be used for other purposes. - -Certain popular wallet software does not support `CHAIN_ID_LEGACY`, so it is unlikely to be practically used. [EIP-2294](./eip-2294.md) further restricts the range of chain ID values. - -## Test Cases - -TBD - -## Reference Implementation +Applications that rely on the replaced MPT `transactions_root` in the block header require migration to the SSZ `transactions_root`. -TBD +While there is no on-chain commitment of the `tx_hash`, it is widely used in JSON-RPC and the [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md) to uniquely identify transactions. The `tx_root` is a different identifier and will be required for use cases such as transaction inclusion proofs where an on-chain commitment is required. ## Security Considerations diff --git a/EIPS/eip-6454.md b/EIPS/eip-6454.md index bf1265c3f6b8fa..584644c93477d2 100644 --- a/EIPS/eip-6454.md +++ b/EIPS/eip-6454.md @@ -1,107 +1,7 @@ --- eip: 6454 -title: Minimalistic Non-Transferrable NFTs -description: An interface for Non-Transferrable Non-Fungible Tokens extension allowing for tokens to be non-transferrable. -author: Bruno Škvorc (@Swader), Francesco Sullo (@sullof), Steven Pineda (@steven2308), Stevan Bogosavljevic (@stevyhacker), Jan Turk (@ThunderDeliverer) -discussions-to: https://ethereum-magicians.org/t/minimalistic-transferable-interface/12517 -status: Draft -type: Standards Track category: ERC -created: 2023-01-31 -requires: 165, 721 +status: Moved --- -## Abstract - -The Minimalistic Non-Transferrable interface for Non-Fungible Tokens standard extends [ERC-721](./eip-721.md) by preventing NFTs to be transferred. - -This proposal introduces the ability to prevent a token to be transferred from their owner, making them bound to the externally owned account, smart contract or token that owns it. - -## Motivation - -With NFTs being a widespread form of tokens in the Ethereum ecosystem and being used for a variety of use cases, it is time to standardize additional utility for them. Having the ability to prevent the tokens to be transferred introduces new possibilities of NFT utility and evolution. - -This proposal is designed in a way to be as minimal as possible in order to be compatible with any usecases that wish to utilize this proposal. - -This EIP introduces new utilities for [ERC-721](./eip-721.md) based tokens in the following areas: - -- [Verifiable attribution](#verifiable-attribution) -- [Immutable properties](#immutable-properties) - -### Verifiable attribution - -Personal achievements can be represented by non-fungible tokens. These tokens can be used to represent a wide range of accomplishments, including scientific advancements, philanthropic endeavors, athletic achievements, and more. However, if these achievement-indicating NFTs can be easily transferred, their authenticity and trustworthiness can be called into question. By binding the NFT to a specific account, it can be ensured that the account owning the NFT is the one that actually achieved the corresponding accomplishment. This creates a secure and verifiable record of personal achievements that can be easily accessed and recognized by others in the network. The ability to verify attribution helps to establish the credibility and value of the achievement-indicating NFT, making it a valuable asset that can be used as a recognition of the holder's accomplishments. - -### Immutable properties - -NFT properties are a critical aspect of non-fungible tokens, serving to differentiate them from one another and establish their scarcity. Centralized control of NFT properties by the issuer, however, can undermine the uniqueness of these properties. - -By tying NFTs to specific properties, the original owner is ensured that the NFT will always retain these properties and its uniqueness. - -In a blockchain game that employs non-transferrable NFTs to represent skills or abilities, each skill would be a unique and permanent asset tied to a specific player or token. This would ensure that players retain ownership of the skills they have earned and prevent them from being traded or sold to other players. This can increase the perceived value of these skills, enhancing the player experience by allowing for greater customization and personalization of characters. - -## Specification - -The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. - -```solidity -/// @title EIP-6454 Minimalistic Non-Transferrable interface for NFTs -/// @dev See https://eips.ethereum.org/EIPS/eip-6454 -/// @dev Note: the ERC-165 identifier for this interface is 0x0083fc9d. - -pragma solidity ^0.8.16; - -interface IERC6454 is IERC165 { - /** - * @notice Used to check whether the given token is non-transferrable or not. - * @dev If this function returns `true`, the transfer of the token MUST revert execution - * @param tokenId ID of the token being checked - * @return Boolean value indicating whether the given token is non-transferrable - */ - function isNonTransferrable(uint256 tokenId) external view returns (bool); -} -``` - -## Rationale - -Designing the proposal, we considered the following questions: - -1. **Should we propose another Non-Transferrable NFT proposal given the existence of existing ones, some even final, and how does this proposal compare to them?**\ - This proposal aims to provide the minimum necessary specification for the implementation of non-transferrable NFTs, we feel none of the existing proposals have presented the minimal required interface. Unlike other proposals that address the same issue, this proposal requires fewer methods in its specification, providing a more streamlined solution. -2. **Why is there no event marking the token as Non-Transferrable in this interface?**\ - The token can become non-transferrable either at its creation, after being marked as non-transferrable, or after a certain condition is met. This means that some cases of tokens becoming non-transferrable cannot emit an event, such as if the token becoming non-transferrable is determined by a block number. Requiring an event to be emitted upon the token becoming non-transferrable is not feasible in such cases. -3. **Should the non-transferrable state management function be included in this proposal?**\ - A function that marks a token as non-transferrable or releases the binding is referred to as the non-transferrable management function. To maintain the objective of designing an agnostic non-transferrable proposal, we have decided not to specify the non-transferrable management function. This allows for a variety of custom implementations that require the tokens to be non-transferable. -4. **Why should this be an EIP if it only contains one method?**\ - One could argue that since the core of this proposal is to only prevent ERC-721 tokens to be transferred, this could be done by overriding the transfer function. While this is true, the only way to assure that the token is non-transferrable before the smart contract execution, is for it to have the non-transferrable interface.\ - This also allows for smart contract to validate that the token is non-transferrable and not attempt transferring it as this would result in failed transactions and wasted gas. - -## Backwards Compatibility - -The Minimalistic Non-Transferrable token standard is fully compatible with [ERC-721](./eip-721.md) and with the robust tooling available for implementations of ERC-721 as well as with the existing ERC-721 infrastructure. - -## Test Cases - -Tests are included in [`nonTransferrable.ts`](../assets/eip-6454/test/nonTransferrable.ts). - -To run them in terminal, you can use the following commands: - -``` -cd ../assets/eip-6454 -npm install -npx hardhat test -``` - -## Reference Implementation - -See [`ERC721NonTransferrableMock.sol`](../assets/eip-6454/contracts/mocks/ERC721NonTransferrableMock.sol). - -## Security Considerations - -The same security considerations as with [ERC-721](./eip-721.md) apply: hidden logic may be present in any of the functions, including burn, add asset, accept asset, and more. - -Caution is advised when dealing with non-audited contracts. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6454.md diff --git a/EIPS/eip-6464.md b/EIPS/eip-6464.md new file mode 100644 index 00000000000000..67d9e5deee987c --- /dev/null +++ b/EIPS/eip-6464.md @@ -0,0 +1,7 @@ +--- +eip: 6464 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6464.md diff --git a/EIPS/eip-6465.md b/EIPS/eip-6465.md index 51ff12f3199111..27bcb176e22b4a 100644 --- a/EIPS/eip-6465.md +++ b/EIPS/eip-6465.md @@ -1,39 +1,51 @@ --- eip: 6465 -title: SSZ withdrawals root +title: SSZ Withdrawals Root description: Migration of withdrawals MPT commitment to SSZ -author: Etan Kissling (@etan-status) +author: Etan Kissling (@etan-status), Mikhail Kalinin (@mkalinin) discussions-to: https://ethereum-magicians.org/t/eip-6465-ssz-withdrawals-root/12883 -status: Draft +status: Review type: Standards Track category: Core created: 2023-02-08 -requires: 4895 +requires: 2718, 4895, 6493 --- ## Abstract -This EIP defines a migration process of the existing Merkle-Patricia Trie (MPT) commitment for withdrawals to SSZ. +This EIP defines a migration process of the existing Merkle-Patricia Trie (MPT) commitment for withdrawals to [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md). ## Motivation While the consensus `ExecutionPayloadHeader` and the execution block header map to each other conceptually, they are encoded differently. This EIP aims to align the encoding of the `withdrawals_root`, taking advantage of the more modern SSZ format. This brings several advantages: -1. **Reducing complexity:** Merkle-Patricia Tries (MPT) are hard to work with. Replacing them with SSZ leaves only the state trie in the legacy MPT format. +1. **Reducing complexity:** The proposed design reduces the number of use cases that require support for Merkle-Patricia Trie (MPT). -2. **Better for smart contracts:** The SSZ format is optimized for production and verification of merkle proofs. It allows proving specific fields of containers and allows chunked processing. - -3. **Better for light clients:** Light clients with access to the consensus `ExecutionPayload` no longer need to obtain the matching execution block header to verify proofs rooted in `withdrawals_root`. - -4. **Reducing ambiguity:** The name `withdrawals_root` is currently used to refer to different roots. The execution block header refers to a MPT root, the consensus `ExecutionPayloadHeader` refers to a SSZ root. +2. **Reducing ambiguity:** The name `withdrawals_root` is currently used to refer to different roots. While the execution block header refers to a Merkle Patricia Trie (MPT) root, the consensus `ExecutionPayloadHeader` instead refers to an SSZ root. With these changes, `withdrawals_root` consistently refers to the same SSZ root. ## Specification The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. -### Execution block header changes +### Existing definitions + +Definitions from existing specifications that are used throughout this document are replicated here for reference. + +| Name | SSZ equivalent | +| - | - | +| [`ValidatorIndex`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types) | `uint64` | +| [`Gwei`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types) | `uint64` | +| [`ExecutionAddress`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/bellatrix/beacon-chain.md#custom-types) | `Bytes20` +| [`WithdrawalIndex`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#custom-types) | `uint64` | + +| Name | Value | +| - | - | +| [`MAX_WITHDRAWALS_PER_PAYLOAD`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#execution) | `uint64(2**4)` (= 16) | +| [`TRANSACTION_TYPE_SSZ`](./eip-6493.md#eip-2718-transaction-types) | `0x04` | + +### SSZ `Withdrawal` container -The existing consensus [`Withdrawal`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/capella/beacon-chain.md#withdrawal) SSZ container is used to represent withdrawals. +The existing consensus [`Withdrawal`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#withdrawal) SSZ container is used to represent withdrawals. ```python class Withdrawal(Container): @@ -43,74 +55,63 @@ class Withdrawal(Container): amount: Gwei ``` -The execution block header's `withdrawals-root` is updated to match the consensus [`ExecutionPayloadHeader.withdrawals_root`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/capella/beacon-chain.md#executionpayloadheader). +### Execution block header changes -| Name | Value | Description | -| - | - | - | -| [`MAX_WITHDRAWALS_PER_PAYLOAD`](https://github.com/ethereum/consensus-specs/blob/67c2f9ee9eb562f7cc02b2ff90d92c56137944e1/specs/capella/beacon-chain.md#execution) | `uint64(2**4)` (= 16) | Maximum amount of withdrawals allowed in each block | +The execution block header's `withdrawals-root` is updated to match the consensus [`ExecutionPayloadHeader.withdrawals_root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#executionpayloadheader). ```python -block_header.withdrawals_root == hash_tree_root(List[Withdrawal, MAX_WITHDRAWALS_PER_PAYLOAD]( - withdrawal_0, - withdrawal_1, - withdrawal_2, - ... -)) +withdrawals = List[Withdrawal, MAX_WITHDRAWALS_PER_PAYLOAD]( + withdrawal_0, withdrawal_1, withdrawal_2, ...) + +block_header.withdrawals_root == withdrawals.hash_tree_root() ``` -### Helpers +### Typed withdrawal envelope -```python -def encode_withdrawal(withdrawal: Withdrawal) -> bytes: - schema = ( - (big_endian_int, withdrawal.index), - (big_endian_int, withdrawal.validator_index), - (Binary[20, 20], withdrawal.address), - (big_endian_int, withdrawal.amount), - ) - sedes = List([schema for schema, _ in schema]) - values = [value for _, value in schema] - return rlp.encode(values, sedes) +A typed withdrawal envelope similar to [EIP-2718](./eip-2718.md) is introduced for exchanging withdrawals via the [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md). + +``` +withdrawal = {legacy-withdrawal, typed-withdrawal} ``` -```python -def decode_withdrawal(encoded_withdrawal: bytes) -> Withdrawal: - class RLPWithdrawal(rlp.Serializable): - fields = ( - ('index', bid_endian_int), - ('validator_index', big_endian_int), - ('address', Binary[20, 20]), - ('amount', big_endian_int), - ) - pre = RLPWithdrawal.deserialize(encoded_withdrawal) - - return Withdrawal( - index=pre.index, - validator_index=pre.validator_index, - address=pre.address, - amount=pre.amount, - ) +Untyped, legacy withdrawals are given as an RLP list as defined in [EIP-4895](./eip-4895.md). + +``` +legacy-withdrawal = [ + index: P, + validator-index: P, + address: B_20, + amount: P, +] ``` -## Rationale +Typed withdrawals are encoded as RLP byte arrays where the first byte is a withdrawal type (`withdrawal-type`) and the remaining bytes are opaque type-specific data. -This change was originally a candidate for inclusion in Shanghai, but was postponed to accelerate the rollout of withdrawals. +``` +typed-withdrawal = withdrawal-type || withdrawal-data +``` -## Backwards Compatibility +### Networking -Applications that solely rely on the `Withdrawal` RLP encoding but do not rely on the `withdrawals_root` in the block header can still be used through a re-encoding proxy. +When exchanging SSZ withdrawals via the [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md), the following withdrawal envelope is used: -Applications that rely on the replaced `withdrawals_root` in the block header can no longer find that information. +- `Withdrawal`: `TRANSACTION_TYPE_SSZ || snappyFramed(ssz(Withdrawal))` -Withdrawals were only just recently introduced as part of [EIP-4895](./eip-4895.md) (Shanghai). It is not expected that major applications already rely on the Merkle-Patricia Trie commitment for withdrawals. +Objects are encoded using [SSZ](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) and compressed using the Snappy framing format, matching the encoding of consensus objects as defined in the [consensus networking specification](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/p2p-interface.md#ssz-snappy-encoding-strategy). As part of the encoding, the uncompressed object length is emitted; the RECOMMENDED limit to enforce per object is `8 + 8 + 20 + 8` (= 44) bytes. -## Test Cases +## Rationale + +This change was originally a candidate for inclusion in Shanghai, but was postponed to accelerate the rollout of withdrawals. -TBD +### Why typed withdrawal envelopes? + +The RLPx serialization layer may not be aware of the fork schedule and the block timestamp when withdrawals are exchanged. The typed withdrawal envelope assists when syncing historical blocks based on RLP and the MPT `withdrawals_root`. + +## Backwards Compatibility -## Reference Implementation +Applications that rely on the replaced MPT `withdrawals_root` in the block header require migration to the SSZ `withdrawals_root`. -TBD +Clients can differentiate between the legacy withdrawals and typed withdrawals by looking at the first byte. If it starts with a value in the range `[0, 0x7f]` then it is a new withdrawal type, if it starts with a value in the range `[0xc0, 0xfe]` then it is a legacy withdrawal type. `0xff` is not realistic for an RLP encoded withdrawal, so it is reserved for future use as an extension sentinel value. ## Security Considerations diff --git a/EIPS/eip-6466.md b/EIPS/eip-6466.md new file mode 100644 index 00000000000000..cd2e56b69f0562 --- /dev/null +++ b/EIPS/eip-6466.md @@ -0,0 +1,87 @@ +--- +eip: 6466 +title: SSZ Receipts Root +description: Migration of receipts MPT commitment to SSZ +author: Etan Kissling (@etan-status), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-6466-ssz-receipts-root/12884 +status: Review +type: Standards Track +category: Core +created: 2023-02-08 +requires: 6404, 6493 +--- + +## Abstract + +This EIP defines a migration process of existing Merkle-Patricia Trie (MPT) commitments for receipts to [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) + +## Motivation + +[EIP-6404](./eip-6404.md) introduces the more modern SSZ format to the `transactions_root` of the consensus `ExecutionPayloadHeader` and the execution block header. This EIP defines the equivalent transition for `receipts_root` to add support for [EIP-6493 `Receipt`](./eip-6493.md). + +Note that in contrast to the `transactions_root` which refers to a Merkle Patricia Trie (MPT) root in execution but to an SSZ root in consensus, the `receipts_root` is already consistent and refers to the same MPT root. With this EIP, it will be changed to consistently refer to the same SSZ root. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Consensus `ExecutionPayload` changes + +When building a consensus `ExecutionPayload`, the [`receipts_root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#executionpayload) is now based on the [`Receipt`](./eip-6493.md) SSZ container. [EIP-6493](./eip-6493.md) defines how RLP receipts can be converted to SSZ. + +This changes the type of `receipts_root` from an MPT [`Hash32`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types) to an SSZ [`Root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types). + +```python +class ExecutionPayload(Container): + ... + receipts_root: Root + ... +``` + +To compute the `receipts_root`, the list of individual `Receipt` containers is represented as an SSZ `List`. + +| Name | Value | +| - | - | +| [`MAX_TRANSACTIONS_PER_PAYLOAD`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/bellatrix/beacon-chain.md#execution) | `uint64(2**20)` (= 1,048,576) | + +```python +receipts = List[Receipt, MAX_TRANSACTIONS_PER_PAYLOAD]( + receipt_0, receipt_1, receipt_2, ...) + +payload.receipts_root = receipts.hash_tree_root() +``` + +### Consensus `ExecutionPayloadHeader` changes + +The [consensus `ExecutionPayloadHeader`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/capella/beacon-chain.md#executionpayloadheader) is updated to match the new `ExecutionPayload.receipts_root` definition. + +```python +class ExecutionPayloadHeader(Container): + ... + receipts_root: Root + ... +``` + +```python +payload_header.receipts_root = payload.receipts_root +``` + +### Execution block header changes + +The [execution block header's `receipts-root`](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md#block-encoding-and-validity) is updated to match the consensus `ExecutionPayloadHeader.receipts_root`. + +## Rationale + +This change enables the use of SSZ transactions as defined in [EIP-6493](./eip-6493.md). + +## Backwards Compatibility + +Applications that rely on the replaced MPT `receipts_root` in the block header require migration to the SSZ `receipts_root`. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6475.md b/EIPS/eip-6475.md index 6ae3b7b4df352e..95b77aaa04410e 100644 --- a/EIPS/eip-6475.md +++ b/EIPS/eip-6475.md @@ -18,7 +18,7 @@ This EIP introduces a new [Simple Serialize (SSZ) type](https://github.com/ether Optional values are currently only representable in SSZ using workarounds. Adding proper support provides these benefits: -1. **Better readability:** SSZ structures with optional values can be represented with ideomatic types of the underlying programming language, e.g., `Optional[T]` in Python, making them easier to interact with. +1. **Better readability:** SSZ structures with optional values can be represented with idiomatic types of the underlying programming language, e.g., `Optional[T]` in Python, making them easier to interact with. 2. **Compact serialization:** SSZ serialization can rely on the binary nature of optional values; they either exist or they don't. This allows more compact serialization than using alternative approaches based on workarounds. @@ -37,20 +37,13 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S The default value of `Optional[T]` is `None`. -### Illegal types - -`Optional[T]` with `T` that might serialize to empty data `[]` are illegal: - -- `T` MUST NOT be `List[type, N]` -- `T` MUST NOT be a nested `Optional[type]` - ### Serialization ```python if value is None: return b"" else: - return serialize(value) + return b"\x01" + serialize(value) ``` ### Deserialization @@ -58,7 +51,7 @@ else: The deserialization of an `Optional[T]` depends on the input length: - If the input length is 0, the value is `None`. -- Otherwise, deserialize the input as if it represents a value of type `T`. +- Otherwise, the first byte of the deserialization scope must be checked to be `0x01`, the remainder of the scope is deserialized same as `T`. ### Merkleization @@ -71,7 +64,9 @@ An `Optional[T]` is merkleized as a `List[T, 1]`. ### Why not `Union[None, T]`? -The serialization is less compact, due to the extra selector byte. +`Union[None, T]` leaves ambiguity about the intention whether the type may be extended in the future, i.e., `Union[None, T, U]`. + +Furthermore, SSZ Union types are currently not used in any final Ethereum specification and do not have a finalized design themselves. If the only use case is a workaround for lack of `Optional[T]`, the simpler `Optional[T]` type is sufficient, and support for general unions could be delayed until really needed. Note that the design of `Optional[T]` could be used as basis for a more general `Union`. ### Why not `List[T, 1]`? diff --git a/EIPS/eip-6492.md b/EIPS/eip-6492.md new file mode 100644 index 00000000000000..e5a1e52112afb1 --- /dev/null +++ b/EIPS/eip-6492.md @@ -0,0 +1,7 @@ +--- +eip: 6492 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6492.md diff --git a/EIPS/eip-6493.md b/EIPS/eip-6493.md new file mode 100644 index 00000000000000..466c36eba13040 --- /dev/null +++ b/EIPS/eip-6493.md @@ -0,0 +1,578 @@ +--- +eip: 6493 +title: SSZ Transaction Signature Scheme +description: Signature scheme for SSZ transactions +author: Etan Kissling (@etan-status), Matt Garnett (@lightclient), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-6493-ssz-transaction-signature-scheme/13050 +status: Review +type: Standards Track +category: Core +created: 2023-02-24 +requires: 155, 191, 1559, 2718, 2930, 4844, 5793, 7495 +--- + +## Abstract + +This EIP defines a signature scheme for [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) encoded transactions. + +## Motivation + +For each transaction, two perpetual hashes are derived. + +1. `sig_hash` is the hash of the unsigned transaction that is being signed. It is crucial that no two valid transactions ever share the same `sig_hash`. + +2. `tx_hash` is a unique identifier to refer to a signed transaction. This hash is used to refer to a transaction within the mempool, and remains stable after a transaction is included into a block. + +For existing [EIP-2718](./eip-2718.md) Recursive-Length Prefix (RLP) transactions, these hashes are based on a linear keccak256 hash across their serialization. + +For [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) transaction types, an alternative signature scheme based on SHA256 Merkle trees is defined in this EIP. + +Furthermore, this EIP defines a conversion mechanism to achieve a consistent representation across both RLP and SSZ transactions and receipts. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### [EIP-2718](./eip-2718.md) transaction types + +| Name | SSZ equivalent | Description | +| - | - | - | +| `TransactionType` | `uint8` | [EIP-2718](./eip-2718.md) transaction type, range `[0x00, 0x7F]` | + +The values `0x00` and `0x04` are marked as reserved [EIP-2718](./eip-2718.md) transaction types. + +- `0x00` indicates an [EIP-2718](./eip-2718.md) `LegacyTransaction`. +- `0x04` indicates an SSZ `Transaction` as defined in this EIP. + +| Name | Value | Description | +| - | - | - | +| (n/a) | `None` | Untyped [`LegacyTransaction`](./eip-2718.md#transactions) ('Homestead' scheme) | +| `TRANSACTION_TYPE_LEGACY` | `TransactionType(0x00)` | Untyped [`LegacyTransaction`](./eip-2718.md#transactions) ([EIP-155 scheme](./eip-155.md)) | +| `TRANSACTION_TYPE_EIP2930` | `TransactionType(0x01)` | [EIP-2930](./eip-2930.md#definitions) transaction | +| `TRANSACTION_TYPE_EIP1559` | `TransactionType(0x02)` | [EIP-1559](./eip-1559.md#specification) transaction | +| `TRANSACTION_TYPE_EIP4844` | `TransactionType(0x03)` | [EIP-4844](./eip-4844.md#parameters) transaction | +| `TRANSACTION_TYPE_SSZ` | `TransactionType(0x04)` | SSZ `Transaction` | + +Note that `0x19` is reserved to prevent collision with [ERC-191](./eip-191.md) signed data. + +### Existing definitions + +Definitions from existing specifications that are used throughout this document are replicated here for reference. + +| Name | SSZ equivalent | +| - | - | +| [`Hash32`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types) | `Bytes32` | +| [`ExecutionAddress`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/bellatrix/beacon-chain.md#custom-types) | `Bytes20` | +| [`KZGCommitment`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/polynomial-commitments.md#custom-types) | `Bytes48` | +| [`KZGProof`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/polynomial-commitments.md#custom-types) | `Bytes48` | +| [`Blob`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/polynomial-commitments.md#custom-types) | `ByteVector[BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB]` | +| [`VersionedHash`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/beacon-chain.md#custom-types) | `Bytes32` | + +| Name | Value | +| - | - | +| [`BYTES_PER_LOGS_BLOOM`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/bellatrix/beacon-chain.md#execution) | `uint64(2**8)` (= 256) | +| [`BYTES_PER_FIELD_ELEMENT`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/polynomial-commitments.md#constants) | `uint64(32)` | +| [`FIELD_ELEMENTS_PER_BLOB`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/polynomial-commitments.md#blob) | `uint64(4096)` | +| [`MAX_BLOB_COMMITMENTS_PER_BLOCK`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/deneb/beacon-chain.md#execution) | `uint64(2**12)` (= 4,096) | + +### SSZ `Transaction` container + +All SSZ transactions are represented as a single, normalized SSZ container. The definition uses the `StableContainer[N]` SSZ type and `Optional[T]` as defined in [EIP-7495](./eip-7495.md). + +| Name | Value | Description | +| - | - | - | +| `MAX_CALLDATA_SIZE` | `uint64(2**24)` (= 16,777,216) | Maximum `input` calldata byte length for a transaction | +| `MAX_ACCESS_LIST_STORAGE_KEYS` | `uint64(2**19)` (= 524,288) | Maximum number of storage keys within an access tuple | +| `MAX_ACCESS_LIST_SIZE` | `uint64(2**19)` (= 524,288) | Maximum number of access tuples within an `access_list` | +| `ECDSA_SIGNATURE_SIZE` | `32 + 32 + 1` (= 65) | Byte length of an ECDSA (secp256k1) signature | +| `MAX_FEES_PER_GAS_FIELDS` | `uint64(2**4)` (= 16) | Maximum number of fields to which `FeesPerGas` can ever grow in the future | +| `MAX_TRANSACTION_PAYLOAD_FIELDS` | `uint64(2**5)` (= 32) | Maximum number of fields to which `TransactionPayload` can ever grow in the future | +| `MAX_TRANSACTION_SIGNATURE_FIELDS` | `uint64(2**4)` (= 16) | Maximum number of fields to which `TransactionSignature` can ever grow in the future | + +| Name | SSZ equivalent | Description | +| - | - | - | +| `ChainId` | `uint64` | [EIP-155](./eip-155.md) chain ID at time of signature | +| `FeePerGas` | `uint256` | Fee per unit of gas, cannot overflow across an entire block | + +```python +class FeesPerGas(StableContainer[MAX_FEES_PER_GAS_FIELDS]): + regular: Optional[FeePerGas] + + # EIP-4844 + blob: Optional[FeePerGas] + +class AccessTuple(Container): + address: ExecutionAddress + storage_keys: List[Hash32, MAX_ACCESS_LIST_STORAGE_KEYS] + +class TransactionPayload(StableContainer[MAX_TRANSACTION_PAYLOAD_FIELDS]): + # EIP-2718 + type_: Optional[TransactionType] + + # EIP-155 + chain_id: Optional[ChainId] + + nonce: Optional[uint64] + max_fees_per_gas: Optional[FeesPerGas] + gas: Optional[uint64] + to: Optional[ExecutionAddress] + value: Optional[uint256] + input_: Optional[ByteList[MAX_CALLDATA_SIZE]] + + # EIP-2930 + access_list: Optional[List[AccessTuple, MAX_ACCESS_LIST_SIZE]] + + # EIP-1559 + max_priority_fees_per_gas: Optional[FeesPerGas] + + # EIP-4844 + blob_versioned_hashes: Optional[List[VersionedHash, MAX_BLOB_COMMITMENTS_PER_BLOCK]] + +class TransactionSignature(StableContainer[MAX_TRANSACTION_SIGNATURE_FIELDS]): + from_: Optional[ExecutionAddress] + ecdsa_signature: Optional[ByteVector[ECDSA_SIGNATURE_SIZE]] + +class Transaction(Container): + payload: TransactionPayload + signature: TransactionSignature +``` + +Valid transaction types can be defined using [EIP-7495](./eip-7495.md) `Profile`. + +```python +class BasicFeesPerGas(Profile[FeesPerGas]): + regular: FeePerGas + +class BlobFeesPerGas(Profile[FeesPerGas]): + regular: FeePerGas + blob: FeePerGas + +class EcdsaTransactionSignature(Profile[TransactionSignature]): + from_: Optional[ExecutionAddress] + ecdsa_signature: Optional[ByteVector[ECDSA_SIGNATURE_SIZE]] + +class ReplayableTransactionPayload(Profile[TransactionPayload]): + type_: TransactionType + nonce: uint64 + max_fees_per_gas: BasicFeesPerGas + gas: uint64 + to: Optional[ExecutionAddress] + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + +class ReplayableTransaction(Container): + payload: ReplayableTransactionPayload + signature: EcdsaTransactionSignature + +class LegacyTransactionPayload(Profile[TransactionPayload]): + type_: TransactionType + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BasicFeesPerGas + gas: uint64 + to: Optional[ExecutionAddress] + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + +class LegacyTransaction(Container): + payload: LegacyTransactionPayload + signature: EcdsaTransactionSignature + +class Eip2930TransactionPayload(Profile[TransactionPayload]): + type_: TransactionType + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BasicFeesPerGas + gas: uint64 + to: Optional[ExecutionAddress] + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] + +class Eip2930Transaction(Container): + payload: Eip2930TransactionPayload + signature: EcdsaTransactionSignature + +class Eip1559TransactionPayload(Profile[TransactionPayload]): + type_: TransactionType + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BasicFeesPerGas + gas: uint64 + to: Optional[ExecutionAddress] + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] + max_priority_fees_per_gas: BasicFeesPerGas + +class Eip1559Transaction(Container): + payload: Eip1559TransactionPayload + signature: EcdsaTransactionSignature + +class Eip4844TransactionPayload(Profile[TransactionPayload]): + type_: TransactionType + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BlobFeesPerGas + gas: uint64 + to: ExecutionAddress + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] + max_priority_fees_per_gas: BlobFeesPerGas + blob_versioned_hashes: List[VersionedHash, MAX_BLOB_COMMITMENTS_PER_BLOCK] + +class Eip4844Transaction(Container): + payload: Eip4844TransactionPayload + signature: EcdsaTransactionSignature + +class BasicTransactionPayload(Profile[TransactionPayload]): + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BasicFeesPerGas + gas: uint64 + to: Optional[ExecutionAddress] + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] + max_priority_fees_per_gas: BasicFeesPerGas + +class BasicTransaction(Container): + payload: BasicTransactionPayload + signature: EcdsaTransactionSignature + +class BlobTransactionPayload(Profile[TransactionPayload]): + chain_id: ChainId + nonce: uint64 + max_fees_per_gas: BlobFeesPerGas + gas: uint64 + to: ExecutionAddress + value: uint256 + input_: ByteList[MAX_CALLDATA_SIZE] + access_list: List[AccessTuple, MAX_ACCESS_LIST_SIZE] + max_priority_fees_per_gas: BlobFeesPerGas + blob_versioned_hashes: List[VersionedHash, MAX_BLOB_COMMITMENTS_PER_BLOCK] + +class BlobTransaction(Container): + payload: BlobTransactionPayload + signature: EcdsaTransactionSignature + +def select_transaction_profile(cls, value: Transaction) -> Type[Profile]: + if value.payload.type_ is None: + if value.payload.blob_versioned_hashes is not None: + return BlobTransaction + return BasicTransaction + + if value.payload.type_ == TRANSACTION_TYPE_EIP4844: + return Eip4844Transaction + + if value.payload.type_ == TRANSACTION_TYPE_EIP1559: + return Eip1559Transaction + + if value.payload.type_ == TRANSACTION_TYPE_EIP2930: + return Eip2930Transaction + + if value.payload.chain_id is not None: + return LegacyTransaction + + return ReplayableTransaction +``` + +Future specifications MAY: + +- Append fields to `TransactionPayload` and `TransactionSignature` +- Adjust `Profile` types and update `select_transaction_profile` logic + +Such changes [do not affect](./eip-7495.md) how existing transactions serialize or merkleize. + +![Transaction merkleization](../assets/eip-6493/transaction.png) + +### Transaction signature scheme + +When an SSZ transaction is signed, additional information is mixed into the `sig_hash` to uniquely identify the underlying specifications. If other networks define additional transaction types, they MUST use a different `DomainType` for signing SSZ data. + +| Name | Value | Description | +| - | - | - | +| `DOMAIN_TRANSACTION_SSZ` | `DomainType('0x04000080)` | [`DomainType`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/beacon-chain.md#custom-types) for signing SSZ transactions compatible with this EIP | + +The hash to sign `sig_hash` and the unique transaction identifier `tx_hash` are computed using [`hash_tree_root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md#merkleization). + +```python +class ExecutionSigningData(Container): + object_root: Root + domain_type: DomainType + +def compute_ssz_sig_hash(payload: TransactionPayload) -> Hash32: + return Hash32(ExecutionSigningData( + object_root=payload.hash_tree_root(), + domain=DOMAIN_TRANSACTION_SSZ, + ).hash_tree_root()) + +def compute_ssz_tx_hash(tx: Transaction) -> Hash32: + assert tx.payload.type_ == TRANSACTION_TYPE_SSZ + return Hash32(tx.hash_tree_root()) +``` + +### Transaction validation + +As part of `Transaction` validation, the `from` address MUST be checked for consistency with the `ecdsa_signature`. + +```python +def ecdsa_pack_signature(y_parity: bool, + r: uint256, + s: uint256) -> ByteVector[ECDSA_SIGNATURE_SIZE]: + return r.to_bytes(32, 'big') + s.to_bytes(32, 'big') + bytes([0x01 if y_parity else 0x00]) + +def ecdsa_unpack_signature(signature: ByteVector[ECDSA_SIGNATURE_SIZE]) -> tuple[bool, uint256, uint256]: + y_parity = signature[64] != 0 + r = uint256.from_bytes(signature[0:32], 'big') + s = uint256.from_bytes(signature[32:64], 'big') + return (y_parity, r, s) + +def ecdsa_validate_signature(signature: ByteVector[ECDSA_SIGNATURE_SIZE]): + SECP256K1N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 + assert len(signature) == 65 + assert signature[64] in (0, 1) + _, r, s = ecdsa_unpack_signature(signature) + assert 0 < r < SECP256K1N + assert 0 < s < SECP256K1N + +def ecdsa_recover_from_address(signature: ByteVector[ECDSA_SIGNATURE_SIZE], + sig_hash: Hash32) -> ExecutionAddress: + ecdsa = ECDSA() + recover_sig = ecdsa.ecdsa_recoverable_deserialize(signature[0:64], signature[64]) + public_key = PublicKey(ecdsa.ecdsa_recover(sig_hash, recover_sig, raw=True)) + uncompressed = public_key.serialize(compressed=False) + return ExecutionAddress(keccak(uncompressed[1:])[12:]) + +def validate_transaction(tx): + ecdsa_validate_signature(tx.signature.ecdsa_signature) + assert tx.signature.from_ == ecdsa_recover_from_address( + tx.signature.ecdsa_signature, + compute_sig_hash(tx), + ) +``` + +See [EIP assets](../assets/eip-6493/tx_hashes.py) for a definition of `compute_sig_hash` that takes the various transaction types into account. + +### SSZ `PooledTransaction` container + +During transaction gossip responses ([`PooledTransactions`](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md#pooledtransactions-0x0a)), each `Transaction` is wrapped into a `PooledTransaction`. The definition uses the `StableContainer[N]` SSZ type and `Optional[T]` as defined in [EIP-7495](./eip-7495.md). + +| Name | Value | Description | +| - | - | - | +| `MAX_POOLED_TRANSACTION_FIELDS` | `uint64(2**3)` (= 8) | Maximum number of fields to which `PooledTransaction` can ever grow in the future | + +```python +class BlobData(Container): + blobs: List[Blob, MAX_BLOB_COMMITMENTS_PER_BLOCK] + commitments: List[KZGCommitment, MAX_BLOB_COMMITMENTS_PER_BLOCK] + proofs: List[KZGProof, MAX_BLOB_COMMITMENTS_PER_BLOCK] + +class PooledTransaction(StableContainer[MAX_POOLED_TRANSACTION_FIELDS]): + tx: Transaction + blob_data: Optional[BlobData] +``` + +The same additional validation constraints as defined in [EIP-4844](./eip-4844.md) also apply to transactions that define `tx.payload.blob_versioned_hashes` or `blob_data`. + +Future specifications MAY: + +- Add fields to the end of `PooledTransactionPayload` +- Convert existing fields to `Optional` + +Such changes [do not affect](./eip-7495.md) how existing pooled transactions serialize, merkleize, or validate. + +### SSZ `Receipt` container + +All SSZ receipts are represented as a single, normalized SSZ container. The definition uses the `StableContainer[N]` SSZ type and `Optional[T]` as defined in [EIP-7495](./eip-7495.md). + +| Name | Value | Description | +| - | - | - | +| `MAX_TOPICS_PER_LOG` | `4` | `LOG0` through `LOG4` opcodes allow 0-4 topics per log | +| `MAX_LOG_DATA_SIZE` | `uint64(2**24)` (= 16,777,216) | Maximum `data` byte length for a log | +| `MAX_LOGS_PER_RECEIPT` | `uint64(2**21)` (= 2,097,152) | Maximum number of entries within `logs` | +| `MAX_RECEIPT_FIELDS` | `uint64(2**5)` (= 32) | Maximum number of fields to which `Receipt` can ever grow in the future | + +```python +class Log(Container): + address: ExecutionAddress + topics: List[Bytes32, MAX_TOPICS_PER_LOG] + data: ByteList[MAX_LOG_DATA_SIZE] + +class Receipt(StableContainer[MAX_RECEIPT_FIELDS]): + root: Optional[Hash32] + gas_used: Optional[uint64] + contract_address: Optional[ExecutionAddress] + logs_bloom: Optional[ByteVector[BYTES_PER_LOGS_BLOOM]] + logs: Optional[List[Log, MAX_LOGS_PER_RECEIPT]] + + # EIP-658 + status: Optional[boolean] +``` + +Valid receipt types can be defined using [EIP-7495](./eip-7495.md) `Profile`. + +```python +class HomesteadReceipt(Profile[Receipt]): + root: Hash32 + gas_used: uint64 + contract_address: Optional[ExecutionAddress] + logs_bloom: ByteVector[BYTES_PER_LOGS_BLOOM] + logs: List[Log, MAX_LOGS_PER_RECEIPT] + +class BasicReceipt(Profile[Receipt]): + gas_used: uint64 + contract_address: Optional[ExecutionAddress] + logs_bloom: ByteVector[BYTES_PER_LOGS_BLOOM] + logs: List[Log, MAX_LOGS_PER_RECEIPT] + status: boolean + +def select_receipt_profile(value: Receipt) -> Type[Profile]: + if value.status is not None: + return BasicReceipt + + return HomesteadReceipt +``` + +Future specifications MAY: + +- Add fields to the end of `Receipt` +- Adjust `Profile` types and update `select_receipt_profile` logic + +Such changes [do not affect](./eip-7495.md) how existing receipts serialize or merkleize. + +![Receipt merkleization](../assets/eip-6493/receipt.png) + +### Networking + +When exchanging SSZ transactions and receipts via the [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md), the following [EIP-2718](./eip-2718.md) compatible envelopes are used: + +- `Transaction`: `TRANSACTION_TYPE_SSZ || snappyFramed(ssz)` +- `PooledTransaction`: `TRANSACTION_TYPE_SSZ || snappyFramed(ssz(PooledTransaction))` +- `Receipt`: `TRANSACTION_TYPE_SSZ || snappyFramed(ssz(Receipt))` + +Objects are encoded using [SSZ](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) and compressed using the Snappy framing format, matching the encoding of consensus objects as defined in the [consensus networking specification](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/specs/phase0/p2p-interface.md#ssz-snappy-encoding-strategy). As part of the encoding, the uncompressed object length is emitted; the RECOMMENDED limit to enforce per object is [`MAX_CHUNK_SIZE`](https://github.com/ethereum/consensus-specs/blob/e3a939e439d6c05356c9c29c5cd347384180bc01/specs/phase0/p2p-interface.md#configuration) bytes. + +Implementations SHOULD continue to support accepting RLP transactions into their transaction pool. However, such transactions MUST be converted to SSZ for inclusion into an `ExecutionPayload`. See [EIP assets](../assets/eip-6493/convert.py) for a reference implementation to convert from RLP to SSZ, as well as corresponding [test cases](../assets/eip-6493/convert_tests.py). The original `sig_hash` and `tx_hash` are retained throughout the conversion process. + +### Transaction gossip announcements + +The semantics of the [`types` element](./eip-5793.md) in transaction gossip announcements ([`NewPooledTransactionHashes`](https://github.com/ethereum/devp2p/blob/6b259a7003b4bfb18365ba690f4b00ba8a26393b/caps/eth.md#newpooledtransactionhashes-0x08)) is changed to match `ssz(PooledTransaction.active_fields())`: + +| `types` | Description | +| - | - | +| `0x00` | Untyped [`LegacyTransaction`](./eip-2718.md#transactions) ('Homestead' scheme, or [EIP-155 scheme](./eip-155.md)) | +| `0x01` | [EIP-2930](./eip-2930.md) transaction, or basic SSZ `PooledTransaction` without any additional auxiliary payloads | +| `0x02` | [EIP-1559](./eip-1559.md) transaction | +| `0x03` | [EIP-4844](./eip-4844.md) transaction, or SSZ `PooledTransaction` with `blob_data` | + +### Engine API + +When exchanging via the engine API, the structure of the `transactions` field in `ExecutionPayload` versions adopting this EIP is changed from `Array of DATA` to `Array of TransactionV1`. + +`TransactionV1` is defined to map onto the SSZ `Transaction` `StableContainer`, as follows: + +- `payload`: `TransactionPayloadV1` - An `OBJECT` containing the fields of a `TransactionPayloadV1` structure +- `signature`: `TransactionSignatureV1` - An `OBJECT` containing the fields of a `TransactionSignatureV1` structure + +`TransactionPayloadV1` is defined to map onto the SSZ `TransactionPayload` `StableContainer`, as follows: + +- `type`: `QUANTITY|null`, 8 Bits or `null` +- `chainId`: `QUANTITY|null`, 64 Bits or `null` +- `nonce`: `QUANTITY|null`, 64 Bits or `null` +- `maxFeesPerGas`: `FeesPerGasV1|null` - An `OBJECT` containing the fields of a `FeesPerGasV1` structure or `null` +- `gas`: `QUANTITY|null`, 64 Bits or `null` +- `to`: `DATA|null`, 20 Bytes or `null` +- `value`: `QUANTITY|null`, 256 Bits or `null` +- `input`: `DATA|null`, 0 through `MAX_CALLDATA_SIZE` bytes or `null` +- `accessList`: `Array of AccessTupleV1` - 0 through `MAX_ACCESS_LIST_SIZE` `OBJECT` entries each containing the fields of an `AccessTupleV1` structure, or `null` +- `maxPriorityFeesPerGas`: `FeesPerGasV1|null` - An `OBJECT` containing the fields of a `FeesPerGasV1` structure or `null` +- `blobVersionedHashes`: `Array of DATA|null` - 0 through `MAX_BLOB_COMMITMENTS_PER_BLOCK` `DATA` entries each containing 32 Bytes, or `null` + +`FeesPerGasV1` is defined to map onto the SSZ `FeesPerGas` `StableContainer`, as follows: + +- `regular`: `QUANTITY|null`, 256 Bits or `null` +- `blob`: `QUANTITY|null`, 256 Bits or `null` + +`AccessTupleV1` is defined to map onto the SSZ `AccessTuple` `Container`, as follows: + +- `address`: `DATA`, 20 Bytes +- `storageKeys`: `Array of DATA` - 0 through `MAX_ACCESS_LIST_STORAGE_KEYS` `DATA` entries each containing 32 Bytes + +`TransactionSignatureV1` is defined to map onto the SSZ `TransactionSignature` `StableContainer`, as follows: + +- `from`: `DATA|null`, 20 Bytes or `null` +- `ecdsaSignature`: `DATA|null`, 65 Bytes or `null` + +## Rationale + +### Why SSZ transactions? + +1. **Transaction inclusion proofs:** Currently, there is no commitment to the transaction hash stored on chain. Therefore, proving inclusion of a certain transaction within a block requires sending the entire transaction body, and proving a list of all transaction hashes within a block requires sending _all_ transaction bodies. With SSZ, a transaction can be ["summarized"](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md#summaries-and-expansions) by it's [`hash_tree_root`](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md#merkleization), unlocking transaction root proofs without sending all transaction bodies, and compact transaction inclusion proofs by root. + +2. **Better for light clients:** With SSZ, individual fields of a transaction or receipt can be proven. This allows light clients to obtain only fields relevant to them. Furthermore, common fields fields always merkleize at the same [generalized indices](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/merkle-proofs.md), allowing existing verification logic to continue working even when future updates introduce additional transaction or receipt fields. + +3. **Better for smart contracts:** Smart contracts that validate transactions or receipts benefit from the ability to prove individual chunks of a transaction. Gas fees may be lower, and it becomes possible to process transactions and receipts that do not fully fit into calldata. + +4. **Smaller data size:** SSZ objects are typically compressed using Snappy framed compression. Transaction `input` and `access_list` fields as well as receipt `logs_bloom` and `logs` fields often contain a lot of zero bytes and benefit from this compression. Snappy framed compression allows sending sequences of transactions and receipts without having to recompress, and is designed to be computationally inexpensive. + +### Why include the `from` address in transactions? + +For transactions converted from RLP, the `sig_hash` is computed from its original RLP representation. To avoid requiring API clients to implement the original RLP encoding and keccak hashing, the `from` address is included as part of the `Transaction`. + +Note that this also eliminates the need for secp256k1 public key recovery when serving JSON-RPC API requests, as the `from` address is already known. + +Furthermore, this allows early rejecting transactions with sender accounts that do not have sufficient balance, as the `from` account balance can be checked without the computationally expensive `ecrecover`. + +### Why include the `contract_address` in receipts? + +Computing the address of a newly created contract requires RLP encoding and keccak hashing. Adding a commitment on-chain avoids requiring API clients to implement those formats. + +Even though the `contract_address` is statically determinable from the corresponding `Transaction` alone, including it in the `Receipt` allows the mechanism by which it is computed to change in the future. + +### Why the `ExecutionSigningData`? + +If other SSZ objects are being signed in the future, e.g., messages, it must be ensured that their hashes do not collide with transaction `sig_hash`. Mixing in a constant that indicates that `sig_hash` pertains to an SSZ transaction prevents such hash collisions. + +### What about EIP-2718 transaction types? + +All SSZ transactions (including future ones) share the single [EIP-2718](./eip-2718.md) transaction type `TRANSACTION_TYPE_SSZ`. Future features can introduce new optional fields as well as new allowed combination of optional fields, as determined by `select_transaction_profile`. + +This also reduces combinatorial explosion; for example, the `access_list` property could be made optional for all SSZ transactions without having to double the number of defined transaction types. + +### Why redefine `types` for `NewPooledTransactionHashes`? + +The `types` element as introduced in eth/68 via [EIP-5793](./eip-5793.md) allows the receiving node better control over the data it fetches from the peer and allows throttling the download of specific types. + +Current implementations primarily use `types` to distinguish type `0x03` blob transactions from basic type `0x00`, `0x01` and `0x02` transactions. However, all SSZ `Transaction` use type `0x04` (`TRANSACTION_TYPE_SSZ`), eliminating this optimization potential. + +To restore the optimization potential, `types` is redefined to indicate instead what auxiliary payloads are present in the `PooledTransaction`: SSZ blob transactions will share type `0x03` with RLP blob transactions, while basic SSZ transactions will be assigned type `0x01`, which is currently also used for a basic RLP transaction type. Therefore, implementations will not require changes to distinguish blob transactions from basic transactions. + +### Why change from `cumulative_gas_used` to `gas_used` in receipts? + +[EIP-658](./eip-658.md) replaced the intermediate post-state `root` from receipts with a boolean `status` code. Replacing `cumulative_gas_used` with `gas_used` likewise replaces the final stateful field with a stateless one, unlocking future optimization potential as transaction receipts operating on distinct state no longer depend on their order. Furthermore, API clients no longer need to fetch information from multiple receipts if they want to validate the `gas_used` of an individual transaction. + +### What about `Log` data in receipts? + +`Log` data is formatted according to the Ethereum contract ABI. Merkleizing log data according to its original structure would be more useful than merkleizing it as a `ByteVector`. However, the data structure is determined by the log event signature, of which only the hash is known. As the hash preimages are erased from emitted EVM logs, it is not reliably possible to recover the original log event signature. Therefore, log data and transaction input data are provided as a `ByteVector` for now. + +## Backwards Compatibility + +The new transaction signature scheme is solely used for SSZ transactions. + +Existing RLP transactions can be converted to SSZ transactions. Their original `sig_hash` and `tx_hash` can be recovered from their SSZ representation. + +Existing RLP receipts can be converted to SSZ receipts. The full sequence of accompanying transactions must be known to fill-in the new `contract_address` field. Note that because JSON-RPC exposes the `contract_address`, implementations are already required to know the transaction before queries for receipts can be served. + +## Security Considerations + +SSZ signatures MUST NOT collide with existing RLP transaction and message hashes. + +As RLP messages are hashed using keccak256, and all SSZ objects are hashed using SHA256. These two hashing algorithms are both considered cryptographically secure and are based on fundamentally different approaches, minimizing the risk of hash collision between those two hashing algorithms. + +Furthermore, RLP messages are hashed linearly across their serialization, while SSZ objects are hashed using a recursive Merkle tree. Having a different mechanism further reduce the risk of hash collisions. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6506.md b/EIPS/eip-6506.md new file mode 100644 index 00000000000000..36457b4509bc03 --- /dev/null +++ b/EIPS/eip-6506.md @@ -0,0 +1,7 @@ +--- +eip: 6506 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6506.md diff --git a/EIPS/eip-6538.md b/EIPS/eip-6538.md new file mode 100644 index 00000000000000..9db10ae1e895d6 --- /dev/null +++ b/EIPS/eip-6538.md @@ -0,0 +1,7 @@ +--- +eip: 6538 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6538.md diff --git a/EIPS/eip-6551.md b/EIPS/eip-6551.md new file mode 100644 index 00000000000000..348f6e5ae49ed1 --- /dev/null +++ b/EIPS/eip-6551.md @@ -0,0 +1,7 @@ +--- +eip: 6551 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6551.md diff --git a/EIPS/eip-6596.md b/EIPS/eip-6596.md new file mode 100644 index 00000000000000..ed34bd6ba5b0e8 --- /dev/null +++ b/EIPS/eip-6596.md @@ -0,0 +1,7 @@ +--- +eip: 6596 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6596.md diff --git a/EIPS/eip-6604.md b/EIPS/eip-6604.md new file mode 100644 index 00000000000000..d8d09b67424c82 --- /dev/null +++ b/EIPS/eip-6604.md @@ -0,0 +1,7 @@ +--- +eip: 6604 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6604.md diff --git a/EIPS/eip-6617.md b/EIPS/eip-6617.md new file mode 100644 index 00000000000000..aa60113d2ac4c3 --- /dev/null +++ b/EIPS/eip-6617.md @@ -0,0 +1,7 @@ +--- +eip: 6617 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6617.md diff --git a/EIPS/eip-663.md b/EIPS/eip-663.md index 2d88e22e27903f..778fb19a1db7f2 100644 --- a/EIPS/eip-663.md +++ b/EIPS/eip-663.md @@ -1,19 +1,19 @@ --- eip: 663 -title: Unlimited SWAP and DUP instructions -description: Introduce SWAPN and DUPN which take an immediate value for the depth -author: Alex Beregszaszi (@axic) +title: SWAPN, DUPN and EXCHANGE instructions +description: Introduce additional instructions for manipulating the stack which allow accessing the stack at higher depths +author: Alex Beregszaszi (@axic), Charles Cooper (@charles-cooper), Danno Ferrin (@shemnon) discussions-to: https://ethereum-magicians.org/t/eip-663-unlimited-swap-and-dup-instructions/3346 status: Review type: Standards Track category: Core created: 2017-07-03 -requires: 3540 +requires: 3540, 5450 --- ## Abstract -Currently, `SWAP` and `DUP` instructions are limited to a stack depth of 16. Introduce two new instructions, `SWAPN` and `DUPN`, which lift this limitation and allow accessing the stack up to depth of 256 items. +Currently, `SWAP*` and `DUP*` instructions are limited to a stack depth of 16. Introduce three new instructions, `SWAPN`, `DUPN` and `EXCHANGE` which lift this limitation and allow accessing the stack at higher depths. ## Motivation @@ -23,35 +23,39 @@ Furthermore, implementing higher level constructs, such as functions, on top of The number of these arguments (or stack items) can easily exceed 16 and thus will require extra care from a compiler to lay them out in a way that all of them are still accessible. -Introducing `SWAPN` and `DUPN` will provide an option to compilers to simplify accessing deep stack items at the price of possibly increased gas costs. +Lastly, swapping items besides the 1st and Nth items in the stack is very important for compilers implementing stack scheduling algorithms (the analog of register allocation for stack machines), which try to minimize stack traffic given a set of variables and usage analysis. + +Introducing `SWAPN`, `DUPN` and `EXCHANGE` will provide an option to compilers to simplify accessing deep stack items. ## Specification We introduce two new instructions: - 1. `DUPN` (`0xb5`) - 2. `SWAPN` (`0xb6`) - -If the code is legacy bytecode, both of these instructions result in an *exceptional halt*. (*Note: This means no change to behaviour.*) + 1. `DUPN` (`0xe6`) + 1. `SWAPN` (`0xe7`) + 2. `EXCHANGE` (`0xe8`) -If the code is valid EOF1, the following execution rules apply: +If the code is legacy bytecode, any of these instructions result in an *exceptional halt*. (*Note: This means no change to behaviour.*) - 1. These instructions are followed by an 8-bit immediate value, which we call `imm`, and can have a value of 0 to 255. We introduce the variable `n` which equals to `imm + 1`. +If the code is valid EOF1, the following rules apply: - 2. For `DUPN`: + 1. The instructions are followed by an 8-bit immediate value, which we call `imm`, and can have a value of 0 to 255. + 1.1 In the case of `DUPN` and `SWAPN`, we introduce the variable `n` which equals to `imm + 1`. + 1.2 In the case of `EXCHANGE`, we introduce the variable `n` which is equal to `imm >> 4 + 1`, and the variable `m` which is equal to `imm & 0x0F + 1` (i.e., the first and second nibbles of `imm`, converted to one-indexing). - - If the current stack height is less than `n`, then a stack underflow exception is issued. - - If the current stack height is at the limit (1024), a stack overflow exception is issued. - - Otherwise the `n`'th stack item is duplicated at the top of the stack. (*Note: We use 1-based indexing here.*) + 2. Code validation is extended to check that no relative jump instruction (`RJUMP`/`RJUMPI`/`RJUMPV`) targets immediate values of `DUPN`, `SWAPN` or `EXCHANGE`. - 3. For `SWAPN`: + 3. The stack validation algorithm of [EIP-5450](./eip-5450.md) is extended: + 3.1. Before `DUPN` if the current stack height is less than `n`, code is invalid. After `DUPN`, the stack height is incremented. + 3.2. Before `SWAPN` if the current stack height is less than `n + 1`, code is invalid. After `SWAPN`, the stack height is unchanged. + 3.2. Before `EXCHANGE` if the current stack height is less than `n + m + 1`, code is invalid. After `EXCHANGE`, the stack height is unchanged. - - If the current stack height is less than `n + 1`, then a stack underflow exception is issued. - - Otherwise the `n + 1`th stack item is swapped with the top stack item. + 4. Execution rules: + 4.1. `DUPN`: the `n`'th stack item is duplicated at the top of the stack. (*Note: We use 1-based indexing here.*) + 4.2. `SWAPN`: the `n + 1`'th stack item is swapped with the top of the stack. + 4.3 `EXCHANGE`: the `n + 1`'th stack item is swapped with the `n + m + 1`'th stack item. -Clarification: the "stack underflow/overflow exception" means the EVM execution is halted and all gas is consumed. - -The gas cost for both instructions is set at 3. +The gas cost for all three instructions is set at 3. ## Rationale @@ -61,28 +65,41 @@ Since this instruction depends on an immediate argument encoding, it can only be ### Size of immediate argument -A 16-bit size was considered to accommodate the full stack space of 1024 items, however: +For `DUPN` and `SWAPN` a 16-bit size was considered to accommodate the full stack space of 1024 items, however: 1. that would require an additional restriction/check (`n < 1024`) 2. the 256 depth is a large improvement over the current 16 and the overhead of an extra byte would make it less useful +Similarly for `EXCHANGE`, the proposed scheme allows addressing of 32 items. + +### Gas cost + +The gas cost for these operations is the same as for existing `DUP*` and `SWAP*` instructions, because they are just implemented as pointer swaps. + +### `EXCHANGE` vs `SWAPN` + +As mentioned before, `EXCHANGE` is important to compilers implementing stack scheduling algorithms. Specifically, in the case that a stack item is scheduled to be consumed deeper in the stack (for instance, the 3rd item in the stack needs to be moved into 2nd position in order to be consumed by the next operation), that currently takes three instructions, `SWAP2 SWAP3 SWAP2`. However, in the EVM implementation, the implementation is just a pointer swap, so it could be implemented in a single instruction at no extra runtime cost to the client. + ## Backwards Compatibility This has no effect on backwards compatibility because the opcodes were not previously allocated and the feature is only enabled in EOF. ## Test Cases -For `0 <= n <= 255`: +Given `stack[]` is a 0-based data structure, and `n`, `m` and `imm` are defined as according to the spec: - - `DUPN n` to fail if `stack_height < n`. - - `SWAPN n` to fail if `stack_height < (n + 1)`. - - `DUPN n` to fail if `stack_height + 1 > 1024`. - - `DUPN n` and `SWAPN n` to fail if gas available is less than 3. - - otherwise `DUPN n` should push the `stack[n]` item to the stack, and `SWAPN n` should swap `stack[n + 1]` with `stack[stack.top()]`. + - `DUPN imm` to fail validation if `stack_height < n`. + - `SWAPN imm` to fail validation if `stack_height < n + 1`. + - `EXCHANGE imm` to fail validation if `stack_height < n + m + 1`. + - `DUPN imm` to increment maximum stack height of a function. Validation fails if maximum stack height exceeds limit of 1023. + - `DUPN imm`, `SWAPN imm`, and `EXCHANGE imm` to fail at run-time if gas available is less than 3. + - `DUPN imm` should duplicate the `stack[n - 1]` item and push it to the stack + - `SWAPN imm` should swap `stack[n]` with `stack[stack.top()]` + - `EXCHANGE imm` should swap `stack[n]` with `stack[n + m]`. ## Security Considerations -The authors are not aware of any additional risks introduced here. The EVM stack is fixed at 1024 items and most implementations keep that in memory at all times. This change will increase the easy-to-access number of items from 16 to 256. +The authors are not aware of any additional risks introduced here. The EVM stack is fixed at 1024 items and most implementations keep that in memory at all times. This change will increase the number of stack items accessible via single instruction. ## Copyright diff --git a/EIPS/eip-6662.md b/EIPS/eip-6662.md new file mode 100644 index 00000000000000..6ab517409f8834 --- /dev/null +++ b/EIPS/eip-6662.md @@ -0,0 +1,7 @@ +--- +eip: 6662 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6662.md diff --git a/EIPS/eip-6672.md b/EIPS/eip-6672.md new file mode 100644 index 00000000000000..476d9115c703b3 --- /dev/null +++ b/EIPS/eip-6672.md @@ -0,0 +1,7 @@ +--- +eip: 6672 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6672.md diff --git a/EIPS/eip-6682.md b/EIPS/eip-6682.md new file mode 100644 index 00000000000000..66b0a401300815 --- /dev/null +++ b/EIPS/eip-6682.md @@ -0,0 +1,7 @@ +--- +eip: 6682 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6682.md diff --git a/EIPS/eip-6690.md b/EIPS/eip-6690.md new file mode 100644 index 00000000000000..52aeec02ef053b --- /dev/null +++ b/EIPS/eip-6690.md @@ -0,0 +1,631 @@ +--- +eip: 6690 +title: EVM Modular Arithmetic Extensions (EVMMAX) +description: Create modular addition, subtraction, and multiplication opcodes. +author: Jared Wasinger (@jwasinger), Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-6690-evm-modular-arithmetic-extensions-evmmax-decoupled-from-eof/13322 +status: Draft +type: Standards Track +category: Core +created: 2023-03-15 +--- + +## Abstract + +This EIP proposes the addition of new optimized modular addition, subtraction and multiplication opcodes to the EVM. These support odd moduli up to 4096 bits in size. + +## Motivation + +Benefits of the changes proposed in this EIP: + +* enables elliptic curve arithmetic operations on various curves including BLS12-381 to be implemented as EVM contracts +* For operations on values up to 256bits in size, reduces gas cost per operation by 90-95% compared to the current `MULMOD` and `ADDMOD` opcodes. +* for all cases where modexp precompile is useful, it could now be implemented as an EVM contract. +* enables substantial cost reductions for algebraic hash functions (e.g. MiMC/Poseidon), zkp verification in the EVM. + +## Specification + +### Overview + +During contract execution, a contract calls a setup instruction `SETUPX`, sourcing a modulus from a specified memory offset/size and computing several parameters used to speed up modular multiplication (referred to as "Montgomery" parameters). A zeroed memory space (whose size is a stack parameter passed to `SETUPX`) is allocated separate from EVM memory. + +The modulus, computed parameters and memory space are associated with the current call frame state and referred to as the active modulus state. If `SETUPX` is called again to switch to a different modulus, the memory space and Montgomery parameters of the previous active modulus state remain allocated (the memory spaces of active/previously-active modulus state are separate). + +New store and load opcodes `STOREX`/`LOADX` are used to copy multiples values to/from EVM memory and the memory space of the active modulus state. + +Arithmetic is performed with `ADDMODX`/`SUBMODX`/`MULMODX` opcodes which take and return no stack items, require a 3-byte immediate value appended to the opcode. + +The immediate is interpreted as 3 1-byte values `z`, `x`, `y` which are indexes to the array of EVMMAX values that comprise the memory space of the active modulus state. + +An arithmetic operation is performed on inputs at index `x`/`y` placing the result in index `z`. + +### Conventions + +1. `x === y % m`: `x % m == y % m` +2. `pow(x, -1, m)`: The modular multiplicative inverse of `x` with respect to modulus `m`. +2. Opcode definition syntax is formatted as `mneumonic {immediate - type} {immediate2 - type} ...: stack_arg_1, stack_arg_2, ...` where immediates are listed in the order that they proceed the opcode and stack arguments are ordered starting at the top of the stack. +3. In the provided pseudocode, it is assumed that opcode gas charging logic is executed prior to execution logic. +4. Any exception thrown should immediately end the current execution frame and return to the caller. + +### Constants + +| Name | Value | Description | +| ---- | ---- | ---- | +| `STOREX_BASE_GAS` | 3 | base gas cost for `STOREX` opcode | +| `LOADX_BASE_GAS` | 3 | base gas cost for `LOADX` opcode | +| `SETUPX_BASE_GAS` | 3 | base gas cost for `SETUPX` opcode | +| `EVMMAX_MAX_MEM` | 65,536 bytes | maximum amount of EVMMAX memory that can be used in a call frame | +| `MAX_MOD_SIZE` | 4096 bits | tentative modulus size limit (can probably be removed because `EVMMAX_MAX_MEM_SIZE` effectively caps the modulus size) | +| `MULMODX_SUBQUADRATIC_START` | 50 | modulus size in multiples of 8 bytes where we switch to subquadratic mulmont cost model | +| `SYSTEM_WORD_SIZE_BITS` | varies depending on the system | word size in bits of a client's CPU | + +### Context Variables + +| Name | Type | Meaning | +| ---- | ------- | --- | +| `evmmax_state` | `EVMMAXState` | a variable representing ephemeral state which exists for the duration of the current call and in the scope of the current call frame | +| `evm_memory` | `bytes` | EVM memory for the current call context | +| `expand_evm_memory` | `func(size_words: int)` | expands EVM memory by `size_words * 32` bytes | +| `cost_evm_memory_expansion` | `func(new_size_evm_words: int) -> int` | EVM memory expansion cost function, modified according to this EIP | +| `evm_stack` | object | Allows access to the stack via `pop()` and `peek(n)` which return `int` stack elements | +| `contract_code` | `bytes` | code of the currently-executing contract | +| `pc` | `int` | EVM program counter | + +``` +class EVMMAXState(): + def __init__(self): + # ModState currently being used + self.active_mod_state = None + # a lookup of mod_id (int) -> ModState + self.mods = {} + +class ModState(): + def __init__(self, mod: int, num_vals_used: int, mod: int, r: int, r_squared: int, mod_inv_full=None, mod_inv=None): + self.mod = mod + # size (expressed in multiples of 8 bytes) needed to represent mod + self.val_size_multiplier = math.ceil(len(hex(mod)[2:]) / (2 * 8)) + + self.num_vals_used = num_vals_used + self.mod_inv = mod_inv + self.mod_inv_full = mod_inv_full + self.r = r + self.r_squared = r_squared + # a memory space of size num_vals_used * val_size_multiplier + self.values = [0] * self.num_vals_used +``` + +### Helpers + +``` +# ----------------------------------------------------------------------------- +# gas-charging helpers + +def cost_precompute_mont(val_size_multiplier: int) -> int: + PRECOMPUTE_MONT_LO_GAS_A = ? + PRECOMPUTE_MONT_LO_GAS_B = ? + + PRECOMPUTE_MONT_HI_GAS_A = ? + PRECOMPUTE_MONT_HI_GAS_B = ? + + cost = 0 + + if val_size_multiplier < MULMODX_SUBQUADRATIC_START: + cost = math.ceil(PRECOMPUTE_MONT_LO_GAS_A * val_size_multiplier + \ + PRECOMPUTE_MONT_LO_GAS_B) + else: + cost = math.ceil(PRECOMPUTE_MONT_HI_GAS_A * val_size_multiplier + \ + PRECOMPUTE_MONT_HI_GAS_B) + + return cost + +def cost_addmodx(val_size_multiplier: int) -> int: + ADDMODX_GAS_A = 0.20 + ADDMODX_GAS_B = 0.15 + + cost = 0 + if val_size_multiplier == 6: + cost = 1 + else: + cost = round(ADDMODX_GAS_A * limb_count + ADDMODX_GAS_B) + + if cost == 0: + cost = 1 + + return cost + +def cost_mulmodx(val_size_multiplier: int) -> int: + MULMODX_LO_GAS_A = 0.090 + MULMODX_LO_GAS_B = 0 + MULMODX_LO_GAS_C = 0.24 + + MULMODX_HI_GAS_A = 0 + MULMODX_HI_GAS_B = 10.0 + MULMODX_HI_GAS_C = -270.0 + + cost = 0 + + if val_size_multiplier == 6: + cost = 2 + elif val_size_multiplier < MULMODX_SUBQUADRATIC_START: + cost = math.ceil(MULMODX_LO_GAS_A * (val_size_multiplier ** 2) + \ + MULMODX_LO_GAS_B * val_size_multiplier + \ + MULMODX_LO_GAS_C) + else: + cost = math.ceil(MULMODX_HI_GAS_A * val_size_multiplier ** 2 + \ + MULMODX_HI_GAS_B * val_size_multiplier + \ + MULMODX_HI_GAS_C) + + if cost == 0: + cost = 1 + + return cost + +# ----------------------------------------------------------------------------- +# bigint helpers +# a bigint is a unsigned number represented as a list of unsigned system words in descending order of significance + +# split a double-width value into hi/low words +def hi_lo(double_width_val: int) -> (int, int): + base = 2**SYSTEM_WORD_SIZE_BITS + assert double_width_val < base**SYSTEM_WORD_SIZE_BITS, "val must fit in two words" + return (double_width_val >> SYSTEM_WORD_SIZE_BITS) % base, double_width_val % base + +def bigint_to_int(x: [int]) -> int: + res = 0 + for i in reversed(range(len(x))): + res += x[i] * 2**(SYSTEM_WORD_BITS * (len(x) - i - 1)) + return res + +def int_to_bigint(x: int, word_count: int): + res = [0] * word_count + for i in range(word_count): + res[word_count - i - 1] = x & (2**SYSTEM_WORD_BITS - 1) + x >>= SYSTEM_WORD_BITS + return res + +# return x - y (omitting borrow-out) +def bigint_sub(x: [int], y: [int]) -> [int]: + num_words = len(x) + res = [0] * num_words + c = 0 + + for i in reversed(range(num_words)): + c, res[i] = sub_with_borrow(x[i], y[i], c) + + return res + +# return x >= y +def bigint_gte(x: [int], y: [int]) -> bool: + for (x_word, y_word) in list(zip(x,y)): + if x_word > y_word: + return True + elif x_word < y_word: + return False + # x == y + return True + +# CIOS Montgomery multiplication algorithm +# +# input: +# * x, y, mod - bigint inputs of `val_size_multiplier` length. the most significant limb of the modulus cannot be zero. +# * mod_inv - pow(-mod, -1, 2**SYSTEM_WORD_SIZE_BITS) +# requires: +# * x < mod and y < mod +# * mod_int % 2 != 0 +# * mod[0] != 0 +# returns: +# (x * y * pow(2**(SYSTEM_WORD_SIZE_BITS * val_size_multiplier), -1, mod)) % mod represented as a bigint +# note: references to x_int/y_int/mod_int/t_int refer to the python int representation of the corresponding bigint variable +def mulmont_quadratic(x: [int], y: [int], mod: [int], modinv: int) -> [int]: + assert len(x) == len(y) and len(y) == len(mod), "{}, {}, {}".format(x, y, mod) + assert mod[0] != 0, "modulus must occupy all words" + + word_count = len(mod) + + t = [0] * (word_count + 2) + + for i in reversed(range(word_count)): + # first inner-loop: t <- t + x_int * y[i] + c = 0 + for j in reversed(range(word_count)): + c, t[j + 2] = hi_lo(t[j + 2] + x[j] * y[i] + c) + + t[0], t[1] = hi_lo(t[1] + c) + + m = (modinv * t[-1]) % BASE + c, _ = hi_lo(m * mod[-1] + t[-1]) + + # second inner-loop: + # 1. t_int <- t_int + modinv * mod_int * t[-1] + # 2. t_int <- t_int // (2**SYSTEM_WORD_SIZE) + # note: + # after step 1: + # * modinv * mod_int * t[-1] === -1 % (2**SYSTEM_WORD_SIZE_BITS) + # * t_int === (t_int + (-1) t_int) % (2**SYSTEM_WORD_SIZE_BITS) === 0 % (2**SYSTEM_WORD_SIZE_BITS) + # so the shift in step 2 is a word-sized right shift. + # Steps 1 and 2 are combined and the shift is implicit. + for j in reversed(range(1, word_count)): + c, t[j + 2] = hi_lo(t[j + 1] + mod[j - 1] * m + c) + + hi, t[2] = hi_lo(t[1] + c) + t[1] = t[0] + hi + + # t_int = (t_int + t_int * mod_int * pow(-(2**(SYSTEM_WORD_SIZE_BITS*len(mod))), -1, mod_int)) // (2 ** (len(mod) * SYSTEM_WORD_SIZE_BITS)) + # 0 < t_int < 2 * mod_int + t = t[1:] + if t[0] != 0: + # result occupies len(mod) + 1 words so it must be greater than modulus + return bigint_sub(t, [0] + mod)[1:] + elif bigint_gte(t[1:], mod): + return bigint_sub(t[1:], mod) + else: + return t[1:] + +# subquadratic mulmont: same general algorithm as mulmont_quadratic with the assumption +# that any multiplications will be performed using Karatsuba subquadratic multiplication algorithm +# input: +# x, y, mod (int) - x < mod and y < mod +# mod (int) - an odd modulus +# R (int) - a power of two, and greater than mod +# mod_inv (int) - pow(-mod, -1, R) +# output: +# (x * y * pow(R, -1, mod)) % mod +# +def mulmont_subquadratic(x: int, y: int, mod: int, mod_inv_full: int, R: int) -> int: + T = x * y + m = ((T % R) * mod_inv_full) % R + T = T + m * mod + T /= R + if T >= mod: + T -= mod + return T + +def mulmont(mod_state: ModState, x: int, y: int) -> int: + if mod_state.val_size_multiplier >= MULMODX_SUBQUADRATIC_START: + return mulmont_subquadratic(x, y, mod_state.mod, mod_state.mod_inv) + else: + x_bigint = int_to_bigint(x, (mod_state.val_size_multiplier * 64) // SYSTEM_WORD_SIZE_BITS) + y_bigint = int_to_bigint(y, (mod_state.val_size_multiplier * 64) // SYSTEM_WORD_SIZE_BITS) + mod_bigint = int_to_bigint(mod_state.mod) + return bigint_to_int(mulmont_quadratic(x_bigint, y_bigint, mod_bigint, mod_state.mod_inv_full, mod_state.r)) +``` + +### New Opcodes + +| Mneumonic | Opcode | Immediate size (bytes) | Stack in | Stack out | +| ----- | ----- | ----- | ----- | ---- | +| SETUPX | 0x21 | 0 | 4 | 0 | +| ADDMODX | 0x22 | 3 | 0 | 0 | +| SUBMODX | 0x23 | 3 | 0 | 0 | +| MULMODX | 0x24 | 3 | 0 | 0 | +| LOADX | 0x25 | 0 | 3 | 0 | +| STOREX | 0x26 | 0 | 3 | 0 | + +#### SETUPX + +`SETUPX : mod_id, mod_offset, mod_size, vals_used` + +##### Gas Charging + +``` +mod_id = evm.stack.peek(0) +mod_offset = evm_stack.peek(1) +mod_size = evm_stack.peek(2) +vals_used = evm_stack.peek(3) + +cost = SETUPX_BASE_GAS + +if mod_id in evmmax_state.mods: + # the modulus state keyed by mod_id was already active in this call-frame. + # no additional charge beyond SETUPX_BASE_GAS + return + +if vals_used > 256: + raise Exception("cannot use more than 256 values for a given mod_id") + +if mod_offset + mod_size > len(evm_memory): + raise Exception("cannot load a modulus that would extend beyond the bounds of EVM memory") + +val_size_multiplier = math.ceil(mod_size / 8) + +cost += cost_precompute_mont(val_size_multiplier) +cost += cost_evm_memory_expansion(math.ceil((num_vals_used * val_size_multiplier * 8) / 32)) +``` + +##### Execution + +``` +mod_id = stack.pop() +mod_offset = stack.pop() +mod_size = stack.pop() +vals_used = stack.pop() + +mod_inv = None + +if mod_id in evmmax_state.mods[mod_id]: + # this mod state was previously used in this call frame. + # the associated montgomery parameters and memory space are already allocated. + # mark mod_id as the current active modulus state + evmmax_state.active_mod_state = evmmax_state.mods[mod_id] + return + +val_size_multiplier = math.ceil(mod_size / 8) + +mod = int.from_bytes(evm_memory[mod_offset:mod_offset+val_size], byteorder='big') +if mod == 0 or mod % 2 == 0: + raise Exception("modulus must be nonzero and odd") + +if val_size_multiplier >= MULMODX_SUBQUADRATIC_START: + mod_inv_full = pow(-r, -1, mod) +else: + mod_inv = pow(-mod, -1, 2**SYSTEM_WORD_SIZE_BITS) + +r = 2**(SYSTEM_WORD_SIZE_BITS * val_size_multiplier) +r_squared = r**2 % mod + +mod_state = ModState(mod, val_size, r, r_squared, mod_inv_full=mod_inv_full, mod_inv=mod_inv) + +evmmax_state.mods[mod_id] = mod_state +evmmax_state.active_mod_state = mod_state +``` + +#### LOADX + +`LOADX: dst_offset, val_idx, num_vals` + +##### Description + +Load EVMMAX values in the current active modulus state to EVM memory. + +##### Gas Charging + +``` +cost = LOADX_BASE_GAS +dst_offset = evm_stack.peek(0) +val_idx = evm_stack.peek(1) +num_vals = evm_stack.peek(2) + +val_size_multiplier = evmmax_state.active_mod_state.val_size_multiplier +if dst_offset + num_vals * val_size_multiplier > len(evm_memory): + cost += cost_evm_mem_expansion(evm_memory, (dst_offset + num_vals * val_size_multiplier) - len(evm_memory)) + +cost += cost_mulmodx(val_size_multiplier) * mod_state.num_vals +``` + +##### Execution + +``` +dst_offset = evm_stack.pop() +val_idx = evm_stack.pop() +num_vals = evm_stack.pop() + +if num_vals == 0: + return + +mod_state = evmmax_state.active_mod_state +if mod_state == None: + raise Exception("no modulus set") + +if val_idx + num_vals > len(mod_state.vals): + raise Exception("attempt to load beyond allocated values") + +if dst_offset + num_vals * mod_state.val_size_multiplier > len(evm_memory): + expand_evm_memory(evm_memory, (dst_offset + num_vals * mod_state.val_size_multiplier * 8) - len(evm_memory)) + +cur_dst_offset = dst_offset +for i in range(num_vals): + mont_val = mod_state.vals[start_val + i] + + # convert the value to canonical form + val = mulmont(mod_state, mont_val, 1) + + evm_memory[cur_dst_offset:cur_dst_offset + mod_state.val_size_multiplier] = val.to_bytes(mod_state.val_size_multiplier * 8, byteorder='big') + cur_dst_offset += mod_state.val_size_multiplier * 8 +``` + +#### STOREX + +`STOREX: dst_val, offset, num_vals` + +##### Description + +Store values from EVM memory into EVMMAX memory space of the current active modulus state, validating that they are reduced by the modulus. + +##### Gas Charging + +``` +dst_val = evm_stack.peek(0) +offset = evm_stack.peek(1) +num_vals = evm_stack.peek(2) + +val_size_multiplier = evmmax_state.active_mod_state.val_size_multiplier +cost = STOREX_BASE_COST + num_vals * cost_mulmodx(val_size_multiplier) +``` + +##### Execution + +``` +dst_val = evm_stack.pop() +offset = evm_stack.pop() +num_vals = evm_stack.pop() + +if num_vals == 0: + return + +mod_state = evmmax_state.active_mod_state +if mod_state == None: + raise Exception("no modulus set") + +if dst_val + num_vals > len(mod_state.vals): + raise Exception("attempt to copy to destination beyond allocated values") + +if offset + num_vals * mod_state.val_size_multiplier * 8 > len(evm_memory): + raise Exception("source of copy would extend beyond allocated memory") + +cur_src_offset = offset +r = 2** (mod_state.val_size_multiplier * SYSTEM_WORD_SIZE_BITS) % mod_state.mod +r_squared = r ** 2 % mod_state.mod + +for i in range(num_vals): + val = int.from_bytes(evm_memory[cur_src_offset:cur_src_offset + mod_state.val_size_multiplier * 8], byteorder='big') + + if val >= mod_state.modulus: + raise Exception("values cannot be greater than the modulus") + + # convert the value to Montgomery form + mont_val = mulmont(mod_state, val, mod_state.r_squared) + + mod_state.vals[dst_val + i] = mont_val + cur_offset += mod_state.val_size_multiplier * 8 +``` + +#### ADDMODX + +`ADDMODX {z_offset - byte}, {x_offset - byte}, {y_offset - byte}:` + +##### Description + +Compute the modular addition of two EVMMAX values, storing the result in an output. + +##### Gas Charging + +``` +val_size_multiplier = evmmax_state.active_mod_state.val_size_multiplier +cost = cost_addmodx(val_size_multiplier) +``` + +##### Execution + +``` +mod_state = evmmax_state.active_modulus +if mod_state == None: + raise Exception("no mod state set") + +z_offset = int(contract_code[pc+1:pc+2]) +x_offset = int(contract_code[pc+2:pc+3]) +y_offset = int(contract_code[pc+3:pc+4]) + +if x_offset >= mod_state.num_vals_used or y_offset >= mod_state.num_vals_used or z_offset >= mod_state.num_vals_used: + raise Exception("out of bounds value reference") + +mod_state.values[z_offset] = (mod_state.values[x_offset] + mod_state.values[y_offset]) % mod_state.mod +``` + +#### SUBMODX + +`SUBMODX {z_offset - byte}, {x_offset - byte}, {y_offset - byte}:` + +##### Description + +Compute the modular subtraction of two EVMMAX values in the current active modulus state, storing the result in an output. + +##### Gas Charging + +Same as `ADDMODX`. + +##### Execution + +``` +mod_state = evmmax_state.active_modulus +if mod_state == None: + raise Exception("no mod state set") + +z_offset = int(contract_code[pc+1:pc+2]) +x_offset = int(contract_code[pc+2:pc+3]) +y_offset = int(contract_code[pc+3:pc+4]) + +if x_offset >= mod_state.num_vals_used or y_offset >= mod_state.num_vals_used or z_offset >= mod_state.num_vals_used: + raise Exception("out of bounds value reference") + +mod_state.values[z_offset] = (mod_state.values[x_offset] - mod_state.values[y_offset]) % mod_state.mod +``` + +#### `MULMODX` + +`MULMODX {z_offset - byte}, {x_offset - byte}, {y_offset - byte}:` + +##### Description + +Compute the Montgomery modular multiplication of two EVMMAX values in the current active modulus state, storing the result in an output. + +##### Gas Charging + +``` +val_size_multiplier = evmmax_state.active_mod_state.val_size_multiplier +cost = cost_mulmodx(val_size_multiplier) +``` + +##### Execution + +``` +mod_state = evmmax_state.active_modulus +if mod_state == None: + raise Exception("no mod state set") + +z_offset = int(contract_code[pc+1:pc+2]) +x_offset = int(contract_code[pc+2:pc+3]) +y_offset = int(contract_code[pc+3:pc+4]) + +if x_offset >= mod_state.num_vals_used or y_offset >= mod_state.num_vals_used or z_offset >= mod_state.num_vals_used: + raise Exception("out of bounds value reference") + +mod_state.values[z_offset] = mulmont(mod_state, mod_state.values[x_offset], mod_state.values[y_offset]) +``` + +### Changes to Contract Execution + +#### EVM Memory Expansion Cost Function + +Any EVM operation which expands memory `x` bytes will charge to expand memory to `cur_evm_mem_size + x + evmmax_mem_size` bytes where `evmmax_mem_size` is the size of all allocated EVMMAX values in the current call context (the sum of the values used by each `mod_id` that has been previously/currently set with `SETUPX`). + +#### Jumpdest Analysis + +Jumpdest analysis is modified to disallow jumps into immediate data for `ADDMDOX`/`SUBMODX`/`MULMODX`. + +## Rationale + +### Montgomery Modular Multiplication + +EVMMAX values are stored internally in Montgomery form. Expressing values in Montgomery form enables the use of Montgomery reduction in modular multiplication which gives a substantial performance gain versus naive modular multiplication. + +Modular addition and subtraction on Montgomery form values is computed the same as normal. + +### Memory Alignment for EVMMAX Values + +`LOADX`/`STOREX` move 64bit-aligned big-endian values to/from the memory space of the active modulus state. `SETUPX` memory expansion pricing is tuned to assume that values will be stored in a as 64bit-aligned values in their EVMMAX memory space. + +This choice is made to keep EVMMAX memory aligned to ensure performance. + +### Gas Costs + +Gas models assume a rate of 1 gas per 25ns of execution time. + +#### ADDMODX/SUBMODX/MULMODX + +`ADDMODX` and `SUBMODX` can each be implemented using a single extended-precision addition, and single extended precision subtraction. This justifies a linear cost model. + +`MULMODX` runtime scales quadratically with input size. After a certain threshold, the quadratic complexity of `mulmont_quadratic` dominates and it becomes more performant to use `mulmont_subquadratic`. Thus, there is a segmented cost model to reflect different asymptotic behavior between quadratic/subquadratic `mulmont`. + +`ADDMODX`/`SUBMODX`/`MULMODX` pricing includes the cost of arithmetic and latency of accessing input values from CPU cache. + +The price model assumes that the implementation will be generic for most bitwidths with the exception of 321-384bits which is priced aggressively. + +#### LOADX/STOREX + +These perform conversion to/from Montgomery and canonical forms for each value copied (a single `mulmont` per value converted). The overhead of memory loading/copying is covered by `cost_mulmontx`. + +#### SETUPX + + + +## Backwards Compatibility + +Jumpdest analysis changes in this EIP could potentially break existing contracts where a jump destination occurs in the 3 bytes proceeding a `0x22`/`0x23`/`0x24`. This is unlikely to affect many existing contracts. Further analysis of deployed contract bytecode can determine with certainty, which (if any) contracts could be broken. + +## Security Considerations + + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-67.md b/EIPS/eip-67.md index 3bea904a084028..d974f342e07314 100644 --- a/EIPS/eip-67.md +++ b/EIPS/eip-67.md @@ -1,80 +1,7 @@ --- eip: 67 -title: URI Scheme with Metadata, Value and Bytecode -description: Format for encoding transactions into a URI -author: Alex Van de Sande (@alexvansande) -discussions-to: https://github.com/ethereum/EIPs/issues/67 -status: Withdrawn -type: Standards Track category: ERC -created: 2016-02-17 -withdrawal-reason: Superseded by EIP-681 +status: Moved --- -## Abstract - -This proposal (inspired by BIP 21) defines a format for encoding a transaction into a URI, including a recipient, number of ethers (possibly zero), and optional bytecode. - -## Motivation - -Imagine these scenarios: - - * An exchange or a instant converter like ShapeShift wants to create a single Ethereum address for payments that will be converted into credit in their internal system or output bitcoin to an address. - * A store wants to show a QR code to a client that will pop up a payment for exactly 12.34 ethers, which contains metadata on the product being bought. - * A betting site wants to provide a link that the user can click on his site and it will open a default Ethereum wallet and execute a specific contract with given parameters. - * A dapp in Mist wants to simply ask the user to sign a transaction with a specific ABI in a single call. - - -In all these scenarios, the provider wants to internally set up a transaction, with a recipient, an associated number of ethers (or none) and optional bytecode, all without requiring any fuss from the end user that is expected simply to choose a sender and authorise the transaction. - -Currently implementations for this are wonky: ShapeShift creates tons of temporary addresses and uses an internal system to check which one correspond to which metadata, there isn't any standard way for stores that want payment in ether to put specific metadata about price on the call and any app implementing contracts will have to use different solutions depending on the client they are targeting. - -The proposal goes beyond address, and also includes optional bytecode and value. Of course this would make the link longer, but it should not be something visible to the user. Instead it should be shown as a visual code (QR or otherwise), a link, or some other way to pass the information. - -If properly implemented in all wallets, this should make execution of contracts directly from wallets much simpler as the wallet client only needs to put the bytecode obtained by reading the QR code. - -## Specification - -If we follow the bitcoin standard, the result would be: - -``` - ethereum:
[?value=][?gas=][?data=] -``` - -Other data could be added, but ideally the client should take them from elsewhere in the blockchain, so instead of having a `label` or a `message` to be displayed to the users, these should be read from an identity system or metadata on the transaction itself. - -### Example 1 - -Clicking this link would open a transaction that would try to send _5 unicorns_ to address _deadbeef_. The user would then simply approve, based on each wallet UI. - -``` - ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7?gas=100000&data=0xa9059cbb00000000000000000000000000000000000000000000000000000000deadbeef0000000000000000000000000000000000000000000000000000000000000005 -``` - -#### Without Bytecode - -Alternatively, the bytecode could be generated by the client and the request would be in plain text: - -``` - ethereum:
[?value=][?gas=][?function=nameOfFunction(param)] -``` - -### Example 2 - -This is the same function as above, to send 5 unicorns from he sender to _deadbeef_, but now with a more readable function, which the client converts to bytecode. - -``` - ethereum:0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7?gas=100000&function=transfer(address 0xdeadbeef, uint 5) -``` - -## Rationale - -TODO - -## Security Considerations - -TODO - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-67.md diff --git a/EIPS/eip-6734.md b/EIPS/eip-6734.md new file mode 100644 index 00000000000000..bc89b4e00921ba --- /dev/null +++ b/EIPS/eip-6734.md @@ -0,0 +1,7 @@ +--- +eip: 6734 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6734.md diff --git a/EIPS/eip-6735.md b/EIPS/eip-6735.md new file mode 100644 index 00000000000000..88aba2e2c5d5b6 --- /dev/null +++ b/EIPS/eip-6735.md @@ -0,0 +1,7 @@ +--- +eip: 6735 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6735.md diff --git a/EIPS/eip-6780.md b/EIPS/eip-6780.md new file mode 100644 index 00000000000000..1b6a0e94cc47e8 --- /dev/null +++ b/EIPS/eip-6780.md @@ -0,0 +1,80 @@ +--- +eip: 6780 +title: SELFDESTRUCT only in same transaction +description: SELFDESTRUCT will recover all funds to the target but not delete the account, except when called in the same transaction as creation +author: Guillaume Ballet (@gballet), Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad) +discussions-to: https://ethereum-magicians.org/t/deactivate-selfdestruct-except-where-it-occurs-in-the-same-transaction-in-which-a-contract-was-created/13539 +status: Final +type: Standards Track +category: Core +created: 2023-03-25 +requires: 2681, 2929, 3529 +--- + +## Abstract + +This EIP changes the functionality of the `SELFDESTRUCT` opcode. The new functionality will be only to send all Ether in the account to the target, except that the current behaviour is preserved when `SELFDESTRUCT` is called in the same transaction a contract was created. + +## Motivation + +The `SELFDESTRUCT` opcode requires large changes to the state of an account, in particular removing all code and storage. This will not be possible in the future with Verkle trees: Each account will be stored in many different account keys, which will not be obviously connected to the root account. + +This EIP implements this change. Applications that only use `SELFDESTRUCT` to retrieve funds will still work. Applications that only use `SELFDESTRUCT` in the same transaction as they created a contract will also continue to work without any changes. + +## Specification + +The behaviour of `SELFDESTRUCT` is changed in the following way: + +1. When `SELFDESTRUCT` is executed in a transaction that is not the same as the contract calling `SELFDESTRUCT` was created: + + - The current execution frame halts. + - `SELFDESTRUCT` does not delete any data (including storage keys, code, or the account itself). + - `SELFDESTRUCT` transfers the entire account balance to the target. + - Note that if the target is the same as the contract calling `SELFDESTRUCT` there is no net change in balances. Unlike the prior specification, Ether will not be burnt in this case. + - Note that no refund is given since [EIP-3529](./eip-3529.md). + - Note that the rules of [EIP-2929](./eip-2929.md) regarding `SELFDESTRUCT` remain unchanged. + +2. When `SELFDESTRUCT` is executed in the same transaction as the contract was created: + + - `SELFDESTRUCT` continues to behave as it did prior to this EIP, this includes the following actions + - The current execution frame halts. + - `SELFDESTRUCT` deletes data as previously specified. + - `SELFDESTRUCT` transfers the entire account balance to the target + - The account balance of the contact calling `SELFDESTRUCT` is set to `0`. + - Note that if the target is the same as the contract calling `SELFDESTRUCT` that Ether will be burnt. + - Note that no refund is given since [EIP-3529](./eip-3529.md). + - Note that the rules of [EIP-2929](./eip-2929.md) regarding `SELFDESTRUCT` remain unchanged. + +A contract is considered created at the beginning of a create transaction or when a CREATE series operation begins execution (CREATE, CREATE2, and other operations that deploy contracts in the future). If a balance exists at the contract's new address it is still considered to be a contract creation. + +The `SELFDESTRUCT` opcode remains deprecated as specified in [EIP-6049](./eip-6049.md). Any use in newly deployed contracts is strongly discouraged even if this new behaviour is taken into account, and future changes to the EVM might further reduce the functionality of the opcode. + +## Rationale + +Getting rid of the `SELFDESTRUCT` opcode has been considered in the past, and there are currently no strong reasons to use it. This EIP implements a behavior that will attempt to leave some common uses of `SELFDESTRUCT` working, while reducing the complexity of the change on EVM implementations that would come from contract versioning. + +Handling the account creation and contract creation as two distinct and possibly separate events is needed for use cases such as counterfactual accounts. By allowing the `SELFDESTRUCT` to delete the account at contract creation time it will not result in stubs of counterfactually instantiated contracts that never had any on-chain state other than a balance prior to the contract creation. These accounts would never have any storage and thus the trie updates to delete the account would be limited to the account node, which is the same impact a regular transfer of ether would have. + +## Backwards Compatibility + +This EIP requires a hard fork, since it modifies consensus rules. + +Contracts that depended on re-deploying contracts at the same address using `CREATE2` (after a `SELFDESTRUCT`) will no longer function properly if the created contract does not call `SELFDESTRUCT` within the same transaction. + +Previously it was possible to burn ether by calling `SELFDESTRUCT` targeting the executing contract as the beneficiary. If the contract existed prior to the transaction the ether will not be burned. If the contract was newly created in the transaction the ether will be burned, as before. + +## Test Cases + +Test cases for this EIP can be found in the Execution Spec Tests suite [`eip6780_selfdestruct`](https://github.com/ethereum/execution-spec-tests/tree/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip6780_selfdestruct). + +## Security Considerations + +The following applications of `SELFDESTRUCT` will be broken and applications that use it in this way are not safe anymore: + +1. Where `CREATE2` is used to redeploy a contract in the same place in order to make a contract upgradable. This is not supported anymore and [ERC-2535](./eip-2535.md) or other types of proxy contracts should be used instead. + +2. Where a contract depended on burning Ether via a `SELFDESTRUCT` with the contract as beneficiary, in a contract not created within the same transaction. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6785.md b/EIPS/eip-6785.md new file mode 100644 index 00000000000000..36359e27d95e5e --- /dev/null +++ b/EIPS/eip-6785.md @@ -0,0 +1,7 @@ +--- +eip: 6785 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6785.md diff --git a/EIPS/eip-6786.md b/EIPS/eip-6786.md new file mode 100644 index 00000000000000..fa946ddf382c09 --- /dev/null +++ b/EIPS/eip-6786.md @@ -0,0 +1,7 @@ +--- +eip: 6786 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6786.md diff --git a/EIPS/eip-6787.md b/EIPS/eip-6787.md new file mode 100644 index 00000000000000..7d52ec769b8046 --- /dev/null +++ b/EIPS/eip-6787.md @@ -0,0 +1,7 @@ +--- +eip: 6787 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6787.md diff --git a/EIPS/eip-6789.md b/EIPS/eip-6789.md new file mode 100644 index 00000000000000..06df1676f6913a --- /dev/null +++ b/EIPS/eip-6789.md @@ -0,0 +1,113 @@ +--- +eip: 6789 +title: Rename gas to mana +description: This EIP suggests renaming gas to mana, as proposed by Vitalik Buterin in 2015 +author: Pascal Caversaccio (@pcaversaccio) +discussions-to: https://ethereum-magicians.org/t/eip-6789-rename-gas-to-mana/13570 +status: Stagnant +type: Standards Track +category: Interface +created: 2023-03-27 +--- + +## Abstract + +This EIP suggests renaming `gas` to `mana`, as proposed by Vitalik Buterin in 2015. + +## Motivation + +The underlying motivation for reviving Vitalik's original proposal from 2015 is that we have finally arrived at the age of Proof-of-Stake, and given the roadmap ahead (i.e. "The Surge", "The Scourge", "The Verge", "The Purge", and "The Splurge"), I consider this moment as the last opportunity to make such a far-reaching semantic change. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +The core term `gas` MUST be renamed to `mana`. + +The following opcodes MUST be renamed: + +- `GASPRICE` to `MANAPRICE`; +- `GASLIMIT` to `MANALIMIT`; and +- `GAS` to `MANA`. + +Additionally, the input parameters or outputs of the following opcodes MUST be renamed: + +- `CALL`'s `gas` input parameter to `mana`; +- `CALLCODE`'s `gas` input parameter to `mana`; +- `DELEGATECALL`'s `gas` input parameter to `mana`; +- `STATICCALL`'s `gas` input parameter to `mana`; +- `GASLIMIT`'s `gasLimit` output to `manaLimit`; and +- `GAS`'s `gas` output to `mana`. + +Finally, the following RPC endpoints MUST be renamed: + +- `eth_estimateGas` to `eth_estimateMana`; +- `eth_gasPrice` to `eth_manaPrice`; and +- `eth_maxPriorityFeePerGas` to `eth_maxPriorityFeePerMana`. + +The description of the RPC endpoints MUST be renamed accordingly: + +- `eth_estimateMana`: Generates and returns an estimate of how much `mana` is necessary to allow the transaction to complete; +- `eth_manaPrice`: Returns the current price per `mana` in wei; and +- `eth_maxPriorityFeePerMana`: Returns the current `maxPriorityFeePerMana` per `mana` in wei. + +## Rationale + +- `mana` reflects the increased environmental friendliness of Proof-of-Stake; +- `mana` is generally understood to be ephemeral and non-transferable, which better represents the concept of `gas`; and +- `mana` is generally portrayed as renewable, while (natural) `gas` is non-renewable. + +## Backwards Compatibility + +This proposal is not backward compatible as it renames the core term `gas`. + +## Test Cases + +### Example 1 + +If a transaction requires more `mana` than allowed by the `manaLimit`, it is reverted as an _out-of-mana_ transaction. + +### Example 2 + +A Solidity contract to estimate the used `mana` via the new `manaleft()` syntax (replacing `gasleft()`) for dedicated function calls. + +```solidity +// SPDX-License-Identifier: AGPL-3.0 +pragma solidity 0.8.19; + +contract ManaMetering { + function oldWay() external view returns (string memory, uint256 manaUsed) { + string memory hiMom = "Hi Mom, "; + string memory missYou = "miss you."; + uint256 startMana = manaleft(); + string memory concat = string(abi.encodePacked(hiMom, missYou)); + manaUsed = startMana - manaleft(); + return (concat, manaUsed); + } + + function newWay() external view returns (string memory, uint256 manaUsed) { + string memory hiMom = "Hi Mom, "; + string memory missYou = "miss you."; + uint256 startMana = manaleft(); + string memory concat = string.concat(hiMom, missYou); + manaUsed = startMana - manaleft(); + return (concat, manaUsed); + } +} +``` + +In Vyper, the same behaviour can be replicated with the new transaction property `msg.mana`, which replaces `msg.gas`. + +### Example 3 + +An example of how to set the `manaLimit` in MetaMask: + +![MetaMask manaLimit](../assets/eip-6789/MetaMask_ManaLimit.png) + +## Security Considerations + +There are no security considerations directly related to the renaming of `gas` to `mana`. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6800.md b/EIPS/eip-6800.md new file mode 100644 index 00000000000000..d7c587c9996092 --- /dev/null +++ b/EIPS/eip-6800.md @@ -0,0 +1,304 @@ +--- +eip: 6800 +title: Ethereum state using a unified verkle tree +description: This introduces a new Verkle state tree alongside the existing MPT. +author: Vitalik Buterin (@vbuterin), Dankrad Feist (@dankrad), Kevaundray Wedderburn (@kevaundray), Guillaume Ballet (@gballet), Piper Merriam (@pipermerriam), Gottfried Herold (@GottfriedHerold) +discussions-to: https://ethereum-magicians.org/t/proposed-verkle-tree-scheme-for-ethereum-state/5805 +status: Draft +type: Standards Track +category: Core +created: 2023-03-17 +requires: 6780 +--- + +## Abstract + +Introduce a new Verkle state tree alongside the existing hexary Patricia tree. After the hard fork, the Verkle tree stores all edits to state and a copy of all accessed state, and the hexary Patricia tree can no longer be modified. This is a first step in a multi-phase transition to Ethereum exclusively relying on Verkle trees to store execution state. + +## Motivation + +Verkle trees solve a key problem standing in the way of Ethereum being stateless-client-friendly: witness sizes. A witness accessing an account in today’s hexary Patricia tree is, in the average case, close to 3 kB, and in the worst case it may be three times larger. Assuming a worst case of 6000 accesses per block (15m gas / 2500 gas per access), this corresponds to a witness size of ~18 MB, which is too large to safely broadcast through a p2p network within a 12-second slot. Verkle trees reduce witness sizes to ~200 bytes per account in the average case, allowing stateless client witnesses to be acceptably small. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Verkle tree definition + +We define a Verkle tree here by providing the function to compute the root commitment given a set of 32-byte keys and 32-byte values. Algorithms for updating and inserting values are up to the implementer; the only requirement is that the root commitment after the update must continue to match the value computed from this specification. We will then define an embedding that provides the 32-byte key at which any particular piece of state information (account headers, code, storage) should be stored. + +``` +# Bandersnatch curve order +BANDERSNATCH_MODULUS = \ +13108968793781547619861935127046491459309155893440570251786403306729687672801 +# Bandersnatch Pedersen basis of length 256 +PEDERSEN_BASIS = [....] +VERKLE_NODE_WIDTH = len(PEDERSEN_BASIS) + +def group_to_scalar_field(point: Point) -> int: + # Not collision resistant. Not random oracle. + # Binding for Pedersen commitments. + assert isinstance(point, Point) + if point == bandersnatch.Z: + return 0 + else: + return point.map_to_base_field() % BANDERSNATCH_MODULUS + +def compute_commitment_root(children: Sequence[int]) -> Point: + o = bandersnatch.Z + for generator, child in zip(PEDERSEN_BASIS, children): + o = bandersnatch.add(o, bandersnatch.mul(generator, child)) + return o + +def extension_and_suffix_tree(stem: bytes31, values: Dict[byte, bytes32]) -> int: + sub_leaves = [0] * 512 + for suffix, value in values.items(): + sub_leaves[2 * suffix] = int.from_bytes(value[:16], 'little') + 2**128 + sub_leaves[2 * suffix + 1] = int.from_bytes(value[16:], 'little') + C1 = compute_commitment_root(sub_leaves[:256]) + C2 = compute_commitment_root(sub_leaves[256:]) + return compute_commitment_root([1, # Extension marker + int.from_bytes(stem, "little"), + group_to_scalar_field(C1), + group_to_scalar_field(C2)] + + [0] * 252) + +def compute_main_tree_root(data: Dict[bytes32, int], + prefix: bytes) -> int: + # Empty subtree: 0 + if len(data) == 0: + return 0 + elif len(data) == 1: + return list(data.values())[0] + else: + sub_commitments = [ + compute_main_tree_root({ + key: value for key, value in data.items() if + key[:len(prefix) + 1] == prefix + bytes([i]) + }, prefix + bytes([i])) + for i in range(VERKLE_NODE_WIDTH) + ] + return group_to_scalar_field(compute_commitment_root(sub_commitments)) + +def compute_verkle_root(data: Dict[bytes32, bytes32]) -> Point: + stems = set(key[:-1] for key in data.keys()) + data_as_stems = {} + for stem in stems: + commitment_data = Dict[byte, bytes32]() + for i in range(VERKLE_NODE_WIDTH): + if stem + bytes([i]) in data: + commitment_data[i] = data[stem + bytes([i])] + data_as_stems[stem] = extension_and_suffix_tree(stem, commitment_data) + sub_commitments = [ + compute_main_tree_root({ + key: value for key, value in data.items() if + key[0] == i + }, bytes([i])) + for i in range(VERKLE_NODE_WIDTH) + ] + return compute_commitment_root(sub_commitments) +``` + +Note that a value of zero is not the same thing as a position being empty; a position being empty is represented as 0 in the bottom layer commitment, but a position being zero is represented by a different value in the suffix tree commitment (2**128 is added to value_lower to distinguish it from empty). This distinction between zero and empty is not a property of the existing Patricia tree, but it is a property of the proposed Verkle tree. + +In the rest of this document, saving or reading a number at some position in the Verkle tree will mean saving or reading the 32-byte little-endian encoding of that number. + +### Illustration + +This is an illustration of the tree structure. + +![tree structure](../assets/eip-6800/tree_structure.png) + +### Tree embedding + +Instead of a two-layer structure as in the Patricia tree, in the Verkle tree we will embed all information into a single `key: value` tree. This section specifies which tree keys store the information (account header data, code, storage) in the state. + +| Parameter | Value | +| --------------------- | ------- | +| VERSION_LEAF_KEY | 0 | +| BALANCE_LEAF_KEY | 1 | +| NONCE_LEAF_KEY | 2 | +| CODE_KECCAK_LEAF_KEY | 3 | +| CODE_SIZE_LEAF_KEY | 4 | +| HEADER_STORAGE_OFFSET | 64 | +| CODE_OFFSET | 128 | +| VERKLE_NODE_WIDTH | 256 | +| MAIN_STORAGE_OFFSET | 256**31 | + +_It’s a required invariant that `VERKLE_NODE_WIDTH > CODE_OFFSET > HEADER_STORAGE_OFFSET` and that `HEADER_STORAGE_OFFSET` is greater than the leaf keys. Additionally, `MAIN_STORAGE_OFFSET` must be a power of `VERKLE_NODE_WIDTH`._ + +Note that addresses are always passed around as an `Address32`. To convert existing addresses to `Address32`, prepend with 12 zero bytes: + +``` +def old_style_address_to_address32(address: Address) -> Address32: + return b'\x00' * 12 + address +``` + +#### Header values + +These are the positions in the tree at which block header fields of an account are stored. + +``` +def hash_point_to_bytes(point: Point) -> int: + return group_to_scalar_field(point).to_bytes(32, 'little') + +def pedersen_hash(inp: bytes) -> bytes32: + assert len(inp) <= 255 * 16 + # Interpret input as list of 128 bit (16 byte) integers + ext_input = inp + b"\0" * (255 * 16 - len(inp)) + ints = [2 + 256 * len(inp)] + \ + [int.from_bytes(ext_input[16 * i:16 * (i + 1)], 'little') for i in range(255)] + return compute_commitment_root(ints).hash_point_to_bytes() + +def get_tree_key(address: Address32, tree_index: int, sub_index: int): + # Assumes VERKLE_NODE_WIDTH = 256 + return ( + pedersen_hash(address + tree_index.to_bytes(32, 'little'))[:31] + + bytes([sub_index]) + ) + +def get_tree_key_for_version(address: Address32): + return get_tree_key(address, 0, VERSION_LEAF_KEY) + +def get_tree_key_for_balance(address: Address32): + return get_tree_key(address, 0, BALANCE_LEAF_KEY) + +def get_tree_key_for_nonce(address: Address32): + return get_tree_key(address, 0, NONCE_LEAF_KEY) + +# Backwards compatibility for EXTCODEHASH +def get_tree_key_for_code_keccak(address: Address32): + return get_tree_key(address, 0, CODE_KECCAK_LEAF_KEY) + +# Backwards compatibility for EXTCODESIZE +def get_tree_key_for_code_size(address: Address32): + return get_tree_key(address, 0, CODE_SIZE_LEAF_KEY) +``` + +When any account header field is set, the `version` is also set to zero. The `code_keccak` and `code_size` fields are set upon contract creation. + +#### Code + +``` +def get_tree_key_for_code_chunk(address: Address32, chunk_id: int): + return get_tree_key( + address, + (CODE_OFFSET + chunk_id) // VERKLE_NODE_WIDTH, + (CODE_OFFSET + chunk_id) % VERKLE_NODE_WIDTH + ) +``` + +Chunk `i` stores a 32 byte value, where bytes 1…31 are bytes `i*31...(i+1)*31 - 1` of the code (ie. the i’th 31-byte slice of it), and byte 0 is the number of leading bytes that are part of PUSHDATA (eg. if part of the code is `...PUSH4 99 98 | 97 96 PUSH1 128 MSTORE...` where `|` is the position where a new chunk begins, then the encoding of the latter chunk would begin `2 97 96 PUSH1 128 MSTORE` to reflect that the first 2 bytes are PUSHDATA). + +For precision, here is an implementation of code chunkification: + +``` +PUSH_OFFSET = 95 +PUSH1 = PUSH_OFFSET + 1 +PUSH32 = PUSH_OFFSET + 32 + +def chunkify_code(code: bytes) -> Sequence[bytes32]: + # Pad to multiple of 31 bytes + if len(code) % 31 != 0: + code += b'\x00' * (31 - (len(code) % 31)) + # Figure out how much pushdata there is after+including each byte + bytes_to_exec_data = [0] * (len(code) + 32) + pos = 0 + while pos < len(code): + if PUSH1 <= code[pos] <= PUSH32: + pushdata_bytes = code[pos] - PUSH_OFFSET + else: + pushdata_bytes = 0 + pos += 1 + for x in range(pushdata_bytes): + bytes_to_exec_data[pos + x] = pushdata_bytes - x + pos += pushdata_bytes + # Output chunks + return [ + bytes([min(bytes_to_exec_data[pos], 31)]) + code[pos: pos+31] + for pos in range(0, len(code), 31) + ] +``` + +#### Storage + +``` +def get_tree_key_for_storage_slot(address: Address32, storage_key: int): + if storage_key < (CODE_OFFSET - HEADER_STORAGE_OFFSET): + pos = HEADER_STORAGE_OFFSET + storage_key + else: + pos = MAIN_STORAGE_OFFSET + storage_key + return get_tree_key( + address, + pos // VERKLE_NODE_WIDTH, + pos % VERKLE_NODE_WIDTH + ) +``` + +Note that storage slots in the same size `VERKLE_NODE_WIDTH` range (ie. a range the form `x*VERKLE_NODE_WIDTH ... (x+1)*VERKLE_NODE_WIDTH-1)` are all, with the exception of the `HEADER_STORAGE_OFFSET` special case, part of a single commitment. This is an optimization to make witnesses more efficient when related storage slots are accessed together. If desired, this optimization can be exposed to the gas schedule, making it more gas-efficient to make contracts that store related slots together (however, Solidity already stores in this way by default). + +#### Fork + +TODO - see specific EIP + +#### Access events + +Described in [EIP-4762](./eip-4762.md). + +## Rationale + +This implements all of the logic in transitioning to a Verkle tree, and at the same time reforms gas costs, but does so in a minimally disruptive way that does not require simultaneously changing the whole tree structure. Instead, we add a new Verkle tree that starts out empty, and only new changes to state and copies of accessed state are stored in the tree. The Patricia tree continues to exist, but is frozen. + +This sets the stage for a future hard fork that swaps the Patricia tree in-place with a Verkle tree storing the same data. Unlike [EIP-2584](./eip-2584.md), this replacement Verkle tree does not need to be computed by clients in real time. Instead, because the Patricia tree would at that point be fixed, the replacement Verkle tree can be computed off-chain. + +### Verkle tree design + + +The Verkle tree uses a single-layer tree structure with 32-byte keys and values for several reasons: + + * **Simplicity**: working with the abstraction of a key/value store makes it easier to write code dealing with the tree (eg. database reading/writing, caching, syncing, proof creation and verification) as well as to upgrade it to other trees in the future. Additionally, witness gas rules can become simpler and clearer. + * **Uniformity**: the state is uniformly spread out throughout the tree; even if a single contract has many millions of storage slots, the contract’s storage slots are not concentrated in one place. This is useful for state syncing algorithms. Additionally, it helps reduce the effectiveness of unbalanced tree filling attacks. + * **Extensibility**: account headers and code being in the same structure as storage makes it easier to extend the features of both, and even add new structures if later desired. + +The single-layer tree design does have a major weakness: the inability to deal with entire storage trees as a single object. This is why this EIP includes removing most of the functionality of SELFDESTRUCT. If absolutely desired, SELFDESTRUCT’s functionality could be kept by adding and incrementing an account_state_offset parameter that increments every time an account self-destructs, but this would increase complexity. + +### Gas reform + +Gas costs for reading storage and code are reformed to more closely reflect the gas costs under the new Verkle tree design. WITNESS_CHUNK_COST is set to charge 6.25 gas per byte for chunks, and WITNESS_BRANCH_COST is set to charge ~13,2 gas per byte for branches on average (assuming 144 byte branch length) and ~2.5 gas per byte in the worst case if an attacker fills the tree with keys deliberately computed to maximize proof length. + +The main differences from gas costs in Berlin are: + + * 200 gas charged per 31 byte chunk of code. This has been estimated to increase average gas usage by ~6-12% + * Cost for accessing adjacent storage slots (`key1 // 256 == key2 // 256`) decreases from 2100 to 200 for all slots after the first in the group, + * Cost for accessing storage slots 0…63 decreases from 2100 to 200, including the first storage slot. This is likely to significantly improve performance of many existing contracts, which use those storage slots for single persistent variables. + +Gains from the latter two properties have not yet been analyzed, but are likely to significantly offset the losses from the first property. It’s likely that once compilers adapt to these rules, efficiency will increase further. + +The precise specification of when access events take place, which makes up most of the complexity of the gas repricing, is necessary to clearly specify when data needs to be saved to the period 1 tree. + +## Backwards Compatibility + +The three main backwards-compatibility-breaking changes are: + + * `SELFDESTRUCT` neutering (see [EIP-6780](./eip-6780.md) for a document stating the case for doing this despite the backwards compatibility loss) + * Gas costs for code chunk access making some applications less economically viable + * Tree structure change makes in-EVM proofs of historical state no longer work + +(2) can be mitigated by increasing the gas limit at the same time as implementing this EIP, reducing the risk that applications will no longer work at all due to transaction gas usage rising above the block gas limit. (3) cannot be mitigated this time, but this proposal could be implemented to make this no longer a concern for any tree structure changes in the future. + +## Test Cases + +TODO + +## Reference Implementation + + * github.com/gballet/go-ethereum, branch beverly-hills-just-after-pbss - a geth implementation + * github.com/NethermindEth/nethermind, branch verkle/tree - a nethermind implementation + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6806.md b/EIPS/eip-6806.md new file mode 100644 index 00000000000000..bbf9647252aa29 --- /dev/null +++ b/EIPS/eip-6806.md @@ -0,0 +1,7 @@ +--- +eip: 6806 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6806.md diff --git a/EIPS/eip-6808.md b/EIPS/eip-6808.md new file mode 100644 index 00000000000000..f2d777c1440d3d --- /dev/null +++ b/EIPS/eip-6808.md @@ -0,0 +1,7 @@ +--- +eip: 6808 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6808.md diff --git a/EIPS/eip-6809.md b/EIPS/eip-6809.md new file mode 100644 index 00000000000000..e76d2c62fe2e10 --- /dev/null +++ b/EIPS/eip-6809.md @@ -0,0 +1,7 @@ +--- +eip: 6809 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6809.md diff --git a/EIPS/eip-681.md b/EIPS/eip-681.md index 772e9ca4bdbff9..307b7fae475fb9 100644 --- a/EIPS/eip-681.md +++ b/EIPS/eip-681.md @@ -1,92 +1,7 @@ --- eip: 681 -title: URL Format for Transaction Requests -author: Daniel A. Nagy (@nagydani) -type: Standards Track category: ERC -status: Final -discussions-to: https://ethereum-magicians.org/t/erc-681-representing-various-transactions-as-urls -created: 2017-08-01 -requires: 20, 137 +status: Moved --- -## Simple Summary -A standard way of representing various transactions, especially payment requests in ether and [ERC-20](./eip-20.md) tokens as URLs. - -## Abstract -URLs embedded in QR-codes, hyperlinks in web-pages, emails or chat messages provide for robust cross-application signaling between very loosely coupled applications. A standardized URL format for payment requests allows for instant invocation of the user's preferred wallet application (even if it is a webapp or a swarm đapp), with the correct parameterization of the payment transaction only to be confirmed by the (authenticated) user. - -## Motivation -The convenience of representing payment requests by standard URLs has been a major factor in the wide adoption of Bitcoin. Bringing a similarly convenient mechanism to Ethereum would speed up its acceptance as a payment platform among end-users. In particular, URLs embedded in broadcast Intents are the preferred way of launching applications on the Android operating system and work across practically all applications. Desktop web browsers have a standardized way of defining protocol handlers for URLs with specific protocol specifications. Other desktop applications typically launch the web browser upon encountering a URL. Thus, payment request URLs could be delivered through a very broad, ever growing selection of channels. - -This specification supersedes the defunct ERC-67, which is a URL format for representing arbitrary transactions in a low-level fashion. This ERC focuses specifically on the important special case of payment requests, while allowing for other, ABI-specified transactions. - -## Specification - -### Syntax -Payment request URLs contain "ethereum" in their schema (protocol) part and are constructed as follows: - - request = schema_prefix target_address [ "@" chain_id ] [ "/" function_name ] [ "?" parameters ] - schema_prefix = "ethereum" ":" [ "pay-" ] - target_address = ethereum_address - chain_id = 1*DIGIT - function_name = STRING - ethereum_address = ( "0x" 40*HEXDIG ) / ENS_NAME - parameters = parameter *( "&" parameter ) - parameter = key "=" value - key = "value" / "gas" / "gasLimit" / "gasPrice" / TYPE - value = number / ethereum_address / STRING - number = [ "-" / "+" ] *DIGIT [ "." 1*DIGIT ] [ ( "e" / "E" ) [ 1*DIGIT ] ] - - -Where `TYPE` is a standard ABI type name, as defined in [Ethereum Contract ABI specification](https://solidity.readthedocs.io/en/develop/abi-spec.html). `STRING` is a URL-encoded unicode string of arbitrary length, where delimiters and the -percentage symbol (`%`) are mandatorily hex-encoded with a `%` prefix. - -Note that a `number` can be expressed in *scientific notation*, with a multiplier of a power of 10. Only integer numbers are allowed, so the exponent MUST be greater or equal to the number of decimals after the point. - -If *key* in the parameter list is `value`, `gasLimit`, `gasPrice` or `gas` then *value* MUST be a `number`. Otherwise, it must correspond to the `TYPE` string used as *key*. - -For the syntax of ENS_NAME, please consult [ERC-137](./eip-137.md) defining Ethereum Name Service. - -### Semantics - -`target_address` is mandatory and denotes either the beneficiary of native token payment (see below) or the contract address with which the user is asked to interact. - -`chain_id` is optional and contains the decimal chain ID, such that transactions on various test- and private networks can be requested. If no `chain_id` is present, the client's current network setting remains effective. - -If `function_name` is missing, then the URL is requesting payment in the native token of the blockchain, which is ether in our case. The amount is specified in `value` parameter, in the atomic unit (i.e. wei). The use of scientific notation is strongly encouraged. For example, requesting 2.014 ETH to address `0xfb6916095ca1df60bb79Ce92ce3ea74c37c5d359` would look as follows: -[ethereum:0xfb6916095ca1df60bb79Ce92ce3ea74c37c5d359?value=2.014e18](ethereum:0xfb6916095ca1df60bb79Ce92ce3ea74c37c5d359?value=2.014e18) - -Requesting payments in [ERC-20](./eip-20.md) tokens involves a request to call the `transfer` function of the token contract with an `address` and a `uint256` typed parameter, containing the *beneficiary address* and the *amount in atomic units*, respectively. For example, -requesting a Unicorn to address `0x8e23ee67d1332ad560396262c48ffbb01f93d052` looks as follows: -[ethereum:0x89205a3a3b2a69de6dbf7f01ed13b2108b2c43e7/transfer?address=0x8e23ee67d1332ad560396262c48ffbb01f93d052&uint256=1](ethereum:0x89205a3a3b2a69de6dbf7f01ed13b2108b2c43e7/transfer?address=0x8e23ee67d1332ad560396262c48ffbb01f93d052&uint256=1) - -If using ENS names instead of hexadecimal addresses, the resolution is up to the payer, at any time between receiving the URL and sending the transaction. Hexadecimal addresses always take precedence over ENS names, i. e. even if there exists a matching ENS name consisting of `0x` followed by 40 hexadecimal digits, it should never be resolved. Instead, the hexadecimal address should be used directly. - -Note that the indicated amount is only a suggestion (as are all the supplied arguments) which the user is free to change. With no indicated amount, the user should be prompted to enter the amount to be paid. - -Similarly `gasLimit` and `gasPrice` are suggested user-editable values for *gas limit* and *gas price*, respectively, for the requested transaction. It is acceptable to abbreviate `gasLimit` as `gas`, the two are treated synonymously. - -## Rationale -The proposed format is chosen to resemble `bitcoin:` URLs as closely as possible, as both users and application programmers are already familiar with that format. In particular, this motivated the omission of the unit, which is often used in Ethereum ecosystem. Handling different orders of magnitude is facilitated by the exponent so that amount values can be expressed in their nominal units, just like in the case of `bitcoin:`. The use of scientific notation is strongly encouraged when expressing monetary value in ether or [ERC-20](./eip-20.md) tokens. For better human readability, the exponent should be the decimal value of the nominal unit: 18 for ether or the value returned by `decimals()` of the token contract for [ERC-20](./eip-20.md) tokens. Additional parameters may be added, if popular use cases requiring them emerge in practice. - -The `0x` prefix before ethereum addresses specified as hexadecimal numbers is following established practice and also unambiguously distinguishes hexadecimal addresses from ENS names consisting of 40 alphanumeric characters. - -Future upgrades that are partially or fully incompatible with this proposal must use a prefix other than `pay-` that is separated by a dash (`-`) character from whatever follows it. - -## Backwards Compatibility - -In the fairly common case of only indicating the recipient address in a request for payment in ether, this specification is compatible with the superseded ERC-67. - -## Security Considerations - -Since irreversible transactions can be initiated with parameters from such URLs, the integrity and authenticity of these URLs are of great importance. -In particular, changing either the recipient address or the amount transferred can be a profitable attack. Users should only use URLs received from authenticated sources with adequate integrity protection. - -To prevent malicious redirection of payments using ENS, hexadecimal interpretation of Ethereum addresses must have precedence over ENS lookups. Client software may alert the user if an ENS address is visually similar to a hexadecimal address or even outright reject such addresses as likely phishing attacks. - -In order to make sure that the amount transacted is the same as the amount intended, the amount communicated to the human user should be easily verifiable by inspection, including the order of magnitude. In case of [ERC-20](./eip-20.md) token payments, if the payer client has access to the blockchain or some other trusted source of information about the token contract, the interface should display the amount in the units specified in the token contract. Otherwise, it should be displayed as expressed in the URL, possibly alerting the user to the uncertainty of the nominal unit. To facilitate human inspection of the amount, the use of scientific notation with an exponent corresponding to the nominal unit of the transacted token (e.g. 18 in case of ether) is advisable. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-681.md diff --git a/EIPS/eip-6810.md b/EIPS/eip-6810.md new file mode 100644 index 00000000000000..554b7c7e5c91e5 --- /dev/null +++ b/EIPS/eip-6810.md @@ -0,0 +1,107 @@ +--- +eip: 6810 +title: Ex Post Facto Cascading Revert +description: Allow transactions to be reversed after confirmation +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-6810-ex-post-facto-cascading-revert/13630 +status: Stagnant +type: Standards Track +category: Core +created: 2023-04-01 +requires: 2718, 2929 +--- + +## Abstract + +A new transaction type reverts one of a sender's prior transactions, and other transactions dependent on that state, recursively. + +## Motivation + +While Ethereum has the capability of reversible transactions through smart contracts, instant settlement is the default. +But sometimes users make mistakes. +Most mistakes are discovered quickly. +However, once the transaction is confirmed, it is settled. +There are many use cases for reverting settled transactions. +Some of the most-common mistakes are listed below. + +- Wrong recipient +- Unintended consequences +- Got scammed + +This feature addresses these issues and more, ending all regret. + +## Specification + +### Parameters + +A new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` `0x5a`. +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is `rlp([chainId, nonce, revertNonce, budget, signatureYParity, signatureR, signatureS])`. +The `signatureYParity, signatureR, signatureS` elements of this transaction represent a secp256k1 signature over `keccak256(0x5a || rlp([chainId, nonce, revertNonce, budget]))`. +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, budgetUsed, removedLogsBloom, [newReceiptPayloads]])`, where `newReceiptPayloads` is a sequential array of the updated receipts of all reverted transactions. + +### Block gas limit + +A transaction of type `0x5a` shall be the only transaction in its block. + +### Cascading revert operation + +A transaction fee budget is initialized to the value specified by `budget`, denominated in ether. +This budget is the transaction fee for this type of transaction. +Reverted transaction fees are refunded from this budget. +Should the budget be insufficient, the Ex Post Facto Cascading Revert transaction fails and the entire budget is paid to the `COINBASE` specified in the block header. +Otherwise, the remainder of the budget after all transactions are reverted is paid to the `COINBASE` account. + +The state is rolled back to the start of the transaction specified by `revertNonce`. +An access list is initialized empty. +Any state previously modified by a reverted transaction is added to the access list. +Any subsequent transaction reading or using state included in the access list must also be reverted. +This operation cascades forward until the current block. + +State includes: + +- ether balance +- contract code +- account nonce +- storage keys + +### Snap sync + +Due to the large amount of state that may be modified by such a transaction, slower clients should use snap sync to load the new state. + +## Rationale + +The transaction must fill the entire block to prevent MEV attacks. + +While some cascading reverts are highly consequential, others are considerably simpler. +The budget ensures the full network cost of the operation is paid. +For example, reversing a token transfer to the wrong recipient would be relatively cheap. +On the other hand, it would be prohibitively expensive to revert all deposits to a custodial exchange. + +Transaction fees must be refunded from this budget rather than the prior block reward in order to protect the security of the consensus protocol. + +Snap sync should be safe because if the state root is invalid then the block producer could get slashed. + +## Backwards Compatibility + +If we find any backwards compatibility issue we can maybe reverse those transactions. +If that doesn't work idk maybe need another hard fork. + +## Test Cases + +- Reverting a transaction that ever funded an account reverts all of that account's subsequent transactions. +- Reverting the transaction that deploys a contract reverts all transactions interacting with that contract. +- Reverting a transfer to a new account does not revert other transactions. + +## Reference Implementation + +Seems simple enough. +TODO this later; should only take a few hours, tops. + +## Security Considerations + +This specification has been audited by Illinois Senator Robert Peters. +No exploits were found. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6811.md b/EIPS/eip-6811.md new file mode 100644 index 00000000000000..75d12ea7697b7f --- /dev/null +++ b/EIPS/eip-6811.md @@ -0,0 +1,49 @@ +--- +eip: 6811 +title: To The Moon—10 Minute Blocks +description: Increases the block time to facilitate finality over cosmic distances +author: Pandapip1 (@Pandapip1) +discussions-to: https://ethereum-magicians.org/t/ethereum-to-the-moon/13633 +status: Stagnant +type: Standards Track +category: Core +created: 2023-04-01 +--- + +## Abstract + +This EIP makes a minimal number of changes to allow Ethereum to be used on the moon and other potentially habitable bodies in Earth's solar system. It changes the time between blocks, the per-block validator reward, and the number of blocks per epoch. + +## Motivation + +It is impossible for today's Ethereum to literally "go to the moon" due to a limitation in the protocol: the block length. Should validators attempt to validate on the surface of the moon, they would find that the ~1.25 second communication delay (caused by the speed of light) might cause issues with synchronization, considering the 12-second timer between blocks. The validators would eventually be ejected on the terrestrial chain after leaking. If however a substantial number of validators are displaced (think 1/3), they might follow their own fork and would eventually eject the terrestrial to finalize their own chain. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +* The time between blocks MUST be changed from 12 seconds to 600 seconds (10 minutes). +* The per-block validator reward MUST be multiplied by 50 +* The number of blocks per epoch MUST be reduced from 4 to 2 + +## Rationale + +* The block gas limit is multiplied by fifty to compensate for the time between blocks being multiplied by fifty. +* The per-block validator reward is also multiplied by fifty to compensate for the time between blocks being multiplied by fifty. +* Epochs are changed to be 2 blocks long so that finality can be reached in a reasonable amount of time. + +## Backwards Compatibility + +Many applications expect mainnet transactions to be included in a short amount of time. This would clearly no longer be the case. Such applications should switch to planetary rollups. Syncing rollups across heavenly bodies is outside the scope of this proposal. + +## Test Cases + +TODO. + +## Security Considerations + +Definitely needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6821.md b/EIPS/eip-6821.md new file mode 100644 index 00000000000000..64cbc2c6ae094b --- /dev/null +++ b/EIPS/eip-6821.md @@ -0,0 +1,7 @@ +--- +eip: 6821 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6821.md diff --git a/EIPS/eip-6823.md b/EIPS/eip-6823.md new file mode 100644 index 00000000000000..dec335e190bdb6 --- /dev/null +++ b/EIPS/eip-6823.md @@ -0,0 +1,7 @@ +--- +eip: 6823 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6823.md diff --git a/EIPS/eip-684.md b/EIPS/eip-684.md new file mode 100644 index 00000000000000..9f45676e5f3941 --- /dev/null +++ b/EIPS/eip-684.md @@ -0,0 +1,55 @@ +--- +eip: 684 +title: Revert creation in case of collision +description: Revert contract creation if address already has code +author: Vitalik Buterin (@vbuterin), Renan Rodrigues de Souza (@RenanSouza2) +discussions-to: https://ethereum-magicians.org/t/eip-revert-on-address-collision/13442 +status: Final +type: Standards Track +category: Core +created: 2023-03-20 +--- + +## Abstract + +This EIP causes contract creation to throw an error when attempted at an address with pre-existing code. This prevents an attack consisting of deploying contract code and later changing the code arbitrarily by "creating" an account at that existing address. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +If a contract creation is attempted due to a creation transaction, the `CREATE` opcode, the `CREATE2` opcode, or any other reason, and the destination address already has either a nonzero nonce, or a nonzero code length, then the creation MUST throw as if the first byte in the init code were an invalid opcode. This change MUST apply retroactively for all existing blocks. + +## Rationale + +One of the core tenants of smart contracts is that its code will not change. However with sufficient computing power an attacker can change the code stored in an address to any other code, steal funds or execute other malicious activity. + +## Backwards Compatibility + +This is an execution layer upgrade, and so it requires a hard fork. + +## Test Cases + +Given a genesis allocation of + +``` +Address : 0xd0bBEc6D2c628b7e2E6D5556daA14a5181b604C5, +Balance : 1000000000000000000, // 1 ether +Nonce : 0, +code : "", + +Address : 0x7658771dc6Af74a3d2F8499D349FF9c1a0DF8826, +Balance : 0, +Nonce : 1, +Code : "0xB0B0FACE", +``` + +A contract created in the first transaction from EOA `0xd0bBEc6...` (`227bcc6959669226360814723ed739f1214201584b6a27409dfb8228b8be5f59`), with no salt, should revert. + +## Security Considerations + +This EIP is a security upgrade: it enforces the imutability of deployed code. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6860.md b/EIPS/eip-6860.md new file mode 100644 index 00000000000000..ab60a4e36fba63 --- /dev/null +++ b/EIPS/eip-6860.md @@ -0,0 +1,7 @@ +--- +eip: 6860 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6860.md diff --git a/EIPS/eip-6864.md b/EIPS/eip-6864.md new file mode 100644 index 00000000000000..eef971dac5b57a --- /dev/null +++ b/EIPS/eip-6864.md @@ -0,0 +1,7 @@ +--- +eip: 6864 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6864.md diff --git a/EIPS/eip-6865.md b/EIPS/eip-6865.md new file mode 100644 index 00000000000000..8ddaf707f27965 --- /dev/null +++ b/EIPS/eip-6865.md @@ -0,0 +1,7 @@ +--- +eip: 6865 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6865.md diff --git a/EIPS/eip-6873.md b/EIPS/eip-6873.md new file mode 100644 index 00000000000000..ada437aefa5afd --- /dev/null +++ b/EIPS/eip-6873.md @@ -0,0 +1,64 @@ +--- +eip: 6873 +title: Preimage retention +description: Execution clients must retain the preimages of addresses and slots accessed between the fork preceding the verge, and the verge itself. +author: Guillaume Ballet (@gballet) +discussions-to: https://ethereum-magicians.org/t/eip-6873-preimage-retention-in-the-fork-preceding-the-verge/15830 +status: Stagnant +type: Standards Track +category: Core +created: 2023-04-14 +--- + +## Abstract + +Enforce preimage collection by every node on the network from the fork preceding the verge, up to the fork. This is needed in case each node is responsible for their own conversion. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Let `T_p` be the timestamp of the fork preceding the verge, and `T_v` the timestamp of the verge. + + * EL clients MUST save the preimage of each address and slot hashes they produce during the execution of all blocks produced between `T_p` and `T_v` + + * EL clients MAY start storing preimages outside of this time range as well + + * Given a hash produced between `T_p` and `T_v`, EL clients SHOULD be able to show they have the preimage for that hash in their database + + * EL clients SHOULD be able to download the preimages of the address and slot hashes that were produced before `T_v` from a publicly-available datastore + +## Rationale + +Switching to verkle trees require a complete rehashing of all tree keys. Most execution clients store all keys hashed, without their preimages, which as the time of print take up 70GB on mainnet. In order to make these preimages available to everyone, the following course of action are available to each user: + + * Restart a full-sync with preimage retention enabled + * Download the preimages as a file + +The second option is the only acceptable option in practice, as a full-sync requires the syncing machine to be offline for several days, and therefore should not be simultaneously imposed to the entire network. A file download, however, poses a problem of data obsolecense as new preimages will immediately need to be added to the list as the chain progresses and new addresses are accessed. Updating the preimage file is not sufficient, since it takes more than a slot time to download over 70GB. + +To guarantee a timely availability of all preimages around the verkle transition time, each node is therefore responsible for updating the list of preimages between the fork preceding the Verge, and the Verge itself. + +## Backwards Compatibility + +No backward compatibility issues found. + + + +## Reference Implementation + +All clients already implement preimage retention, at least as an option. + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6888.md b/EIPS/eip-6888.md new file mode 100644 index 00000000000000..8e05d1e6e26b5a --- /dev/null +++ b/EIPS/eip-6888.md @@ -0,0 +1,107 @@ +--- +eip: 6888 +title: Math checking in EVM +description: Check for math underflows overflows and division by zero at EVM level +author: Renan Rodrigues de Souza (@RenanSouza2) +discussions-to: https://ethereum-magicians.org/t/eip-math-checking/13846 +status: Stagnant +type: Standards Track +category: Core +created: 2023-04-16 +--- + +## Abstract + +This EIP adds many checks to EVM arithmetic and a new opcode to get the corresponding flags and clear them. The list of check includes underflows, overflows, division by zero. + +## Motivation + +The importance of math checks in smart contract projects is very clear. It was an OpenZeppelin library and then incorporated in Solidity's default behavior. Bringing this to EVM level can combine both gas efficiency and safety. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Starting from `BLOCK_TIMESTAMP >= HARDFORK_TIMESTAMP` + +### Constants + +| Constant | Type | Value | +| ------------------- | --------- |:------------- | +| `INT_MIN` | `int` | -(2**255) | +| `UINT_MAX` | `uint` | 2 ** 256 | + +### Flags + +| Variable | Type | Initial Value | +| ------------------- | --------- |:------------- | +| `carry` | `bool` | false | +| `overflow` | `bool` | false | + +Two new flags are added to the EVM state: unsigned error (`carry`) and signed error (`overflow`). The scope of those flags are the same as the program counter. Each frame of execution has their own flags. At the frame creation they are unset and they are updated in call. + +From this point forward `a`, `b` and `c` references the arguments in a math operation and `res` the output. `c` is only used if the operation takes 3 inputs. + +The `carry` flag MUST be set in the following circumstances: + + - When opcode is `ADD` (`0x01`) and `res < a` + - When opcode is `MUL` (`0x02`) and `a != 0 ∧ res / a != b` + - When opcode is `SUB` (`0x03`) and `b > a` + - When opcode is `DIV` (`0x04`) or `MOD` (`0x06`); and `b == 0` + - When opcode is `ADDMOD` (`0x08`) and `c == 0 ∨ ((a + b) / UINT_MAX > c)` + - When opcode is `MULMOD` (`0x08`) and `c == 0 ∨ ((a * b) / UINT_MAX > c)` + - When opcode is `EXP` (`0x0A`) and ideal `a ** b > UINT_MAX` + - When opcode is `SHL` (`0x1b`) and `res >> a != b` + +The `overflow` flag is MUST set in the following circumstances: + + - When opcode is `SUB` (`0x03`) and `a != 0 ∧ sgn(a) != sgn(b) ∧ sgn(b) == sgn(res)` + - When opcode is `ADD` (`0x01`) and `a != 0 ∧ sgn(a) == sgn(b) ∧ sgn(a) != sgn(res)` + - When opcode is `MUL` (`0x02`) and `(a == -1 ∧ b == INT_MIN) ∨ (a == INT_MIN ∧ b == -1) ∨ (a != 0 ∧ (res / a != b))` (this `/` represents `SDIV`) + - When opcode is `SDIV` (`0x05`) or `SMOD` (`0x06`); and `b == 0 ∨ (a == INT_MIN ∧ b == -1)` + - When opcode is `SHL` (`0x1b`) and `res >> a != b` (this `>>` represents `SAR`) + +The function `sgn(num)` returns the sign of the number, it can be negative, zero or positive. + +| Value | Mnemonic | δ | α | Description | +|-------|----------|---|---|---------------------------------------------------------------------------------------| +| `JUMPC` | `0x5B` | 1 | 0 | Conditionally alter the program counter. +|||||```J_JUMPC = carry ? µ_s[0] : µ_pc + 1``` +|||||```carry = overflow = false``` | +| `JUMPO` | `0x5C` | 1 | 0 | Conditionally alter the program counter. +|||||```J_JUMPO = ovewrflow ? µ_s[0] : µ_pc + 1``` +|||||```carry = overflow = false``` | + +### gas + +The gas cost for both instructions is `G_high`, the same as `JUMPI`. + +## Rationale + +EVM uses two's complement for negative numbers. The opcodes listed above triggers one or two flags depending if they are used for signed and unsigned numbers. + +The conditions described for each opcode is made with implementation friendliness in mind. The only exception is EXP as it is hard to give a concise test as most of the others relied on the inverse operation and there is no native `LOG`. Most `EXP` implementations will internally use `MUL` so the flag `carry` can be drawn from that instruction, not the `overflow`. + +The divisions by `UINT_MAX` used in the `ADDMOD` and `MULMOD` is another way to represent the higher 256 bits of the internal 512 number representation. + +Both flags are cleaned at the same time because the instructions are expected to be used when transitioning between codes where numbers are treated as signed or unsigned. + +## Backwards Compatibility + +This EIP introduces a new opcode and changes int EVM behavior. + +## Test Cases + +TBD + +## Reference Implementation + +TBD + +## Security Considerations + +This is a new EVM behavior but each code will decide how to interact with it. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6900.md b/EIPS/eip-6900.md new file mode 100644 index 00000000000000..eab36cd60cde0d --- /dev/null +++ b/EIPS/eip-6900.md @@ -0,0 +1,7 @@ +--- +eip: 6900 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6900.md diff --git a/EIPS/eip-6909.md b/EIPS/eip-6909.md new file mode 100644 index 00000000000000..fc4c6f558c2764 --- /dev/null +++ b/EIPS/eip-6909.md @@ -0,0 +1,7 @@ +--- +eip: 6909 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6909.md diff --git a/EIPS/eip-6913.md b/EIPS/eip-6913.md new file mode 100644 index 00000000000000..dcce12c97ea449 --- /dev/null +++ b/EIPS/eip-6913.md @@ -0,0 +1,104 @@ +--- +eip: 6913 +title: SETCODE instruction +description: new instruction to replace code in-place +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-6913-setcode-instruction/13898 +status: Draft +type: Standards Track +category: Core +created: 2023-04-20 +--- + +## Abstract + +Introduce the `SETCODE` (`0xfc`) instruction, which replaces the code of the executing account from memory. + +## Motivation + +Many contracts are upgradeable in order to facilitate improvement or defer decisions without migrating to a new address. +Contracts presently do this in several ways: + +The oldest method uses `CALL`. +The limitation of this method is that internal state must be modifiable by all future implementations. + +Second, `DELEGATECALL` can proxy the implementation. +Some proxies are minimal while others branch to many separate implementation accounts. +This method can also bypass account code size limits. + +A third method uses `SELFDESTRUCT` and `CREATE2` to replace code in-place. +This method improves upon the prior methods by removing the need to call into external contracts. +One limitation of this method is that any internal state is removed by `SELFDESTRUCT`. +Another limitation is that `SELFDESTRUCT` does not remove code until the end of the transaction, sacrificing availability until `CREATE2` can complete the upgrade. + +Given the upcoming deprecation of `SELFDESTRUCT`, `SETCODE` introduces a better method for replacing code in-place. + +## Specification + +When within a read-only execution scope like the recursive kind created by `STATICCALL`, `SETCODE` causes an exceptional abort. + +When the currently executing code does not equal the code of the executing account, such as can happen inside of `DELEGATECALL` or `CREATE`, `SETCODE` causes an exceptional abort. + +Otherwise, `SETCODE` consumes two words from the stack: offset and length. +These specify a range of memory containing the new code. +Any validations that would be performed on the result of `CREATE` or `CREATE2` occur immediately, potentially causing failure with exceptional abort. +The operations `EXTCODESIZE` and `EXTCODECOPY` now query the updated code, and message-calls such as `DELEGATECALL`, `CALLCODE`, `CALL`, and `STATICCALL` now execute the updated code. +Any execution scopes already executing replaced code, including the one that `SETCODE`, will continue executing the prior code. +Inside such scopes, `CODESIZE` and `CODECOPY` continue to query the executing code. + +Like `SSTORE`, this account modification will be reverted if the current scope or any parent scope reverts or aborts. + +Unlike `SELFDESTRUCT`, `SETCODE` does not clear account balance, nonce, or storage. + +### Gas + +The gas cost of this operation is the sum of `Gselfdestruct` and the product of `Gcodedeposit` and the number of bytes in the new code. + +## Rationale + +The behavior of `CODECOPY`, `CODESIZE`, `EXTCODESIZE`, and `EXTCODECOPY` match the behavior of `DELEGATECALL` and `CREATE`, where it is also possible for executing code to differ from the code of the executing account. + +The gas cost of `SETCODE` is comparable to `CREATE` but excludes `Gcreate` because no execution context is created, nor any new account. +Other account modification costs are accounted for outside of execution gas. + +Unlike `SELFDESTRUCT`, execution proceeds normally after `SETCODE` in order to allow validation and return data. +Post-update validation can undo a `SETCODE` operation with `REVERT`, or with a recursive `SETCODE`, but `REVERT` uses less gas. + +Preventing `SETCODE` within most `DELEGATECALL` allows static analysis to easily identify mutable code. +Account code not containing the `SETCODE` operation can be safely assumed to be immutable. +Code observed in a non-reverting context to be immutable will remain immutable, allowing on-chain static analysis for immutability. + +## Backwards Compatibility + +The only prior operation changing code is `SELFDESTRUCT`. +As code modification via `SELFDESTRUCT` is deferred until the end of the transaction, its interactions with `SETCODE` are well-defined. + +## Test Cases + +| CodeStart | CallData | CodeResult | Gas | +|----------------------|------------------|----------------------|------| +| 365f5f37365ffc00 | 365f5f37365ffc00 | 365f5f37365ffc00 | 6613 | +| 365f5f37365ffc00 | 00 | 00 | 5213 | +| 365f5f37365ffc00 | | | 5013 | +| 365f5f37365ffc595ffd | 365f5f37365ffc00 | 365f5f37365ffc595ffd | 6617 | +| 365f5f37365ffcfe | 365f5f37365ffc00 | 365f5f37365ffcfe | all | + +## Security Considerations + +Risks related to `SETCODE` similarly apply to other upgrade patterns. + +Most contracts should never be replaced and should not be upgradeable. +Any upgrade mechanism can risk permanent failure. +The possibility of upgrade perpetuates such risk. + +Access to upgrade operations should be restricted. +Upgrades should never be performed in a hurry or when tired. +Upgrades should be tested under as similar conditions to production as possible; discrepancies are sources of unexpected results. +When possible, multiple engineers should preview and independently verify pending upgrade procedures. + +Block explorers, wallets, and other interfaces should flag upgradeable code. +Client software should warn against approving [ERC-20](./eip-20.md) or [ERC-721](./eip-721.md) tokens for upgradeable accounts. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6914.md b/EIPS/eip-6914.md new file mode 100644 index 00000000000000..61e09b21debaaf --- /dev/null +++ b/EIPS/eip-6914.md @@ -0,0 +1,77 @@ +--- +eip: 6914 +title: Reuse Withdrawn Validator Indices +description: Reuse fully withdrawn and safe to reuse validator indices for new beacon chain deposits. +author: Lion (@dapplion), Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-6914-reuse-withdrawn-validator-indices/15253 +status: Draft +type: Standards Track +category: Core +created: 2023-04-19 +--- + +## Abstract + +Reuse fully withdrawn validator indices after a sufficient safe-to-reuse period has passed to eliminate the unbounded growth of the beacon chain validator list as the validator set churns. + +## Motivation + +The beacon chain maintains a list of validators and a separate list of balances associated with each validator. When a new deposit for a new validator occurs, the current mechanism only appends, rather than reusing previously fully withdrawn validator indices. As validators fully withdraw and new validators enter, this means the two lists will grow unbounded. + +This specification allows for the reuse of validator indices in the event that it is safe to do so, eliminating the concerns around the unbounded validator list growth. + +## Specification + +### Consensus Layer + +The configuration values and mechanics of the specification can be found in the [Consensus Layer specs](https://github.com/ethereum/consensus-specs/blob/1a38b83e5db8638ee01c9461cccf11e7d8a3ebce/specs/_features/eip6914). + +Note that validator indices are reused in the event that the validator has been fully withdrawn *and* that the validator has been withdrawable for a sufficient safe period. + +### Execution Layer + +This specification does not require any changes to the Execution Layer. + +## Rationale + +The `validators` and `balances` lists are currently appended to each time a new Deposit for a new pubkey comes into the beacon chain. Due to the natural mechanics of stakers entering and leaving consensus over long time spans, these lists, thus the state size, will grow unbounded. + +Increased state size represents load and/or complexity in client implementations. This comes in the form of client memory footprint, state root calculations, validator set scans, and more. This is a relatively simple clean-up within the state transition that will prevent the unnecessary load and complexity of the otherwise unbounded lists. + +## Backwards Compatibility + +This is a backwards incompatible change to the Consensus Layer of Ethereum and must be scheduled with a hard fork. + +There are no forwards/backwards compatibility issues with the Execution Layer + +## Test Cases + +Test cases are work-in-progress within the standard Consensus Layer tests. + +## Security Considerations + +Validator indices cannot be immediately reused but instead must wait `SAFE_EPOCHS_TO_REUSE_INDEX` epochs to ensure that attestations cannot be "poisoned" with withdrawn validator signatures -- thus non-slashable -- for at least the weak subjectivity period. + +The attestation poisoning attack hinges upon two facts: + +* the reuse of a validator index overwrites the previous validator's pubkey from the beacon state. +* `AttesterSlashing`s include validator indices to reconstruct signature pariticipants. + +### Details of attack + +Assume a 1/3 attacker. Attacker exits N validators on the honest chain, where N is a small fraction of the validator set. These validators leave the exit queue and are withdrawable within a few days. Now N new deposits come in and overwrite the validators and most importantly their pubkeys. + +The attacker then constructs an alternative attacker chain from before any of the N voluntary exits such that the original N validators are not exited and withdrawn. N is large enough such that at least one of the N keys is on average in every committee of the attacker chain. The attacker double signs in an attempt to finalize the attacker chain but ensures that one of the N keys is mixed into any revealed double-signed aggregate attestation -- the individual attestations are unavailable, only aggregates. These malicious attestations are *not* includable in the honest chain because `AttesterSlashing`s rely upon mapping validator indices to particular pubkeys, thus breaking accountable safety. + +### Mitigation + +Not overwriting withdrawn validators for `SAFE_EPOCHS_TO_REUSE_INDEX` epochs (3x the max weak subjectivity period) ensures that attestations cannot be poisoned within the accountable safety security window. + +### Alternative + +Note that if `AttesterSlashing`s included a list of pubkeys instead of validator indices, then this would not be an issue. However this would require more breaking changes and would increase the data requirement of an `AttesterSlashing`, the largest Consensus Layer data type by a factor of 6. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-6916.md b/EIPS/eip-6916.md new file mode 100644 index 00000000000000..38716d37eab114 --- /dev/null +++ b/EIPS/eip-6916.md @@ -0,0 +1,144 @@ +--- +eip: 6916 +title: Automatically Reset Testnet +description: A testnet network that periodically rolls back to genesis +author: Mário Havel (@taxmeifyoucan), pk910 (@pk910), Rémy Roy (@remyroy), Holly Atkinson (@atkinsonholly), Tereza Burianova (@T-ess) +discussions-to: https://ethereum-magicians.org/t/automatically-reset-testnet/15825 +status: Review +type: Standards Track +category: Core +created: 2023-04-10 +--- + +## Abstract + +This EIP proposes a specification for an automatically reset testnet, a novel approach to testnets that can be implemented within Ethereum clients. It enables a single testing infrastructure consisting of ephemeral networks with deterministic parameters. Each network iteration is created by a specified function which deterministically generates genesis states. + +## Motivation + +A testnet which automatically resets can provide an alternative environment for short-term testing of applications, validators and also breaking changes in client implementations. It avoids issues of long running testnets which suffer from state bloat, lack of testnet funds or consensus issues. Periodically resetting the network back to genesis cleans the validator set and returns funds back to faucets while keeping the network reasonably small for easy bootstrapping. + +## Specification + +The testnet is set to always reset after a predefined time period. The reset means the generation of the next genesis, discarding the old one and starting a new network. This is possible by introducing functions for the genesis generation and the client reset. + +### Genesis + +To connect to the current instance of the network, the client must implement the genesis function. This function defines how the client stores information about the testnet and generates the current genesis. With each reset, the network starts from a new genesis which needs to be built based on given parameters and correspond in EL and CL clients. + +The network always starts from a genesis which is deterministically created based on the original one - this very first genesis is hardcoded and we can call it `genesis 0`. Terminal time, the expiration of each genesis, is the addition of the start time of that genesis `MIN_GENESIS_TIME` and the testnet lifetime `period`, where `period` is a constant defining the length of time a single ephemeral network runs. Therefore, once the current slot timestamp reaches the terminal time of the ephemeral network, it has to switch to a new genesis. The main changes in each new genesis iteration are chainId, genesis time and the withdrawal credentials of the first validator. + +Clients shall include a hardcoded `genesis 0`, much like other networks predefined in clients. However, this genesis shall be used directly, only at the very beginning of the testnet's existence, in its first iteration where `i` equals `0`. Later on, with iteration `i` equal to `1` and above, the client does not initialize this genesis but uses it to derive the current one. When `i>0`, given a known `period` and current slot timestamp, the client always calculates the number of lifecycle iterations from `genesis 0` and creates a new genesis with the latest parameters. + +When the client starts with the option of an ephemeral testnet, it checks whether a genesis for the network is present. If it doesn't exist or the current slot timestamp is older than `current_genesis.genesis_time + period`, it triggers the generation of a new genesis. This new genesis, derived from `genesis 0`, will be written to the database and used to run the current network. + +#### Execution client + +The EL client includes the hardcoded `genesis 0` serving as a preimage for generating the current one. Iteration of variables is done as follows: + +* Number of iterations: + * `i` = `int((current_slot_timestamp` - `genesis_0.genesis_time) / period)` +* Genesis time of current genesis: + * `current_genesis.genesis_time` = `period` * `i` + `genesis_0.genesis_time` +* Current EL ChainId: + * `chainId` = `genesis_0.chainId` + `i` + +#### Consensus client + +Genesis generation in the CL client includes iteration of values as in EL but also requires the updated genesis state. The state in SSZ format can be either generated by the client or downloaded from an external source. It includes validators with deposits ready to launch a merged network with the validator set created by trusted entities within the community. + +`MIN_GENESIS_TIME` is set to the latest genesis time and defines when the current period starts. It is recommended to add a small `GENESIS_DELAY`, for example 15 minutes, to avoid issues while infrastructure is restarting with the new genesis. + +To ensure a successful reset, `ForkDigest` needs to be unique for each iteration. In order to keep the `ForkVersions` of the network static for better tooling support, the withdrawal credentials of the first validator in the validator set need to be overridden by a calculated value. + +* `genesis.validators[0].withdrawal_credentials` = `0x0100000000000000000000000000000000000000000000000000000000000000` + `i` +* `genesis.genesis_validators_root` = `hash_tree_root(genesis.validators)` + +The update of `genesis.validators[0]` changes the state, therefore, clients have to be able to generate or download the latest genesis state. Generating the genesis ssz is not considered a standard client feature and adding it enables to trustlessly create the latest genesis state at the price of certain complexity. An alternative solution is to obtain it from a third party, either by downloading the ssz file from a server or using the checkpoint sync feature with an endpoint serving the genesis state. This became an accepted practice with Holešky testnet and the existing feature can be used for obtaining genesis states for automatically reset testnets. It also allows maintainers to update the genesis validator set without requiring new client releases. The full implementation of the recommended practice for obtaining the latest CL state should behave as follows: + +* When the testnet flag is provided and client supports checkpoint sync of genesis, automatically use the hardcoded checkpoint endpoint to download the latest genesis state using the checkpoint sync feature + * If user provides a custom checkpoint sync flag, override the default option and use the endpoint provided by user +* Include a backup download option pointing to an url with the latest testnet release, a publicly distributed ssz file, and trigger this option if the checkpoint state sync fails or make it the default if client doesn't support genesis checkpoint sync +* If the client includes a feature for generating the genesis, use it to verify parameters in the downloaded state and issue an error if values or checksum don't correspond + +It's important to note that `genesis_validators_root` is normally predefined in the client but in this case it's not known in advance which can potentially break certain architectures. For example light clients which are relying on hardcoded `genesis_validators_root` won't work. + +### Reset + +The reset function defines an automatic process of throwing away the old data and starting with a new genesis. It depends on the previously defined function for genesis generation which the client must implement in order to be able to automatically follow the latest network iteration. + +For the reset function, we can introduce the `terminal_timestamp` value which defines the network expiry time of an iteration. It can be the same as the genesis time of the next iteration (without the genesis delay) or can be calculated simply as `terminal_timestamp = current_genesis.genesis_time + period`. + +When the network reaches a slot with a timestamp `>= terminal_timestamp`: + +* Client stops accepting/creating new blocks + * Shutdown client services running the network, e.g. p2p communication, beacon service, execution environment + * This feature should be implemented alongside Genesis even without further reset functions just to create a basic support which is always safe from forking +* Client calls a function which discards the current genesis, all chain or beacon data + * Clients already include db tools including for purging the database which could be used here + * It might be beneficial to include an additional flag, e.g. `--retain-ephemeral-data`, which would first export the existing data in a standard format before removing the database +* Client triggers the Genesis function (as defined above): + * Behaves like a regular client startup when genesis is not present + * New genesis is written into db and initialized +* Main network services are started again pointing to the updated genesis +* After the new genesis time is reached, the network starts again from the new genesis + +For a full reset implementation, clients should be able to perform the above actions without requiring manual restart, operating the network fully independently and with minimal downtime. + +Note that depending on the client architecture, it may not be feasible to fully implement such an internal reset mechanism, e.g. if the client doesn't support a graceful shutdown. The reset feature is considered an advanced level of support and is mainly needed by infrastructure providers and genesis validators. The assumption is that even if the client doesn't implement reset, advanced users can achieve similar behavior with external scripts handling the client by system tools. + +## Rationale + +Ephemeral testnets with deterministic parameters provide a sustainable alternative to traditional testnets, with the same infrastructure. At each reset, the validator set is cleared, faucets are filled again and the database is kept small. + +Upon reset the whole state is purged, which, on the one hand keeps the network small and easy to bootstrap but introduces problems for testing longer term / advanced applications. However, basic contract infrastructure can be automatically deployed after each reset by any user. Generally, using the network is recommended for short term testing, deploying `Hello World` kinds of contracts that don't need to stay forever on a long term testnet. However, there can be an offchain mechanism that automatically deploys standard contract primitives after each reset so application developers can also utilize the network more. + +By defining two mechanisms for Genesis and Reset, this EIP enables two levels of how a client implementation can support the testnet; + +* Basic support requires the client to determine the current network specs and enables only connecting to the network. + * This means support of the Genesis mechanism defined above + * Enough to participate in the network for short term testing + * To follow the latest iteration, the user has to manually shut down the client and delete the database + * It's still recommended to add a feature for terminating the network +* Full support enables the client to follow the reset process and always sync the latest chain iteration + * This also requires the client to implement an inherent Reset feature + * Needed for running persistent infrastructure, genesis validators and bootnodes + * It might be more complex to implement due to client architecture of clients + +The design is also compatible with nodes managed by external tooling, i.e. even if the client doesn't implement these features, it can run on the same network as other nodes which are automatically reset by scripts. Any client supporting a custom network can be used for the testnet. + +### Network parameters + +Constants and variables defining testnet properties are arbitrary but need to be crafted considering certain limitations and security properties set out below. + +#### Reset Period + +The `period` is a constant, hardcoded in the client defining the period of time after which the network resets. + +It can be defined based on users' needs but for security reasons, it also depends on the number of validators in genesis. Considering the time to activate a validator, the number of trusted validators should be high enough so the network cannot be overtaken by a malicious actor. + +```sh +Genesis Validators => Epochs until < 66% majority +10k => 1289 Epochs (5,7 days) +50k => 6441 Epochs (28,6 days) +75k => 9660 Epochs (42,9 days) +100k => 12877 Epochs (57,2 days) +150k => 19323 Epochs (85,9 days) +200k => 25764 Epochs (114,5 days) +``` + +#### ChainId + +ChainId is a variable because it needs to keep changing with each new genesis to avoid replay attack. The function for the new ChainId value is a simple incrementation (+1). The ChainId in `genesis 0` is a hardcoded constant. This constant is used by the client with each new genesis to derive a new ChainId for that network iteration. + +New ChainIds shouldn't collide with any other existing public EVM chain even after many iterations. Consequently, low ChainId values are discouraged. + +## Security Considerations + +The network itself is providing a secure environment thanks to regular resets. Even if some sort of vulnerability is exploited, it will be cleared on the next reset. This is also a reason to keep periods relatively short (weeks/months opposed to months/years) with a big enough genesis validator set to keep an honest majority. + +Changes in clients caused by the implementation of features for resetting networks need to be reviewed together with standard security procedures. Especially the mechanism for triggering reset which must be separated from other networks that are not configured as ephemeral. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6944.md b/EIPS/eip-6944.md new file mode 100644 index 00000000000000..693e3e5dbefff1 --- /dev/null +++ b/EIPS/eip-6944.md @@ -0,0 +1,7 @@ +--- +eip: 6944 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6944.md diff --git a/EIPS/eip-6953.md b/EIPS/eip-6953.md new file mode 100644 index 00000000000000..f944cb306c44f9 --- /dev/null +++ b/EIPS/eip-6953.md @@ -0,0 +1,101 @@ +--- +eip: 6953 +title: Network Upgrade Activation Triggers +description: Exhaustive list of network upgrade activation mechanisms +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-6666-network-upgrade-activation-triggers/14047 +status: Final +type: Informational +created: 2023-04-28 +requires: 2982, 3675, 6122 +--- + +## Abstract + +This EIP outlines the various network upgrade activation triggers used on Ethereum over time, from the proof-of-work era to the first post-merge network upgrade, Shanghai/Capella, across both the execution and consensus layers. + +## Motivation + +This EIP aims to provide users and developers with a single source of truth for understanding the various upgrade activation patterns used throughout Ethereum's history. It does not aim to be a comprehensive, ongoing record, of upgrades and their activations mechanism. Readers should assume that future upgrades use the mechanism described in the [Post Merge Upgrades](#post-merge-upgrades) section, unless this EIP is superseded by another one. + +## Specification + +### Proof-of-Work Network Upgrades + +During the proof-of-work era, network upgrades on Ethereum were triggered based on specific block numbers. The following upgrades followed this pattern: + +| Upgrade Name | Activation Block Number | +|--------------------|-------------------------| +| Frontier | `1` | +| Frontier Thawing | `200000` | +| Homestead | `1150000` | +| DAO Fork | `1920000` | +| Tangerine Whistle | `2463000` | +| Spurious Dragon | `2675000` | +| Byzantium | `4370000` | +| Constantinople | `7280000` | +| Petersburg | `7280000` | +| Istanbul | `9069000` | +| Muir Glacier | `9200000` | +| Berlin | `12244000` | +| London | `12965000` | +| Arrow Glacier | `13773000` | +| Gray Glacier | `15050000` | + +### Beacon Chain Launch + +The Beacon Chain was launched following a set of conditions detailed in [EIP-2982](./eip-2982.md). The launch was activated once all the following conditions were met: + +1. The Beacon Chain deposit contract received at least `524288` ETH from `16384` validators. +2. The `MIN_GENESIS_TIME` timestamp of `1606824000` (Dec 1, 2020) had been exceeded. +3. A `GENESIS_DELAY` of `604800` seconds had passed since the minimum validator count was exceeded. + +### Beacon Chain Upgrades + +Beacon Chain upgrades are activated at specific epochs. The following upgrades followed this pattern: + +| Upgrade Name | Activation Epoch | +|--------------|------------------| +| Altair | `74240` | +| Bellatrix | `144896` | + +### The Merge: Paris Upgrade + +The Paris upgrade, the execution layer portion of "The Merge," was triggered by a proof-of-work Total Difficulty value of `58750000000000000000000`, as specified in [EIP-3675](./eip-3675.md). Note that the activation of the Bellatrix upgrade on the Beacon Chain was a pre-requisite for the Paris upgrade to successfully activate on the proof-of-work chain. + +### Post-Merge Upgrades + +After The Merge, network upgrades are triggered at an epoch on the consensus layer (CL), which ideally maps to an historical roots accumulator boundary (i.e., a multiple of 7192 epochs). The epoch's corresponding timestamp, rather than a block number, is then used on the execution layer (EL) as the activation trigger. The following upgrades followed this pattern: + +| Upgrade Name | Activation Epoch | Activation Timestamp | +|------------------|------------------|----------------------| +| Capella (CL) | `194048` | | +| Shanghai (EL) | | `1681338455` | + +Note that epoch `194048` happened at timestamp `1681338455`. In other words, the upgrades activated simultaneously on both the execution and consensus layers, even though they each used a different constant to trigger it. + +Additionally, the use of timestamps on the execution layer resulted in changes to how nodes' `FORK_HASH` and `FORK_NEXT` values are calculated. These are described in [EIP-6122](./eip-6122.md) + +## Rationale + +### Blocks and Epochs + +Blocks and epochs serve as natural trigger points for upgrades, as they represent the levels at which state transitions occur on Ethereum. + +### Terminal Total Difficulty + +For the Terminal Total Difficulty mechanism, the rationale can be found in [EIP-3675](./eip-3675.md). + +### Timestamps + +Due to the possibility of missed slots on the Beacon Chain, the execution layer cannot rely solely on block numbers to trigger upgrades in sync with the consensus layer. + +Timestamps are guaranteed to map to a specific epoch, and in their Unix representation, timestamps will always be greater than the block numbers previously used. This allows for a reliable method to trigger upgrades on the execution layer post-merge, while also ensuring that a post-merge upgrade based on a timestamp can never use a value that is considered lower than the last block-triggered upgrade. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6956.md b/EIPS/eip-6956.md new file mode 100644 index 00000000000000..9ef5b49a4a1bd5 --- /dev/null +++ b/EIPS/eip-6956.md @@ -0,0 +1,7 @@ +--- +eip: 6956 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6956.md diff --git a/EIPS/eip-6960.md b/EIPS/eip-6960.md new file mode 100644 index 00000000000000..519ff172650491 --- /dev/null +++ b/EIPS/eip-6960.md @@ -0,0 +1,7 @@ +--- +eip: 6960 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6960.md diff --git a/EIPS/eip-6963.md b/EIPS/eip-6963.md new file mode 100644 index 00000000000000..a768527c2ed8b5 --- /dev/null +++ b/EIPS/eip-6963.md @@ -0,0 +1,274 @@ +--- +eip: 6963 +title: Multi Injected Provider Discovery +description: Using window events to announce injected Wallet Providers +author: Pedro Gomes (@pedrouid), Kosala Hemachandra (@kvhnuke), Richard Moore (@ricmoo), Gregory Markou (@GregTheGreek), Kyle Den Hartog (@kdenhartog), Glitch (@glitch-txs), Jake Moxey (@jxom), Pierre Bertet (@bpierre), Darryl Yeo (@darrylyeo), Yaroslav Sergievsky (@everdimension) +discussions-to: https://ethereum-magicians.org/t/eip-6963-multi-injected-provider-interface-aka-mipi/14076 +status: Final +type: Standards Track +category: Interface +created: 2023-05-01 +requires: 1193 +--- + +## Abstract + +An alternative discovery mechanism to `window.ethereum` for [EIP-1193](./eip-1193.md) providers which supports discovering multiple injected Wallet Providers in a web page using Javascript's `window` events. + +## Motivation + +Currently, Wallet Provider that offer browser extensions must inject their Ethereum providers ([EIP-1193](./eip-1193.md)) into the same window object `window.ethereum`; however, this creates conflicts for users that may install more than one browser extension. + +Browser extensions are loaded in the web page in an unpredictable and unstable order, resulting in a race condition where the user does not have control over which Wallet Provider is selected to expose the Ethereum interface under the `window.ethereum` object. Instead, the last wallet to load usually wins. + +This results not only in a degraded user experience but also increases the barrier to entry for new browser extensions as users are forced to only install one browser extension at a time. + +Some browser extensions attempt to counteract this problem by delaying their injection to overwrite the same `window.ethereum` object which creates an unfair competition for Wallet Providers and lack of interoperability. + +In this proposal, we present a solution that focuses on optimizing the interoperability of multiple Wallet Providers. This solution aims to foster fairer competition by reducing the barriers to entry for new Wallet Providers, along with enhancing the user experience on Ethereum networks. + +This is achieved by introducing a set of window events to provide a two-way communication protocol between Ethereum libraries and injected scripts provided by browser extensions thus enabling users to select their wallet of choice. + +## Specification + +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in [RFC-2119]. + +### Definitions + +Wallet Provider: A user agent that manages keys and facilitates transactions with Ethereum. + +Decentralized Application (DApp): A web page that relies upon one or many Web3 platform APIs which are exposed to the web page via the Wallet. + +Provider Discovery Library: A library or piece of software that assists a DApp to interact with the Wallet. + +### Provider Info + +Each Wallet Provider will be announced with the following interface `EIP6963ProviderInfo`. The values in the `EIP6963ProviderInfo` MUST be included within the `EIP6963ProviderInfo` object. The `EIP6963ProviderInfo` MAY also include extra extensible properties within the object. If a DApp does not recognize the additional properties, it SHOULD ignore them. + +- **`uuid`** - a globally unique identifier the Wallet Provider that MUST be ([UUIDv4][RFC-4122] compliant) to uniquely distinguish different [EIP-1193](./eip-1193.md) provider sessions that have matching properties defined below during the lifetime of the page. The cryptographic uniqueness provided by [UUIDv4][RFC-4122] guarantees that two independent `EIP6963ProviderInfo` objects can be separately identified. +- **`name`** - a human-readable local alias of the Wallet Provider to be displayed to the user on the DApp. (e.g. `Example Wallet Extension` or `Awesome Example Wallet`) +- **`icon`** - a [URI][RFC-3986] pointing to an image. The image SHOULD be a square with 96x96px minimum resolution. See the [Images/Icons](#imagesicons) below for further requirements of this property. +- **`rdns`** - The Wallet MUST supply the `rdns` property which is intended to be a domain name from the Domain Name System in reverse syntax ordering such as `com.example.subdomain`. It's up to the Wallet to determine the domain name they wish to use, but it's generally expected the identifier will remain the same throughout the development of the Wallet. It's also worth noting that similar to a user agent string in browsers, there are times where the supplied value could be unknown, invalid, incorrect, or attempt to imitate a different Wallet. Therefore, the DApp SHOULD be able to handle these failure cases with minimal degradation to the functionality of the DApp. + +```typescript +/** + * Represents the assets needed to display a wallet + */ +interface EIP6963ProviderInfo { + uuid: string; + name: string; + icon: string; + rdns: string; +} +``` + +#### Images/Icons + +A URI-encoded image was chosen to enable flexibility for multiple protocols for fetching and rendering icons, for example: + +```sh +# svg (data uri) +data:image/svg+xml, +# png (data uri) +data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== +``` + +The `icon` string MUST be a data URI as defined in [RFC-2397]. The image SHOULD be a square with 96x96px minimum resolution. The image format is RECOMMENDED to be either lossless or vector based such as PNG, WebP or SVG to make the image easy to render on the DApp. Since SVG images can execute Javascript, applications and libraries MUST render SVG images using the `` tag to ensure no untrusted Javascript execution can occur. + +#### RDNS + +The **`rdns`** (Reverse-DNS) property serves to provide an identifier which DApps can rely on to be stable between sessions. The Reverse Domain Name Notation is chosen to prevent namespace collisions. +The Reverse-DNS convention implies that the value should start with a reversed DNS domain name controlled by the Provider. The domain name should be followed by a subdomain or a product name. Example: `com.example.MyBrowserWallet`. + +- The `rdns` value MUST BE a valid [RFC-1034] Domain Name; +- The DNS part of the `rdns` value SHOULD BE an active domain controlled by the Provider; +- DApps MAY reject the Providers which do not follow the Reverse-DNS convention correctly; +- DApps SHOULD NOT use the `rnds` value for feature detection as these are self-attested and prone to impersonation or bad incentives without an additional verification mechanism; feature-discovery and verification are both out of scope of this interface specification. + +### Provider Detail + +The `EIP6963ProviderDetail` is used as a composition interface to announce a Wallet Provider and related metadata about the Wallet Provider. The `EIP6963ProviderDetail` MUST contain an `info` property of type `EIP6963ProviderInfo` and a `provider` property of type `EIP1193Provider` defined by [EIP-1193](./eip-1193.md). + +```typescript +interface EIP6963ProviderDetail { + info: EIP6963ProviderInfo; + provider: EIP1193Provider; +} +``` + +### Window Events + +In order to prevent provider collisions, the DApp and the Wallet are expected to emit an event and instantiate an eventListener to discover the various Wallets. This forms an Event concurrency loop. + +Since the DApp code and Wallet code aren't guaranteed to run in a particular order, the events are designed to handle such race conditions. + +To emit events, both DApps and Wallets MUST use the `window.dispatchEvent` function to emit events and MUST use the `window.addEventListener` function to observe events. There are two Event interfaces used for the DApp and Wallet to discover each other. + +#### Announce and Request Events + +The `EIP6963AnnounceProviderEvent` interface MUST be a `CustomEvent` object with a `type` property containing a string value of `eip6963:announceProvider` and a `detail` property with an object value of type `EIP6963ProviderDetail`. The `EIP6963ProviderDetail` object SHOULD be frozen by calling `Object.freeze()` on the value of the `detail` property. + +```typescript +// Announce Event dispatched by a Wallet +interface EIP6963AnnounceProviderEvent extends CustomEvent { + type: "eip6963:announceProvider"; + detail: EIP6963ProviderDetail; +} +``` + +The `EIP6963RequestProviderEvent` interface MUST be an `Event` object with a `type` property containing a string value of `eip6963:requestProvider`. + +```typescript +// Request Event dispatched by a DApp +interface EIP6963RequestProviderEvent extends Event { + type: "eip6963:requestProvider"; +} +``` + +The Wallet MUST announce the `EIP6963AnnounceProviderEvent` to the DApp via a `window.dispatchEvent()` function call. The Wallet MUST add an EventListener to catch an `EIP6963RequestProviderEvent` dispatched from the DApp. This EventListener MUST use a handler that will re-dispatch an `EIP6963AnnounceProviderEvent`. This re-announcement by the Wallet is useful for when a Wallet's initial Event announcement may have been delayed or fired before the DApp had initialized its EventListener. This allows the various Wallet Providers to react to the DApp without the need to pollute the `window.ethereum` namespace which can produce non-deterministic wallet behavior such as different wallets connecting each time. + +The Wallet dispatches the `"eip6963:announceProvider"` event with immutable contents and listens to the `"eip6963:requestProvider"` event: + +```typescript +let info: EIP6963ProviderInfo; +let provider: EIP1193Provider; + +const announceEvent: EIP6963AnnounceProviderEvent = new CustomEvent( + "eip6963:announceProvider", + { detail: Object.freeze({ info, provider }) } +); + +// The Wallet dispatches an announce event which is heard by +// the DApp code that had run earlier +window.dispatchEvent(announceEvent); + +// The Wallet listens to the request events which may be +// dispatched later and re-dispatches the `EIP6963AnnounceProviderEvent` +window.addEventListener("eip6963:requestProvider", () => { + window.dispatchEvent(announceEvent); +}); +``` + +The DApp MUST listen for the `EIP6963AnnounceProviderEvent` dispatched by the Wallet via a `window.addEventListener()` method and MUST NOT remove the Event Listener for the lifetime of the page so that the DApp can continue to handle Events beyond the initial page load interaction. The DApp MUST dispatch the `EIP6963RequestProviderEvent` via a `window.dispatchEvent()` function call after the `EIP6963AnnounceProviderEvent` handler has been initialized. + +```typescript +// The DApp listens to announced providers +window.addEventListener( + "eip6963:announceProvider", + (event: EIP6963AnnounceProviderEvent) => {} +); + +// The DApp dispatches a request event which will be heard by +// Wallets' code that had run earlier +window.dispatchEvent(new Event("eip6963:requestProvider")); +``` + +The DApp MAY elect to persist various `EIP6963ProviderDetail` objects contained in the announcement events sent by multiple wallets. Thus, if the user wishes to utilize a different Wallet over time, the user can express this within the DApp's interface and the DApp can immediately elect to send transactions to that new Wallet. Otherwise, the DApp MAY re-initiate the wallet discovery flow via dispatching a new `EIP6963RequestProviderEvent`, potentially discovering a different set of wallets. + +The described orchestration of events guarantees that the DApp is able to discover the Wallet, regardless of which code executes first, the Wallet code or the DApp code. + +## Rationale + +The previous proposal introduced mechanisms that relied on a single, mutable window object that could be overwritten by multiple parties. We opted for an event-based approach to avoid the race conditions, the namespace collisions, and the potential for "pollution" attacks on a shared mutable object; the event-based orchestration creates a bidirectional communication channel between wallet and dapp that can be re-orchestrated over time. + +To follow the Javascript event name conventions, the names are written in present tense and are prefixed with the number of this document (`EIP6963`). + +### Interfaces + +Standardizing an interface for provider information (`EIP6963ProviderInfo`) allows a DApp to determine all information necessary to populate a user-friendly wallet selection modal. This is particularly useful for DApps that rely on libraries such as Web3Modal, RainbowKit, Web3-Onboard, or ConnectKit to programmatically generate such selection modals. + +Regarding the announced provider interface (`EIP6963ProviderDetail`), it was important to leave the [EIP-1193](./eip-1193.md) provider interface untouched for backwards compatibility; this allows conformant DApps to interface with wallets conforming to either, and for Wallets conformant to this spec to still inject [EIP-1193](./eip-1193.md) providers for legacy DApps. Note that a legacy dapp or a DApp conformant with this spec connecting to a legacy wallet cannot guarantee the correct wallet will be selected if multiple are present. + +## Backwards Compatibility + +This EIP doesn't require supplanting `window.ethereum`, so it doesn't directly break existing applications that cannot update to this method of Wallet discovery. However, it is RECOMMENDED DApps implement this EIP to ensure discovery of multiple Wallet Providers and SHOULD disable `window.ethereum` usage except as a fail-over when discovery fails. Similarly, Wallets SHOULD keep compatibility of `window.ethereum` to ensure backwards compatibility for DApps that have not implemented this EIP. In order to prevent the previous issues of namespace collisions, it's also RECOMMENDED that wallets inject their provider object under a wallet specific namespace then proxy the object into the `window.ethereum` namespace. + +## Reference Implementation + +### Wallet Provider + +Here is a reference implementation for an injected script by a Wallet Provider to support this new interface in parallel with the existing pattern. + +```typescript +function onPageLoad() { + let provider: EIP1193Provider; + + window.ethereum = provider; + + function announceProvider() { + const info: EIP6963ProviderInfo = { + uuid: "350670db-19fa-4704-a166-e52e178b59d2", + name: "Example Wallet", + icon: "data:image/svg+xml,", + rdns: "com.example.wallet" +}; + window.dispatchEvent( + new CustomEvent("eip6963:announceProvider", { + detail: Object.freeze({ info, provider }), + }) + ); + } + + window.addEventListener( + "eip6963:requestProvider", + (event: EIP6963RequestProviderEvent) => { + announceProvider(); + } + ); + + announceProvider(); +} +``` + +### DApp implementation + +Here is a reference implementation for a DApp to display and track multiple Wallet Providers that are injected by browser extensions. + +```typescript +const providers: EIP6963ProviderDetail[]; + +function onPageLoad() { + + window.addEventListener( + "eip6963:announceProvider", + (event: EIP6963AnnounceProviderEvent) => { + providers.push(event.detail); + } + ); + + window.dispatchEvent(new Event("eip6963:requestProvider")); +} +``` + +## Security Considerations + +### EIP-1193 Security considerations + +The security considerations of [EIP-1193](./eip-1193.md) apply to this EIP. Implementers are expected to consider and follow the guidance of the providers they're utilizing as well. + +### Prototype Pollution of Wallet Provider objects + +Browser extensions, and therefore Wallet extensions, are able to modify the contents of the page and the Provider object by design. The provider objects of various Wallets are considered a highly trusted interface to communicate transaction data. In order to prevent the page or various other extensions from modifying the interaction between the DApp and the Wallet in an unexpected way, the best practice is to "freeze" the provider discovery object by utilizing `object.freeze()` on the `EIP1193Provider` object before the wallet dispatches it in the `eip6963:announceProvider` Event. However, there are difficulties that can occur around web compatibility where pages need to monkey patch the object. In scenarios like this there's a tradeoff that needs to be made between security and web compatibility that Wallet implementers are expected to consider. + +### Wallet Imitation and Manipulation + +Similarly so, DApps are expected to actively detect for misbehavior of properties or functions being modified in order to tamper with or modify other wallets. One way this can be easily achieved is to look for when the `uuid` property within two `EIP6963ProviderInfo` objects match. DApps and DApp discovery libraries are expected to consider other potential methods that the `EIP6963ProviderInfo` objects are being tampered with and consider additional mitigation techniques to prevent this as well in order to protect the user. + +### Prevent SVG Javascript Execution + +The use of SVG images introduces a cross-site scripting risk as they can include JavaScript code. This Javascript executes within the context of the page and can therefore modify the page or the contents of the page. So when considering the experience of rendering the icons, DApps need to take into consideration how they'll approach handling these concerns in order to prevent an image being used as an obfuscation technique to hide malicious modifications to the page or to other wallets. + +### Prevent Wallet Fingerprinting + +One advantage to the concurrency Event loop utilized by this design is that it operates in a manner where either the DApp or the Wallet can initiate the flow to announce a provider. For this reason, Wallet implementers can now consider whether or not they wish to announce themselves to all pages or attempt alternative means in order to reduce the ability for a user to be fingerprinted by the injection of the `window.ethereum` object. Some examples, of alternative flows to consider would be to wait to inject the provider object until the DApp has announced the `eip6963:requestProvider`. At that point, the wallet can initiate a UI consent flow to ask the user if they would like to share their wallet address. This allows for the Wallet to enable the option of a "private connect" feature. However, if this approach is taken, Wallets must also consider how they intend to support backwards compatibility with a DApp that does not support this EIP. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + + +[RFC-1034]: https://www.rfc-editor.org/rfc/rfc1034 +[RFC-2119]: https://www.rfc-editor.org/rfc/rfc2119 +[RFC-2397]: https://www.rfc-editor.org/rfc/rfc2397 +[RFC-3986]: https://www.rfc-editor.org/rfc/rfc3986 +[RFC-4122]: https://www.rfc-editor.org/rfc/rfc4122 diff --git a/EIPS/eip-6968.md b/EIPS/eip-6968.md new file mode 100644 index 00000000000000..353cea8aa60fc4 --- /dev/null +++ b/EIPS/eip-6968.md @@ -0,0 +1,94 @@ +--- +eip: 6968 +title: Contract Secured Revenue on an EVM based L2 +description: Contract Secured Revenue on an EVM based L2 +author: Zak Cole , Zak Cole (@zscole), Kevin Owocki , lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-6968-generalized-csr-protocol/14178 +status: Stagnant +type: Standards Track +category: Core +created: 2023-05-01 +--- + +## Abstract + +Contract Secured Revenue (CSR) allows smart contract developers to claim a percentage of all transaction fees paid by users when interacting with their smart contracts. + +This EIP proposes the introduction of CSR on EVM-based L2s which would provide smart contract developers who deploy on L2s access to revenue streams and/or public goods. + +## Motivation + +Using protocol rewards of an L1 to fund smart contract development would be a big change to the way the current market works. This EIP *does not* advocate for any changes to the existing Ethereum L1. + +This EIP does advocate that L2s could begin to experiment with Contract Secured Revenue as a means of: + +1. creating a new revenue stream for smart contract developers +2. creating a new way of funding public goods +3. creating incentives for developers to deploy their dapps on your network + +## Specification + +### Parameters + +| Constant | Value | +|---|---| +| REVENUE_SHARE_QUOTIENT | 5 | + +### Fee Mechanism + +The current [EIP-1559](./eip-1559.md) fee behavior is modified so that `header.base_fee_per_gas * REVENUE_SHARE_QUOTIENT` per gas is reallocated proportionally, based on gas used, to each contract executed during the transaction. + +Implicitly, this means that no fees are redistributed to externally owned accounts (EOA). + +#### Gas Tracking + +In order to fairly distribute the fee revenue, a new transaction-wide gas tracker is defined. + +When executing a block, maintain a mapping `gas_used_by_address` of `address` to `uint64`. This will track the amount of gas used by each address. For every EVM instruction that does not instantiate a new execution frame (e.g. `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE`, and `CREATE2`), add the cost of the instruction to the address' current sum in the mapping. + +For EVM instructions which do instantiate new frames, greater care must be taken to determine the cost of the instruction to the calling frame. For simplicity, this cost is defined to be the total cost of the operation minus the amount of gas passed to the child frame. The gas passed to the child frame is determined via [EIP-150](./eip-150.md). The computed cost is added to the address' current sum in the mapping. + +Additionally: + +- If the address does not exist in the mapping, it's total gas used is `0`. +- If the instructions throws an out-of-gas (OOG) error, all remaining gas allocated to execution frame is added to the current total gas used by the address. +- No other exceptional halt adds remaining gas to the counter for the address where the halt occurred. + +#### Setting Revenue Recipient + +Revenue recipients are tracked via a new transaction wide mapping `revenue_recipient` of `address` to `address`. The default value for every key is the key itself. For example, unless set otherwise, the key `0xdead...beef` maps to the value `0xdead...beef`. + +To set a different revenue recipient, a new instruction `SETREVENUERECIPIENT` is introduced with the opcode `0x49`. The operation takes `1` stack element as input and outputs `0` stack elements. + +The `20` least significant bytes of the input stack element is the address of the new revenue recipient for the instruction's caller. The `revenue_recipient` entry is updated to reflect this. + +The instruction costs `3` gas. + +#### Dispersing Revenue + +After a transaction completes, for every element (`addr`, `gas_used`) in `gas_used_by_address`, increase the balance of `revenue_recipient[addr]` by `gas_used * (header.base_fee_per_gas // REVENUE_SHARE_QUOTIENT)` + +## Rationale + +### Tracking Gas Proportionally + +A simpler mechanism would be to send the full transaction revenue to the `to` value of the transaction. This, however, does not accurately reward the composition of many different smart contracts and applications. Additionally, it is not compatible with smart contract wallets which, by definition, are often the first destination of a transaction. + +Maintaining a transaction wide tracker of gas uses makes it possible to distribute revenue to contracts which are genuinely the most utilized. + +### Ephemeral Revenue Recipient Mapping + +Constructing the revenue recipient mapping ephemerally during each transaction appears inefficient on the surface. This value is expected to be relatively static and even if it did need to change, the change could be facilitated by the recipient contract. + +Unfortunately such a change is much more invasive for the EVM. The recipient value would need to be stored somewhere. This would require a modification to the account structure in the state trie. Also, the recipient value would need to be set at some point. This would necessitate either a modification to the `CREATE*` opcodes or a new opcode, similar to `SETREVENUERECIPIENT`, that would be called by initcode to "initialize" the recipient value. + +## Security Considerations + +### Increased Max Block Size/Complexity + +Similar to EIP-1559, we must consider the effects this will have on block size. Depending on the method by which this is implemented, it could increase maximum block size in the event that a significant number of contracts opt-in to CSR. + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-698.md b/EIPS/eip-698.md index 75fa07b0697c37..df6efc94965fba 100644 --- a/EIPS/eip-698.md +++ b/EIPS/eip-698.md @@ -48,7 +48,7 @@ Where:`µ's[0] ≡ IHR` ### Contract Mining Pools -For distributed consensus systems(staking pools and mining pools) ad hoc groups combine resources in order to reduce variance in payouts. Broadly, pool operations function by allowing a collective of miners / stakers to verify their contribution to solving PoW or staking share by periodically submitting solutions which are is representative of the miners probability of finding a true block. +For distributed consensus systems(staking pools and mining pools) ad hoc groups combine resources in order to reduce variance in payouts. Broadly, pool operations function by allowing a collective of miners / stakers to verify their contribution to solving PoW or staking share by periodically submitting solutions which are representative of the miners probability of finding a true block. In all these schemes `B` stands for a block reward minus pool fee and `p` is a probability of finding a block in a share attempt ( `p=1/D`, where `D` is current block difficulty). diff --git a/EIPS/eip-6981.md b/EIPS/eip-6981.md new file mode 100644 index 00000000000000..7979de61c17819 --- /dev/null +++ b/EIPS/eip-6981.md @@ -0,0 +1,7 @@ +--- +eip: 6981 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6981.md diff --git a/EIPS/eip-6982.md b/EIPS/eip-6982.md new file mode 100644 index 00000000000000..dd015d5e24d493 --- /dev/null +++ b/EIPS/eip-6982.md @@ -0,0 +1,7 @@ +--- +eip: 6982 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6982.md diff --git a/EIPS/eip-6988.md b/EIPS/eip-6988.md new file mode 100644 index 00000000000000..62c2bcaa465a1a --- /dev/null +++ b/EIPS/eip-6988.md @@ -0,0 +1,60 @@ +--- +eip: 6988 +title: Elected block proposer has not been slashed +description: Prevents a slashed validator from being elected as a block proposer +author: Mikhail Kalinin (@mkalinin) +discussions-to: https://ethereum-magicians.org/t/eip-6988-elected-block-proposer-has-not-been-slashed/14349 +status: Stagnant +type: Standards Track +category: Core +created: 2023-05-04 +--- + +## Abstract + +Introduces a modification to the consensus layer specification which ensures that slashed validator cannot be elected as block proposer. + +## Motivation + +A block proposed by a slashed validator is rejected by the corresponding validity check in the [`phase0/process_block_header`](https://github.com/ethereum/consensus-specs/blob/3115d1140b23dd4c9c23fbd9e2428186cf816bde/specs/phase0/beacon-chain.md#block-header) function as defined in the consensus layer specification. + +At the same time the definition of the [`phase0/compute_proposer_index`](https://github.com/ethereum/consensus-specs/blob/3115d1140b23dd4c9c23fbd9e2428186cf816bde/specs/phase0/beacon-chain.md#compute_proposer_index) allows for a slashed validator to be elected as a proposer. This contradiction effectively leads to a missed proposal if it is supposed to be made by a slashed validator. + +The impact of the proposed fix in the case of a single slashing on Ethereum Mainnet is negligible but it becomes significant in the case of correlated slashings. For instance, a correlated slashing of `1/10th` of a validator set can lead to `1/10th` of missed proposals in a number of epochs after the slashing. + +## Specification + +Specification of the proposed change can be found in [`/_features/eip6988/beacon-chain.md`](https://github.com/ethereum/consensus-specs/blob/0ad3972725e7c22e8edf3bab2dd7730acbe3c272/specs/_features/eip6988/beacon-chain.md). + +## Rationale + +### Modifying `get_beacon_proposer_index` + +This function is modified to read a proposer index from a beacon state if a slot of a latest block header is the same as the `state.slot`. + +This modification is done to make the function return correct proposer index in the case when the proposer of a given block is being slashed during processing of the block. + +## Backwards Compatibility + +This fix changes proposer election mechanism in a backwards incompatible way and requires a hard fork to be deployed. + +## Test Cases + +The following test cases were added to cover this change: + +* [`test_slashed_proposer_rewarded_for_sync_aggregate_inclusion`](https://github.com/ethereum/consensus-specs/blob/0ad3972725e7c22e8edf3bab2dd7730acbe3c272/tests/core/pyspec/eth2spec/test/altair/block_processing/sync_aggregate/test_process_sync_aggregate.py#L712) +* [`test_slashed_proposer_rewarded_for_attestation_inclusion`](https://github.com/ethereum/consensus-specs/blob/0ad3972725e7c22e8edf3bab2dd7730acbe3c272/tests/core/pyspec/eth2spec/test/altair/block_processing/test_process_attestation.py#L17) +* [`test_slashed_validator_not_elected_for_proposal`](https://github.com/ethereum/consensus-specs/blob/0ad3972725e7c22e8edf3bab2dd7730acbe3c272/tests/core/pyspec/eth2spec/test/eip6988/unittests/validator/test_validator.py#L9) +* [`test_slashed_validator_elected_for_proposal`](https://github.com/ethereum/consensus-specs/blob/0ad3972725e7c22e8edf3bab2dd7730acbe3c272/tests/core/pyspec/eth2spec/test/phase0/unittests/validator/test_validator_unittest.py#L520) + +## Reference Implementation + +Reference implementation is in the same place as [Specification](#specification). + +## Security Considerations + +There are no observed security issues introduced by the proposed change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-6997.md b/EIPS/eip-6997.md new file mode 100644 index 00000000000000..6aa6b6cd7c370b --- /dev/null +++ b/EIPS/eip-6997.md @@ -0,0 +1,7 @@ +--- +eip: 6997 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-6997.md diff --git a/EIPS/eip-7002.md b/EIPS/eip-7002.md new file mode 100644 index 00000000000000..11a709c46fe658 --- /dev/null +++ b/EIPS/eip-7002.md @@ -0,0 +1,597 @@ +--- +eip: 7002 +title: Execution layer triggerable withdrawals +description: Allow validators to trigger exits and partial withdrawals via their execution layer (0x01) withdrawal credentials +author: Danny Ryan (@djrtwo), Mikhail Kalinin (@mkalinin), Ansgar Dietrichs (@adietrichs), Hsiao-Wei Wang (@hwwhww), lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-7002-execution-layer-triggerable-exits/14195 +status: Review +type: Standards Track +category: Core +created: 2023-05-09 +requires: 7685 +--- + +## Abstract + +Adds a new mechanism to allow validators to trigger withdrawals and exits from their execution layer (0x01) withdrawal credentials. + +These new execution layer exit messages are appended to the execution layer block and then processed by the consensus layer. + +## Motivation + +Validators have two keys -- an active key and a withdrawal credential. The active key takes the form of a BLS key, whereas the withdrawal credential can either be a BLS key (0x00) or an execution layer address (0x01). The active key is "hot", actively signing and performing validator duties, whereas the withdrawal credential can remain "cold", only performing limited operations in relation to withdrawing and ownership of the staked ETH. Due to this security relationship, the withdrawal credential ultimately is the key that owns the staked ETH and any rewards. + +As currently specified, only the active key can initiate a validator exit. This means that in any non-standard custody relationships (i.e. active key is separate entity from withdrawal credentials), that the ultimate owner of the funds -- the possessor of the withdrawal credentials -- cannot independently choose to exit and begin the withdrawal process. This leads to either trust issues (e.g. ETH can be "held hostage" by the active key owner) or insufficient work-arounds such as pre-signed exits. Additionally, in the event that active keys are lost, a user should still be able to recover their funds by using their cold withdrawal credentials. + +To ensure that the withdrawal credentials (owned by both EOAs and smart contracts) can trustlessly control the destiny of the staked ETH, this specification enables exits triggerable by 0x01 withdrawal credentials. + +Note, 0x00 withdrawal credentials can be changed into 0x01 withdrawal credentials with a one-time signed message. Thus any functionality enabled for 0x01 credentials is defacto enabled for 0x00 credentials. + +## Specification + +### Constants + +| Name | Value | Comment | +| - | - | - | +|`FORK_TIMESTAMP` | *TBD* | Mainnet | + +### Configuration + +| Name | Value | Comment | +| - | - | - | +| `WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS` | `0x00A3ca265EBcb825B45F985A16CEFB49958cE017` | Where to call and store relevant details about exit / partial withdrawal mechanism | +| `WITHDRAWAL_REQUEST_TYPE` | `0x01` | The [EIP-7685](./eip-7685.md) type prefix for withdrawal request | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | Address used to invoke system operation on contract +| `EXCESS_WITHDRAWAL_REQUESTS_STORAGE_SLOT` | 0 | | +| `WITHDRAWAL_REQUEST_COUNT_STORAGE_SLOT` | 1 | | +| `WITHDRAWAL_REQUEST_QUEUE_HEAD_STORAGE_SLOT` | 2 | Pointer to head of the withdrawal request message queue | +| `WITHDRAWAL_REQUEST_QUEUE_TAIL_STORAGE_SLOT` | 3 | Pointer to the tail of the withdrawal request message queue| +| `WITHDRAWAL_REQUEST_QUEUE_STORAGE_OFFSET` | 4 | The start memory slot of the in-state withdrawal request message queue| +| `MAX_WITHDRAWAL_REQUESTS_PER_BLOCK` | 16 | Maximum number of withdrawal requests that can be dequeued into a block | +| `TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK` | 2 | | +| `MIN_WITHDRAWAL_REQUEST_FEE` | 1 | | +| `WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION` | 17 | | + +### Execution layer + +#### Definitions + +* **`FORK_BLOCK`** -- the first block in a blockchain with the `timestamp` greater or equal to `FORK_TIMESTAMP`. + +#### Withdrawal request operation + +The new withdrawal request operation is an [EIP-7685](./eip-7685.md) request +with type `0x01` and consists of the following fields: + +1. `source_address`: `Bytes20` +2. `validator_pubkey`: `Bytes48` +3. `amount:` `uint64` + +The [EIP-7685](./eip-7685) encoding of a withdrawal request **MUST** be computed as the follows: + +```python +encoded = WITHDRAWAL_REQUEST_TYPE ++ rlp([source_address, validator_pubkey, amount]) +``` + +#### Withdrawal Request Contract + +The contract has three different code paths, which can be summarized at a high level as follows: + +1. Add withdrawal request - requires a `56` byte input, the validator's public + key concatenated with `uint64` amount value. +2. Excess withdrawal requests getter - if the input length is zero, return the current excess withdrawal requests count. +3. System process - if called by system address, pop off the withdrawal requests for the current block from the queue. + +##### Add Withdrawal Request + +If call data input to the contract is exactly `56` bytes, perform the following: + +* Ensure enough ETH was sent to cover the current withdrawal request fee (`check_fee()`) +* Increase withdrawal request count by 1 for the current block (`increment_count()`) +* Insert a withdrawal request into the queue for the source address and validator pubkey (`insert_withdrawal_request_into_queue()`) + +Specifically, the functionality is defined in pseudocode as the function `add_withdrawal_request()`: + +```python +def add_withdrawal_request(Bytes48: validator_pubkey, uint64: amount): + """ + Add withdrawal request adds new request to the withdrawal request queue, so long as a sufficient fee is provided. + """ + + # Verify sufficient fee was provided. + fee = get_fee() + require(msg.value >= fee, 'Insufficient value for fee') + + # Increment withdrawal request count. + count = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_COUNT_STORAGE_SLOT) + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_COUNT_STORAGE_SLOT, count + 1) + + # Insert into queue. + queue_tail_index = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_TAIL_STORAGE_SLOT) + queue_storage_slot = WITHDRAWAL_REQUEST_QUEUE_STORAGE_OFFSET + queue_tail_index * 3 + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot, msg.sender) + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 1, validator_pubkey[0:32]) + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2, validator_pubkey[32:48] ++ amount) + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_TAIL_STORAGE_SLOT, queue_tail_index + 1) +``` + +###### Fee calculation + +The following pseudocode can compute the cost an individual withdrawal request, given a certain number of excess withdrawal requests. + +```python +def get_fee() -> int: + excess = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, EXCESS_WITHDRAWAL_REQUESTS_STORAGE_SLOT) + return fake_exponential( + MIN_WITHDRAWAL_REQUEST_FEE, + excess, + WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION + ) + +def fake_exponential(factor: int, numerator: int, denominator: int) -> int: + i = 1 + output = 0 + numerator_accum = factor * denominator + while numerator_accum > 0: + output += numerator_accum + numerator_accum = (numerator_accum * numerator) // (denominator * i) + i += 1 + return output // denominator +``` + +##### Excess Withdrawal Requests Getter + +When the input to the contract is length zero, interpret this as a get request for the current excess withdrawal requests count. + +```python +def get_excess_withdrawal_requests(): + count = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, EXCESS_WITHDRAWAL_REQUESTS_STORAGE_SLOT) + return count +``` + +##### System Call + +At the end of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e. after processing all transactions and after performing the block body withdrawal requests validations), call the contract as `SYSTEM_ADDRESS` and perform the following: + +* The contract's queue is updated based on withdrawal requests dequeued and the withdrawal requests queue head/tail are reset if the queue has been cleared (`dequeue_withdrawal_requests()`) +* The contract's excess withdrawal requests are updated based on usage in the current block (`update_excess_withdrawal_requests()`) +* The contract's withdrawal requests count is reset to 0 (`reset_withdrawal_requests_count()`) + +Specifically, the functionality is defined in pseudocode as the function `read_withdrawal_requests()`: + +```python +################### +# Public function # +################### + +def read_withdrawal_requests(): + reqs = dequeue_withdrawal_requests() + update_excess_withdrawal_requests() + reset_withdrawal_requests_count() + return reqs + +########### +# Helpers # +########### + +class ValidatorWithdrawalRequest(object): + source_address: Bytes20 + validator_pubkey: Bytes48 + amount: uint64 + +def dequeue_withdrawal_requests(): + queue_head_index = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_HEAD_STORAGE_SLOT) + queue_tail_index = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_TAIL_STORAGE_SLOT) + num_in_queue = queue_tail_index - queue_head_index + num_dequeued = min(num_in_queue, MAX_WITHDRAWAL_REQUESTS_PER_BLOCK) + + reqs = [] + for i in range(num_dequeue): + queue_storage_slot = WITHDRAWAL_REQUEST_QUEUE_STORAGE_OFFSET + (queue_head_index + i) * 3 + source_address = address(sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot)[0:20]) + validator_pubkey = ( + sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 1)[0:32] + sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2)[0:16] + ) + amount = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2)[16:24] + req = ValidatorWithdrawalRequest( + source_address=Bytes20(source_address), + validator_pubkey=Bytes48(validator_pubkey), + amount=uint64(amount) + ) + reqs.append(req) + + new_queue_head_index = queue_head_index + num_dequeued + if new_queue_head_index == queue_tail_index: + # Queue is empty, reset queue pointers + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_HEAD_STORAGE_SLOT, 0) + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_TAIL_STORAGE_SLOT, 0) + else: + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_QUEUE_HEAD_STORAGE_SLOT, new_queue_head_index) + + return reqs + +def update_excess_withdrawal_requests(): + previous_excess = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, EXCESS_WITHDRAWAL_REQUESTS_STORAGE_SLOT) + count = sload(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_COUNT_STORAGE_SLOT) + + new_excess = 0 + if previous_excess + count > TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK: + new_excess = previous_excess + count - TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK + + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, EXCESS_WITHDRAWAL_REQUESTS_STORAGE_SLOT, new_excess) + +def reset_withdrawal_requests_count(): + sstore(WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_COUNT_STORAGE_SLOT, 0) +``` + +Each withdrawal request must appear in the EIP-7685 requests list in the order they are returned from `dequeue_withdrawal_requests()`. + +##### Bytecode + +```asm +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x90 +jumpi + +calldatasize +iszero +iszero +push1 0x28 +jumpi + +push0 +sload +push0 +mstore +push1 0x20 +push0 +return + +jumpdest +calldatasize +push1 0x38 +eq +iszero +push2 0x012e +jumpi + +push1 0x11 +push0 +sload +push1 0x01 +dup3 +mul +push1 0x01 +swap1 +push0 + +jumpdest +push0 +dup3 +gt +iszero +push1 0x59 +jumpi + +dup2 +add +swap1 +dup4 +mul +dup5 +dup4 +mul +swap1 +div +swap2 +push1 0x01 +add +swap2 +swap1 +push1 0x3e +jump + +jumpdest +swap1 +swap4 +swap1 +div +callvalue +lt +push2 0x012e +jumpi + +push1 0x01 +sload +push1 0x01 +add +push1 0x01 +sstore +push1 0x03 +sload +dup1 +push1 0x03 +mul +push1 0x04 +add +caller +dup2 +sstore +push1 0x01 +add +push0 +calldataload +dup2 +sstore +push1 0x01 +add +push1 0x20 +calldataload +swap1 +sstore +push1 0x01 +add +push1 0x03 +sstore +stop + +jumpdest +push1 0x03 +sload +push1 0x02 +sload +dup1 +dup3 +sub +dup1 +push1 0x10 +gt +push1 0xa4 +jumpi + +pop +push1 0x10 + +jumpdest +push0 + +jumpdest +dup2 +dup2 +eq +push1 0xdd +jumpi + +dup1 +push1 0x4c +mul +dup4 +dup3 +add +push1 0x03 +mul +push1 0x04 +add +dup1 +sload +swap1 +push1 0x01 +add +dup1 +sload +swap1 +push1 0x01 +add +sload +swap2 +push1 0x60 +shl +dup4 +mstore +dup3 +push1 0x14 +add +mstore +swap1 +push1 0x34 +add +mstore +push1 0x01 +add +push1 0xa6 +jump + +jumpdest +swap2 +add +dup1 +swap3 +eq +push1 0xed +jumpi + +swap1 +push1 0x02 +sstore +push1 0xf8 +jump + +jumpdest +swap1 +pop +push0 +push1 0x02 +sstore +push0 +push1 0x03 +sstore + +jumpdest +push0 +sload +dup1 +push2 0x049d +eq +iszero +push2 0x0107 +jumpi + +pop +push0 + +jumpdest +push1 0x01 +sload +push1 0x02 +dup3 +dup3 +add +gt +push2 0x011c +jumpi + +pop +pop +push0 +push2 0x0122 +jump + +jumpdest +add +push1 0x02 +swap1 +sub + +jumpdest +push0 +sstore +push0 +push1 0x01 +sstore +push1 0x4c +mul +push0 +return + +jumpdest +push0 +push0 +revert +``` + +##### Deployment + +The withdrawal requests contract is deployed like any other smart contract. A special synthetic address is generated by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x61049d5f5561013280600f5f395ff33373fffffffffffffffffffffffffffffffffffffffe146090573615156028575f545f5260205ff35b366038141561012e5760115f54600182026001905f5b5f82111560595781019083028483029004916001019190603e565b90939004341061012e57600154600101600155600354806003026004013381556001015f3581556001016020359055600101600355005b6003546002548082038060101160a4575060105b5f5b81811460dd5780604c02838201600302600401805490600101805490600101549160601b83528260140152906034015260010160a6565b910180921460ed579060025560f8565b90505f6002555f6003555b5f548061049d141561010757505f5b60015460028282011161011c5750505f610122565b01600290035b5f555f600155604c025ff35b5f5ffd", + "v": "0x1b", + "r": "0x539", + "s": "0xaba653c9d105790c", + "hash": "0xad43639db86f2d26fa3f0d10b0bfebb64773167258e5e75668fe98070fe70465" +} +``` + +``` +Sender: 0x4951E1ff64Fe2C88effd8a98be863d6Db24aDDdf +Address: 0x00A3ca265EBcb825B45F985A16CEFB49958cE017 +``` + +### Consensus layer + +[Full specification](https://github.com/ethereum/consensus-specs/blob/7bf43d1bc4fdb91059f0e6f4f7f0f3349b144950/specs/electra/beacon-chain.md) + +Sketch of spec: + +* New operation `ExecutionLayerWithdrawalRequest` +* Will show up in `ExecutionPayload` as an SSZ List bound by length `MAX_WITHDRAWAL_REQUESTS_PER_BLOCK` +* New function that has similar functionality to `process_voluntary_exit` but can fail validations (e.g. validator is already exited) without the block failing (similar to deposit coming from EL) +* This function is called in `process_operations` for each `ExecutionLayerWithdrawalRequest` found in the `ExecutionPayload` + +## Rationale + +### `validator_pubkey` field + +Multiple validators can utilize the same execution layer withdrawal credential, thus the `validator_pubkey` field is utilized to disambiguate which validator is being exited. + +Note, `validator_index` also disambiguates validators. + +### Message queue + +The contract maintains and in-state queue of withdrawal request messages to be dequeued each block into the block and thus into the execution layer. + +The number of withdrawal requests that can be passed into the consensus layer are bound by `MAX_WITHDRAWAL_REQUESTS_PER_BLOCK` to bound the load both on the block size as well as on the consensus layer processing. `16` has been chosen for `MAX_WITHDRAWAL_REQUESTS_PER_BLOCK` to be in line with the bounds of similar operations on the beacon chain -- e.g. `VoluntaryExit` and `Deposit`. + +Although there is a maximum number of withdrawal requests that can passed to the consensus layer each block, the execution layer gas limit can provide for far more calls to the withdrawal request predeploy contract at each block. The queue then allows for these calls to successfully be made while still maintaining a system rate limit. + +The alternative design considered was to have calls to the contract fail after `MAX_WITHDRAWAL_REQUESTS_PER_BLOCK` successful calls were made within the context of a single block. This would eliminate the need for the message queue, but would come at the cost of a bad UX of contract call failures in times of high exiting. The complexity to mitigate this bad UX is relatively low and is currently favored. + +### Utilizing `CALL` to return excess payment + +Calls to the contract require a fee payment defined by the current state of the contract. Smart contracts can easily perform a read/calculation to pay the precise fee, whereas EOAs will likely need to compute and send some amount over the current fee at time of signing the transaction. This will result in EOAs having fee payment overages in the normal case. These should be returned to the caller. + +There are two potential designs to return excess fee payments to the caller (1) use an EVM `CALL` with some gas stipend or (2) have special functionality to allow the contract to "credit" the caller's account with the excess fee. + +Option (1) has been selected in the current specification because it utilizes less exceptional functionality and is likely simpler to implement and ensure correctness. The current version sends a gas stipen of 2300. This is following the (outdated) solidity pattern primarily to simplify contract gas accounting (allowing it to be a fixed instead of dynamic cost). The `CALL` could forward the maximum allowed gas but would then require the cost of the contract to be dynamic. + +Option (2) utilizes custom logic (exceptional to base EVM logic) to credit the excess back to the callers balance. This would potentially simplify concerns around contract gas costs/metering, but at the cost of non-standard EVM complexity. We are open to this path, but want to solicit more input before writing it into the specification. + +### Rate limiting using a fee + +Transactions are naturally rate-limited in the execution layer via the gas limit, but an adversary willing to pay market-rate gas fees (and potentially utilize builder markets to pay for front-of-block transaction inclusion) can fill up the exit operation limits for relatively cheap, thus griefing honest validators that want to make a withdrawal request. + +There are two general approaches to combat this griefing -- (a) only allow validators to send such messages and with a limit per time period or (b) utilize an economic method to make such griefing increasingly costly. + +Method (a) (not used in this EIP) would require [EIP-4788](./eip-4788.md) (the `BEACON_ROOT` opcode) against which to prove withdrawal credentials in relation to validator pubkeys as well as a data-structure to track requests per-unit-time (e.g. 4 months) to ensure that a validator cannot grief the mechanism by submitting many requests. The downsides of this method are that it requires another cross-layer EIP and that it is of higher cross-layer complexity (e.g. care that might need to be taken in future upgrades if, for example, the shape of the merkle tree of `BEACON_ROOT` changes, then the contract and proof structure might need to be updated). + +Method (b) has been utilized in this EIP to eliminate additional EIP requirements and to reduce cross-layer complexity to allow for correctness of this EIP (now and in the future) to be easier to analyze. The [EIP-1559](./eip-1559.md)-style mechanism with a dynamically adjusting fee mechanism allows for users to pay `MIN_WITHDRAWAL_REQUEST_FEE` for withdrawal requests in the normal case (fewer than 2 per block on average), but scales the fee up exponentially in response to high usage (i.e. potential abuse). + +### `TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK` configuration value + +`TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK` has been selected as `2` such that even if all ETH is staked (~120M ETH -> 3.75M validators), the 64 validator per epoch target (`2 * 32 slots`) still exceeds the per-epoch exit churn limit on the consensus layer (defined by `get_validator_churn_limit()`) at such values -- 57 validators per epoch (`3.75M // 65536`). + +### Fee update rule + +The fee update rule is intended to approximate the formula `fee = MIN_WITHDRAWAL_REQUEST_FEE * e**(excess / WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION)`, where `excess` is the total "extra" amount of withdrawal requests that the chain has processed relative to the "targeted" number (`TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK` per block). + +Like EIP-1559, it’s a self-correcting formula: as the excess goes higher, the `fee` increases exponentially, reducing usage and eventually forcing the excess back down. + +The block-by-block behavior is roughly as follows. If block `N` processes `X` requests, then at the end of block `N` `excess` increases by `X - TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK`, and so the `fee` in block `N+1` increases by a factor of `e**((X - TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK) / WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION)`. Hence, it has a similar effect to the existing EIP-1559, but is more "stable" in the sense that it responds in the same way to the same total withdrawal requests regardless of how they are distributed over time. + +The parameter `WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION` controls the maximum downwards rate of change of the blob gas price. It is chosen to target a maximum downwards change rate of `e(TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK / WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION) ≈ 1.125` per block. The maximum upwards change per block is `e((MAX_WITHDRAWAL_REQUESTS_PER_BLOCK - TARGET_WITHDRAWAL_REQUESTS_PER_BLOCK) / WITHDRAWAL_REQUEST_FEE_UPDATE_FRACTION) ≈ 2.279`. + +### Withdrawal requests inside of the block + +Withdrawal requests are placed into the actual body of the block (and execution payload in the consensus layer). + +There is a strong design requirement that the consensus layer and execution layer can execute independently of each other. This means, in this case, that the consensus layer cannot rely upon a synchronous call to the execution layer to get the required withdrawal requests for the current block. Instead, the requests must be embedded in the shared data-structure of the execution payload such that if the execution layer is offline, the consensus layer still has the requisite data to fully execute the consensus portion of the state transition function. + +## Backwards Compatibility + +This EIP introduces backwards incompatible changes to the block structure and block validation rule set. But neither of these changes break anything related to current user activity and experience. + +## Security Considerations + +### Impact on existing custody relationships + +There might be existing custody relationships and/or products that rely upon the assumption that the withdrawal credentials *cannot* trigger a withdrawal request. We are currently confident that the additional withdrawal credentials feature does not impact the security of existing validators because: + +1. The withdrawal credentials ultimately own the funds so allowing them to exit staking is natural with respect to ownership. +2. We are currently not aware of any such custody relationships and/or products that do rely on the lack of this feature. + +In the event that existing validators/custodians rely on this, then the validators can be exited and restaked utilizing 0x01 withdrawal credentials pointing to a smart contract that simulates this behaviour. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7007.md b/EIPS/eip-7007.md new file mode 100644 index 00000000000000..5880bff0be1a64 --- /dev/null +++ b/EIPS/eip-7007.md @@ -0,0 +1,7 @@ +--- +eip: 7007 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7007.md diff --git a/EIPS/eip-7015.md b/EIPS/eip-7015.md new file mode 100644 index 00000000000000..124ef7a9b750a5 --- /dev/null +++ b/EIPS/eip-7015.md @@ -0,0 +1,7 @@ +--- +eip: 7015 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7015.md diff --git a/EIPS/eip-7039.md b/EIPS/eip-7039.md new file mode 100644 index 00000000000000..fe5e7c16015ca0 --- /dev/null +++ b/EIPS/eip-7039.md @@ -0,0 +1,101 @@ +--- +eip: 7039 +title: Scheme-Handler Discovery Option for Wallets +description: Using custom protocol handlers to initiate connections between web pages and wallets. +author: Sam Wilson (@SamWilsn) +discussions-to: https://ethereum-magicians.org/t/shadow-a-scheme-handler-discovery-option-for-wallets/14330 +status: Draft +type: Standards Track +category: Interface +created: 2023-05-15 +requires: 1193 +--- + +## Abstract + +This proposal (affectionately known as SHADOW) is an alternative to [EIP-1193](./eip-1193.md) for wallet discovery in web browsers that requires no special permissions. Web pages intending to open a connection to a wallet inject an `iframe` tag pointing at a well-known scheme. Communication between the page and the wallet uses the `postMessage` API. + +## Motivation + +Current wallet discovery methods (eg. `window.ethereum`) only support one active wallet at a time, and require browser extensions to request broad permissions to modify web pages. + +Ideally users should be able to have multiple wallets active, and choose between them at runtime. This not only results in an improved user experience but also reduces the barrier to entry for new browser extensions as users are no longer forced to only install one browser extension at a time. + +With SHADOW, and unlike other recent proposals, browser extensions do not need blanket `content_scripts` or any `permissions` at all. Furthermore, any web page (and not just browser extensions) can register a handler for a protocol. That means better support for pure web wallets, native executable wallets, and hardware wallets. As long as a wallet can serve a page securely, it can register itself as a handler. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Initiating a Connection + +To initiate a connection to a provider, a web page SHOULD: + +1. Add an event listener to `window` for the `"message"` event (or set `window.onmessage`.) +2. Create an `iframe` tag with a `src` attribute value of `web+evm://`; then +3. Attach the `iframe` to the DOM. +4. Wait for a `"message"` event with a non-nullish `source` equal to the `iframe`'s `contentWindow`. +5. Save the first port from the message event for further communication. This is referred to as the "primary port." + +The event received in step 4 MAY contain additional information about the provider. If present, the event data SHALL satisfy the following TypeScript interface: + +```typescript +interface ProviderInfo { + name: string; + icon: string; +} +``` + +Where: + + - **`name`** is the human-readable name of the provider; and + - **`icon`** is a URI pointing at an image. See [Icon Images](#icon-images). + +### Communicating on an Established Connection + +The web page and wallet MAY make requests of the other. The party making the request is known as the requester, and the replying party is known as the responder. + +A requester MAY make requests of the responder by sending a message (using `postMessage`) on the primary port. The message MAY include a `MessagePort` as the first item of the message's transfer list to receive a reply. This port is known as a "reply port." The message's data MUST satisfy [EIP-1193](./eip-1193.md)'s `RequestArguments` interface, and SHALL be interpreted as described there. + +The responder SHALL respond by posting a single message to the reply port, if a reply port was transferred. The message's data SHALL satisfy the following TypeScript interface, where `ProviderRpcError` is defined in EIP-1193: + +```typescript +interface Response { + result?: unknown; + error?: ProviderRpcError; +} +``` + +Exactly one of `result` or `error` SHALL be present on the response. + +If present, `result` SHALL be equivalent to the `result` field of the named JSON-RPC method's response. + +Error objects SHOULD follow the recommendations set out in EIP-1193. + +A request without a transferred reply port SHALL NOT be considered an error, even if a reply would have been sent. + +### Icon Images + + + +## Rationale + +Instead of directly using the `iframe.contentWindow`'s message port, SHADOW transfers a message port in the first message. This allows the `iframe`, in some specific scenarios, to completely hand off communication, so the web page and the provider communicate directly, without any proxying in the `iframe`. + +## Backwards Compatibility + +While not backwards compatible with EIP-1193, this proposal uses extremely similar data structures to make the transition as painless as possible. + +It is possible to implement an EIP-1193 compatible provider using this proposal like so: + + + +## Security Considerations + + + +Both providers and web pages MUST verify the origin of messages before trusting them. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7044.md b/EIPS/eip-7044.md new file mode 100644 index 00000000000000..9f6aeedb73972f --- /dev/null +++ b/EIPS/eip-7044.md @@ -0,0 +1,63 @@ +--- +eip: 7044 +title: Perpetually Valid Signed Voluntary Exits +description: Lock voluntary exit signature domain on capella for perpetual validity +author: Lion (@dapplion) +discussions-to: https://ethereum-magicians.org/t/eip-7044-perpetually-valid-signed-voluntary-exits/14348 +status: Final +type: Standards Track +category: Core +created: 2023-05-18 +--- + +## Abstract + +Lock validator voluntary exit signature domain on Capella for perpetual validity. Currently, signed voluntary exits are only valid for two upgrades. + +## Motivation + +Currently, signed voluntary exits are valid up-to only two upgrades for block inclusion due to the Beacon Chain state considering only the current and previous fork version. This limitation increases the complexity of some staking operations, specifically those in which the staking operator (holder of active key) is distinct from the owner of the funds (holder of the withdrawal credential). Because voluntary exits can only be signed by the active key, such a relationship requires the exchange of signed exits ahead of time for an unbounded number of forks. + +The limited validity of voluntary exits was originally motivated to isolate them in the event of a hard fork that results in two maintained chains. If fork A and B exist and a validator operates on both, if they send an exit, it will be replayable on both. However, this possibility is not sufficient to justify the UX degradation exposed above, as no funds are at risk and the staker can re-stake on one or both of the chains. + +## Specification + +### Consensus Layer + +Specification changes are built into the Consensus Specs Deneb upgrade. + +The specific makes one change to the state transition function: + +- Modify [`process_voluntary_exit`](https://github.com/ethereum/consensus-specs/blob/75971a8c218b1d76d605dd8b88a08d39c42de221/specs/deneb/beacon-chain.md#modified-process_voluntary_exit) to compute the signing domain and root fixed on `CAPELLA_FORK_VERSION`. + +Additionally, the `voluntary_exit` gossip conditions are implicitly modified to support this change. + +To make the change backwards compatible the signature domain is locked on the Capella fork + +### Execution Layer + +This specification does not require any changes to the Execution Layer. + +## Rationale + +Perpetually valid signed voluntary exits allow simpler staking operation designs. It also aligns the UX of such objects to `BLSToExecutionChanges` and deposits, such that downstream tooling does not need to be updated with fork version information. + +## Backwards Compatibility + +This change is backwards compatible to the Consensus Layer of Ethereum block processing logic. + +The expectation of future validity of exits is not forward compatible. Specifically, users who have already pre-signed exits utilizing the Deneb fork domain with an expectation of their validity should be aware that these pre-signed exits will no longer be recognized as valid. Consequently, users should adjust their approach moving forward. For continued validity across forks, including Deneb and subsequent forks, users should ensure that their exits are signed using the Capella fork domain. + +There are no forwards/backwards compatibility issues with the Execution Layer. + +## Test Cases + +Test cases for this EIP can be found in the [`deneb`](https://github.com/ethereum/consensus-specs/tree/2297c09b7e457a13f7b2261a28cb45777be82f83/tests/core/pyspec/eth2spec/test/deneb) test suite of the `consensus-specs` repository. + +## Security Considerations + +The divergent signature domains across forked networks would previously have prevented the replay of VoluntaryExits after two hard forks. This specification change causes the replay protection to no longer exist. These potential replays could impact individual stakers on both sides of a fork, but does not put funds at risk and does not impact the security of the chain. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7045.md b/EIPS/eip-7045.md new file mode 100644 index 00000000000000..48e711c5fb4f07 --- /dev/null +++ b/EIPS/eip-7045.md @@ -0,0 +1,81 @@ +--- +eip: 7045 +title: Increase max attestation inclusion slot +description: Increases max attestaton inclusion slot to the last slot in `N+1` where `N` is the epoch containing the attestation's slot. +author: Danny Ryan (@djrtwo) +discussions-to: https://ethereum-magicians.org/t/eip-7045-increase-attestation-slot-inclusion-range/14342 +status: Final +type: Standards Track +category: Core +created: 2023-05-18 +--- + +## Abstract + +Increases max attestation inclusion slot from `attestation.slot + SLOTS_PER_EPOCH` to the last slot of epoch `N+1` where `N` is the epoch containing the attestation slot. + +This increase is critical to the current LMD-GHOST security analysis as well as the confirmation rule. + +## Motivation + +Attestations can currently be included after some minimum delay (`1` slot on mainnet) up until `SLOTS_PER_EPOCH` slots after the slot the attestation was created in. This rolling window of one epoch was decided upon during Phase 0 because the equal inclusion window for any attestation was assessed as "fair". The alternative considered path was to allow inclusion during the current and next epoch which means attestations created during the start of an epoch have more potential slots of inclusion than those at the end of the epoch. + +Since this decision, it has become apparent that the alternative design is critical for current LMD-GHOST security proofs as well as a new confirmation rule (which will allow for block confirmations in approximately 3-4 slots in normal mainnet conditions). + +This specification thus increases the max inclusion slot for attestations in accordance with the learned security proof and confirmation rule needs. + +## Specification + +### Constants + +| Name | Value | Comment | +| - | - | - | +|`FORK_TIMESTAMP` | *TBD* | Mainnet | + +### Execution layer + +This requires no changes to the Execution Layer. + +### Consensus layer + +Specification changes are built into the Consensus Specs Deneb upgrade. + +The specification makes two minor changes to the state transition function: + +* Modify [`process_attestation`](https://github.com/ethereum/consensus-specs/blob/95f36d99cf4aa59974da06af24ef9a7c12d3c301/specs/deneb/beacon-chain.md#modified-process_attestation) to not have an upper bound on the slot check and instead define the inclusion range via the minimum slot as well as the target epoch being in either current or previous epoch. +* Modify [`get_attestation_participation_flag_indices`](https://github.com/ethereum/consensus-specs/blob/95f36d99cf4aa59974da06af24ef9a7c12d3c301/specs/deneb/beacon-chain.md#modified-get_attestation_participation_flag_indices) to set the `TIMELY_TARGET_FLAG` without consideration of `inclusion_delay` to ensure that the extended inclusion attestations have a non-zero reward. + +Additionally, the specification modifies the [attestation](https://github.com/ethereum/consensus-specs/blob/95f36d99cf4aa59974da06af24ef9a7c12d3c301/specs/deneb/p2p-interface.md#beacon_attestation_subnet_id) and [aggregate attestation](https://github.com/ethereum/consensus-specs/blob/95f36d99cf4aa59974da06af24ef9a7c12d3c301/specs/deneb/p2p-interface.md#beacon_aggregate_and_proof) gossip conditions to allow for gossip during this extended range. + +## Rationale + +### Extended max inclusion slot + +As discussed in the Motivation, extending this max inclusion slot to the end of the next epoch is critical for LMD-GHOST security proofs and confirmation rule. + +### Removal of `inclusion_delay` consideration for target reward + +Previously, `get_attestation_participation_flag_indices` would only set the `TIMELY_TARGET_FLAG` (and thus reward for an attestation with correct target vote) if the attestation was included within a `SLOTS_PER_EPOCH` window. + +The `inclusion_delay` consideration for this flag is removed to ensure that whatever the valid inclusion window is for an attestation, it can receive a baseline non-zero reward for correct target. This ensures that clients will still attempt to pack such attestations into blocks which is important for the security analysis. + +Note, this was the intended behavior with the previously defined range which was equivalent to the max. + +## Backwards Compatibility + +This EIP introduces backwards incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. + +## Test Cases + +Test cases for this EIP can be found in the [`deneb`](https://github.com/ethereum/consensus-specs/tree/2297c09b7e457a13f7b2261a28cb45777be82f83/tests/core/pyspec/eth2spec/test/deneb) test suite of the `consensus-specs` repository. + +## Security Considerations + +This improves LMD-GHOST security as well as enables a fast confirmation rule. + +There are no known negative impacts to security. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-7053.md b/EIPS/eip-7053.md new file mode 100644 index 00000000000000..1c5fa34b158747 --- /dev/null +++ b/EIPS/eip-7053.md @@ -0,0 +1,7 @@ +--- +eip: 7053 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7053.md diff --git a/EIPS/eip-7066.md b/EIPS/eip-7066.md new file mode 100644 index 00000000000000..852fc7ca26ba27 --- /dev/null +++ b/EIPS/eip-7066.md @@ -0,0 +1,7 @@ +--- +eip: 7066 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7066.md diff --git a/EIPS/eip-7069.md b/EIPS/eip-7069.md new file mode 100644 index 00000000000000..04e1b3800d70f7 --- /dev/null +++ b/EIPS/eip-7069.md @@ -0,0 +1,217 @@ +--- +eip: 7069 +title: Revamped CALL instructions +description: Introduce EXTCALL, EXTDELEGATECALL and EXTSTATICCALL with simplified semantics +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Danno Ferrin (@shemnon), Andrei Maiboroda (@gumb0), Charles Cooper (@charles-cooper) +discussions-to: https://ethereum-magicians.org/t/eip-revamped-call-instructions/14432 +status: Review +type: Standards Track +category: Core +created: 2023-05-05 +requires: 150, 211, 214, 2929, 3540 +--- + +## Abstract + +Introduce three new call instructions, `EXTCALL`, `EXTDELEGATECALL` and `EXTSTATICCALL`, with simplified semantics. Introduce another instruction, `RETURNDATALOAD` for loading a word from return data into stack. Modify the behavior of `RETURNDATACOPY` instruction executed within EOF formatted code (as defined by [EIP-3540](./eip-3540.md)). The existing `*CALL` instructions remain unchanged. + +The new instructions do not allow specifying a gas limit, but rather rely on the "63/64th rule" ([EIP-150](./eip-150.md)) to limit gas. An important improvement is the rules around the "stipend" are simplified, and callers do not need to perform special calculation whether the value is sent or not. + +Furthermore, the obsolete functionality of specifying output buffer address is removed in favor of using `RETURNDATACOPY` instead. For cases which would previously `*CALL` output into a buffer and then `MLOAD` from the buffer, `RETURNDATALOAD` is provided instead. + +Lastly, instead of returning a boolean for execution status, an extensible list of status codes is returned: `0` for success, `1` for revert, `2` for failure. + +We expect most new contracts to rely on the new instructions (for simplicity and in order to save gas), and some specific contracts where gas limiting is required to keep using the old instructions (e.g. [ERC-4337](./eip-4337.md)). + +## Motivation + +Observability of gas has been a problem for very long. The system of gas has been (and likely must be) flexible in adapting to changes to both how Ethereum is used as well as changes in underlying hardware. + +Unfortunately, in many cases compromises or workarounds had to be made to avoid affecting call instructions negatively, mostly due to the complex semantics and expectations of them. + +This change aims to remove gas observability from the new instructions and opening the door for new classes of contracts that are not affected by repricings. Furthermore, once the EVM Object Format (EOF) is introduced, the legacy call instructions can be rejected within EOF contracts, making sure they are mostly unaffected by changes in gas fees. Because these operations are required for removing gas observability they will be required for EOF in lieu of the existing instructions. + +It is important to note that starting Solidity 0.4.21, the compiler already passes all remaining gas to calls (using `call(gas(), ...`), unless the developer uses the explicit override (`{gas: ...}`) in the language. This suggests most contracts don't rely on controlling gas. + +Besides the above, this change introduces a convenience feature of returning more detailed status codes: success (0), revert (1), failure (2). This moves from the boolean option to codes, which are extensible in the future. + +Lastly, the introduction of the `RETURNDATA*` instructions ([EIP-211](./eip-211.md)) has obsoleted the output parameters of calls, in a large number of cases rendering them unused. Using the output buffers have caused "bugs" in the past: in the case of [ERC-20](./eip-20.md), conflicting implementations caused a lot of trouble, where some would return something, while others would not. With relying on `RETURNDATA*` instructions this is implicitly clarified. This proposal also adds the "missing" `RETURNDATALOAD` instruction to round out returndata buffer access instructions. + +## Specification + +| Name | Value | Comment | +|------|-------|---------| +| WARM_STORAGE_READ_COST | 100 | From [EIP-2929](./eip-2929.md) | +| COLD_ACCOUNT_ACCESS | 2600 | From [EIP-2929](./eip-2929.md) | +| CALL_VALUE_COST | 9000 | | +| ACCOUNT_CREATION_COST | 25000 | | +| MIN_RETAINED_GAS | 5000 | | +| MIN_CALLEE_GAS | 2300 | | + +We introduce four new instructions: + +- `EXTCALL` (`0xf8`) with arguments `(target_address, input_offset, input_size, value)` +- `EXTDELEGATECALL` (`0xf9`) with arguments `(target_address, input_offset, input_size)` +- `EXTSTATICCALL` (`0xfb`) with arguments `(target_address, input_offset, input_size)` +- `RETURNDATALOAD` (`0xf7`) with argument `offset` + +In case this EIP is included as part of the greater EOF upgrade, these four new instructions are undefined in legacy code and only available in EOF code. + +Execution semantics of `EXT*CALL`: + +1. Charge `WARM_STORAGE_READ_COST` (100) gas. +2. Pop required arguments from stack, halt with exceptional failure on stack underflow. + - **NOTE**: When implemented in EOF, stack underflow check is done during stack validation and runtime check is omitted. +3. If `value` is non-zero: + - Halt with exceptional failure if the current frame is in `static-mode`. + - Charge `CALL_VALUE_COST` gas. +4. If `target_address` has any of the high 12 bytes set to a non-zero value(i.e. it does not contain a 20-byte address) then halt with an exceptional failure. +5. Perform (and charge for) memory expansion using `[input_offset, input_size]`. +6. If `target_address` is not in the `warm_account_list`, charge `COLD_ACCOUNT_ACCESS - WARM_STORAGE_READ_COST` (2500) gas. +7. If `target_address` is not in the state and the call configuration would result in account creation, charge `ACCOUNT_CREATION_COST` (25000) gas. + - The only such case in this EIP is if `value` is non-zero. +8. Calculate the gas available to callee as caller's remaining gas reduced by `max(floor(gas/64), MIN_RETAINED_GAS)`. +9. Fail with status code `1` returned on stack if any of the following is true (only gas charged until this point is consumed): + - Gas available to callee at this point is less than `MIN_CALLEE_GAS`. + - Balance of the current account is less than `value`. + - Current call stack depth equals `1024`. +10. Perform the call with the available gas and configuration. +11. Push a status code on the stack: + - `0` if the call was successful. + - `1` if the call has reverted (also can be pushed earlier in a light failure scenario). + - `2` if the call has failed. +12. Gas not used by the callee is returned to the caller. + +Execution semantics of `RETURNDATALOAD`: + +1. Charge `G_verylow` (3) gas +2. Pop 1 item from the stack, to be referred to as `offset` +3. Push 1 item onto the stack, the 32-byte word read from the returndata buffer starting at `offset`. +4. If `offset + 32 > len(returndata buffer)`, the result is zero-padded. + +In case this EIP is included as part of the greater EOF upgrade, execution semantics of `RETURNDATACOPY` in EOF formatted code ([EIP-3540](./eip-3540.md)) is modified as follows: + +1. Assume the 3 arguments popped from stack are `destOffset`, `offset` and `size`. +2. If `offset + size > len(returndata buffer)` **do not** halt with exceptional failure, but instead set the `offset + size - len(returndata buffer)` memory bytes after the copied ones to zero. +3. Gas charged for memory copying remains `3 * num_words(size)`, regardless of the number of bytes actually copied or set to zero. + +Execution of `RETURNDATACOPY` which is not in EOF formatted code (i.e. is in legacy code) is not changed. + +**TODO:** Clarify which side (caller/callee) is gas deducted from and where an error originates from. + +**TODO:** Mention gas refunds? + +**TODO:** Consider option where non-calldata value transfer is not allowed, but there's a specific `TRANSFER`/`PAY` function for that. Would simplify the logic greatly. + +## Rationale + +### Removing gas selectability + +One major change from the original `CALL` series of instructions is that the caller has no control over the amount of gas passed in as part of the call. The number of cases where such a feature is essential are probably better served by direct protocol integration. + +Removing gas selectability also introduces a valuable property that future revisions to the gas schedule will benefit from: you can always overcome Out of Gas (OOG) errors by sending more gas as part of the transaction (subject to the block gas limit). Previously when raising storage costs ([EIP-1884](./eip-1884.md)) some contracts that sent only a limited amount of gas to their calls were broken by the new costing. + +Hence some contracts had a gas ceiling they were sending to their next call, permanently limiting the amount of gas they could spend. No amount of extra gas could fix the issue as the call would limit the amount sent. The notion of a stipend floor is retained in this spec. This floor can be changed independent of the smart contracts and still preserve the feature that OOG halts can be fixed by sending more gas as part of the transaction. + +### Stipend and 63/64th rule + +The purpose of the stipend is to have enough gas to emit logs (i.e. perform non-state-changing operations) when a "contract wallet" is called. The stipend is only added when the `CALL` instruction is used and the value is non-zero. + +The 63/64th rule has multiple purposes: + +a. to limit call depth, +b. to ensure the caller has gas left to make state changes after a callee returns. + +Additionally, there is a call depth counter, and calls fail if the depth would exceed 1024. + +Before the 63/64th rule was introduced, it was required to calculate available gas semi-accurately on caller side. Solidity has a complicated ruleset where it tries to estimate how much it will cost on the caller side to perform the call itself, in order to set a reasonable gas value. + +We have changed the ruleset: + +The 63/64th rule is still applied, but + - At least `MIN_RETAINED_GAS` gas is retained prior to executing the callee, + - At least `MIN_CALLEE_GAS` gas is available to the callee. + +The `MIN_CALLEE_GAS` rule is a replacement for stipend: it simplifies the reasoning about the gas costs and is applied uniformly for all introduced `EXT*CALL` instructions. +The following table visualizes the differences (note the discrepancy between _caller required gas_ and _caller cost_ for `CALL`). + +| | Caller required gas | Caller cost (burned gas) | Caller min retained gas | Callee min gas | +|-----------------|---------------------|--------------------------|-------------------------|----------------| +| CALL V=0 | 100 | 100 | 0 | 0 | +| CALL V≠0 | 100+9000 | 100+6700 | 0 | 2300 | +| DELEGATECALL | 100 | 100 | 0 | 0 | +| STATICCALL | 100 | 100 | 0 | 0 | +| EXTCALL V=0 | 100 | 100 | 5000 | 2300 | +| EXTCALL V≠0 | 100+9000 | 100+9000 | 5000 | 2300 | +| EXTDELEGATECALL | 100 | 100 | 5000 | 2300 | +| EXTSTATICCALL | 100 | 100 | 5000 | 2300 | + +- **Caller required gas**: the minimum amount of gas a caller is required to have to execute a call instruction, lower value causes caller's OOG, +- **Caller cost (burned gas)**: the amount of gas deducted from the caller to execute the instruction, this amount is not available to the callee, +- **Caller min retained gas**: the minimum amount of gas the caller is guaranteed to have after the call, if this cannot be guaranteed the call fails without even reaching the callee, +- **Callee min gas**: the minimum gas limit for the callee's execution. + +Removing the call stack depth check was initially considered, but this would be incompatible with the original `*CALL` instructions, as well as `CREATE*` instructions, which can be intertwined with the new `EXT*CALL` instructions in the call stack. As such, keeping the call stack depth check involves no change affecting legacy code. + +Also, we find the simple (as opposed to the complex 63/64th rule) hard cap reassuring, that the call stack depth is limited, in case the gas rules can be bypassed. Lastly, the amount of gas to reach depth of 1024 is huge, but not absurdly huge, and we want to avoid constraining ourselves by dependency of this check on current gas limits. + +### Output buffers + +The functionality of specifying output buffer address is removed, because it is added complexity and in a large number of cases implementers prefer to use `RETURNDATACOPY` instead. Even if they rely on the output buffer (like in the case of Vyper), they would still check the length with `RETURNDATASIZE`. In Solidity one exception is the case when the expected return size is known (i.e. non-dynamic return values), in this case Solidity still uses the output buffer. For these cases, `RETURNDATALOAD` is introduced, which simplifies the workflow of copying returndata into a (known) output buffer and using `MLOAD` from there; instead, `RETURNDATALOAD` can be used directly. + +### Status codes + +Current call instructions return a boolean value to signal success: 0 means failure, 1 means success. The Solidity compiler assumed this value is a boolean and thus uses the value as branch condition to status (`if iszero(status) { /* failure */ }`). This prevents us from introducing new status codes without breaking existing contracts. At the time of the design of [EIP-211](./eip-211.md) the idea of return a specific code for revert was discussed, but ultimately abandoned for the above reason. + +We change the value from boolean to a status code, where `0` signals success and thus it will be possible to introduce more non-success codes in the future, if desired. + +Status code `1` is used for both reverts coming from the callee frame and light failures encountered in the execution of the instructions. The reason for combining them is keeping the semantics similar to the original CALLs - both scenarios preserve unused gas and continue being indistinguishable to the caller. + +### Parameter order + +The order of parameters has been changed to move the `value` field to be the last. This allows the instructions to have identical encoding with the exception of the last parameter, and simplifies EVM and compiler implementations slightly. + +### Opcode encoding + +Instead of introducing three new `EXT*CALL` opcodes we have discussed a version with an immediate configuration byte (flags). There are two main disadvantages to this: + +1. Some combination of flags may not be useful/be invalid, and this increases the testing/implementation surface. +2. The instruction could take variable number of stack items (i.e. `value` for `EXTCALL`) would be a brand new concept no other instruction has. + +It is also useful to have these as new opcodes instead of modifying the existing CALL series inside of EOF. This creates an "escape hatch" in case gas observability needs to be restored to EOF contracts. This is done by adding the GAS and original CALL series opcodes to the valid EOF opcode list. + +### `CALLCODE` + +Since `CALLCODE` is deprecated, we do not introduce a counterpart here. + +### Halting when `target_address` is not a 20-byte ethereum addresses + +When existing `CALL` series operations encounter an address that does not fit into 20 bytes the current behavior is to mask the address so that it fits into 20 bytes, ignoring all high bytes. For the `EXT*CALL` operations a halt was chosen over treating the contract as empty for two reasons. First, it handles the case of sending value to an address that doesn't exist without having to create a special case. Second, it keeps the `warm_access_list` from needing to track anything that is not a 20-byte ethereum address. + +Smart contract developers should not rely on the operation reverting when such addresses are passed in. When a suitable proposal for the use of Address Space Extension is adopted it is expected that the `EXT*CALL` series of operations will adopt those changes. + +### New instructions undefined in legacy (only if this EIP is part of EOF) + +There is an alternative scenario where, in case this EIP is included as part of the greater EOF upgrade, the four new instructions are **additionally** available in legacy EVM. There is, however, a preference to limit changes to legacy EVM in the fork where EOF is included as well as in subsequent ones. + +### `RETURNDATALOAD` and `RETURNDATACOPY` padding behavior + +This EIP initially proposed keeping the halt-on-OOB behavior of legacy `RETURNDATACOPY`. This makes compilers optimizations harder, because unnecessary `RETURNDATA*` instructions cannot be optimized out without change to code semantics. + +It could be that only `RETURNDATALOAD` is given the padding behavior, but that would make it confusingly inconsistent with the closely related `RETURNDATACOPY` instruction. + +There also was the alternative to have `RETURNDATACOPY2` introduced with the padding behavior, available in EOF only, at the same time banning `RETURNDATACOPY` in EOF. This has been rejected in order to avoid multiplying opcodes, and also as suboptimal from the point of view of compiler implementation. + +## Backwards Compatibility + +No existing instructions are changed and so we do not think any backwards compatibility issues can occur. + +## Security Considerations + +It is expected that the attack surface will not grow. All of these operations can be modeled by existing operations with fixed gas (all available) and output range (zero length at zero memory). + +When implemented in EOF (where the GAS opcode and the original CALL operations are removed) existing out of gas attacks will be slightly more difficult, but not entirely prevented. Transactions can still pass in arbitrary gas values and clever contract construction can still result in specific gas values being passed to specific calls. It is expected the same surface will remain in EOF, but the ease of explotation will be reduced. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7085.md b/EIPS/eip-7085.md new file mode 100644 index 00000000000000..012ef377a2fd0d --- /dev/null +++ b/EIPS/eip-7085.md @@ -0,0 +1,7 @@ +--- +eip: 7085 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7085.md diff --git a/EIPS/eip-7092.md b/EIPS/eip-7092.md new file mode 100644 index 00000000000000..db9296879a06f8 --- /dev/null +++ b/EIPS/eip-7092.md @@ -0,0 +1,7 @@ +--- +eip: 7092 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7092.md diff --git a/EIPS/eip-7093.md b/EIPS/eip-7093.md new file mode 100644 index 00000000000000..b93654c4967826 --- /dev/null +++ b/EIPS/eip-7093.md @@ -0,0 +1,7 @@ +--- +eip: 7093 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7093.md diff --git a/EIPS/eip-712.md b/EIPS/eip-712.md index 16e14a9065e5fc..6fbb24cfc5f249 100644 --- a/EIPS/eip-712.md +++ b/EIPS/eip-712.md @@ -41,43 +41,7 @@ Here we outline a scheme to encode data along with its structure which allows it ## Specification -### Signatures and Hashing overview - -A signature scheme consists of hashing algorithm and a signing algorithm. The signing algorithm of choice in Ethereum is `secp256k1`. The hashing algorithm of choice is `keccak256`, this is a function from bytestrings, 𝔹⁸ⁿ, to 256-bit strings, 𝔹²⁵⁶. - -A good hashing algorithm should satisfy security properties such as determinism, second pre-image resistance and collision resistance. The `keccak256` function satisfies the above criteria _when applied to bytestrings_. If we want to apply it to other sets we first need to map this set to bytestrings. It is critically important that this encoding function is deterministic and injective. If it is not deterministic then the hash might differ from the moment of signing to the moment of verifying, causing the signature to incorrectly be rejected. If it is not injective then there are two different elements in our input set that hash to the same value, causing a signature to be valid for a different unrelated message. - -### Transactions and bytestrings - -An illustrative example of the above breakage can be found in Ethereum. Ethereum has two kinds of messages, transactions `𝕋` and bytestrings `𝔹⁸ⁿ`. These are signed using `eth_sendTransaction` and `eth_sign` respectively. Originally the encoding function `encode : 𝕋 ∪ 𝔹⁸ⁿ → 𝔹⁸ⁿ` was defined as follows: - -* `encode(t : 𝕋) = RLP_encode(t)` -* `encode(b : 𝔹⁸ⁿ) = b` - -While individually they satisfy the required properties, together they do not. If we take `b = RLP_encode(t)` we have a collision. This is mitigated in ethereum/go-ethereum#2940 by modifying the second leg of the encoding function: - -* `encode(b : 𝔹⁸ⁿ) = "\x19Ethereum Signed Message:\n" ‖ len(b) ‖ b` where `len(b)` is the ascii-decimal encoding of the number of bytes in `b`. - -This solves the collision between the legs since `RLP_encode(t : 𝕋)` never starts with `\x19`. There is still the risk of the new encoding function not being deterministic or injective. It is instructive to consider those in detail. - -As is, the definition above is not deterministic. For a 4-byte string `b` both encodings with `len(b) = "4"` and `len(b) = "004"` are valid. This can be solved by further requiring that the decimal encoding of the length has no leading zeros and `len("") = "0"`. - -The above definition is not obviously collision free. Does a bytestring starting with `"\x19Ethereum Signed Message:\n42a…"` mean a 42-byte string starting with `a` or a 4-byte string starting with `2a`?. This was pointed out in ethereum/go-ethereum#14794 and motivated Trezor to not implement the standard as-is (see trezor/trezor-mcu#163). Fortunately this does not lead to actual collisions as the total length of the encoded bytestring provides sufficient information to disambiguate the cases. - -Both determinism and injectiveness would be trivially true if `len(b)` was left out entirely. The point is, it is difficult to map arbitrary sets to bytestrings without introducing security issues in the encoding function. Yet the current design of `eth_sign` still takes a bytestring as input and expects implementors to come up with an encoding. - -### Arbitrary messages - -The `eth_sign` call assumes messages to be bytestrings. In practice we are not hashing bytestrings but the collection of all semantically different messages of all different DApps `𝕄`. Unfortunately, this set is impossible to formalize. Instead we approximate it with the set of typed named structures `𝕊`. This standard formalizes the set `𝕊` and provides a deterministic injective encoding function for it. - -Just encoding structs is not enough. It is likely that two different DApps use identical structs. When this happens, a signed message intended for one DApp would also be valid for the other. The signatures are compatible. This can be intended behaviour, in which case everything is fine as long as the DApps took replay attacks into consideration. If it is not intended, there is a security problem. - -The way to solve this is by introducing a domain separator, a 256-bit number. This is a value unique to each domain that is 'mixed in' the signature. It makes signatures from different domains incompatible. The domain separator is designed to include bits of DApp unique information such as the name of the DApp, the intended validator contract address, the expected DApp domain name, etc. The user and user-agent can use this information to mitigate phishing attacks, where a malicious DApp tries to trick the user into signing a message for another DApp. - -## Specification - The set of signable messages is extended from transactions and bytestrings `𝕋 ∪ 𝔹⁸ⁿ` to also include structured data `𝕊`. The new set of signable messages is thus `𝕋 ∪ 𝔹⁸ⁿ ∪ 𝕊`. They are encoded to bytestrings suitable for hashing and signing as follows: - * `encode(transaction : 𝕋) = RLP_encode(transaction)` * `encode(message : 𝔹⁸ⁿ) = "\x19Ethereum Signed Message:\n" ‖ len(message) ‖ message` where `len(message)` is the _non-zero-padded_ ascii-decimal encoding of the number of bytes in `message`. * `encode(domainSeparator : 𝔹²⁵⁶, message : 𝕊) = "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)` where `domainSeparator` and `hashStruct(message)` are defined below. @@ -165,9 +129,7 @@ The method `eth_signTypedData` is added to the Ethereum JSON-RPC. The method par #### eth_signTypedData -The sign method calculates an Ethereum specific signature with: `sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)))`. - -By adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. +The sign method calculates an Ethereum specific signature with: `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))`, as defined above. **Note**: the address to sign with must be unlocked. diff --git a/EIPS/eip-7144.md b/EIPS/eip-7144.md new file mode 100644 index 00000000000000..f08ff8b429ff9e --- /dev/null +++ b/EIPS/eip-7144.md @@ -0,0 +1,7 @@ +--- +eip: 7144 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7144.md diff --git a/EIPS/eip-7160.md b/EIPS/eip-7160.md new file mode 100644 index 00000000000000..8be8df0fef64cb --- /dev/null +++ b/EIPS/eip-7160.md @@ -0,0 +1,7 @@ +--- +eip: 7160 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7160.md diff --git a/EIPS/eip-7199.md b/EIPS/eip-7199.md new file mode 100644 index 00000000000000..8ceb24f8b00b77 --- /dev/null +++ b/EIPS/eip-7199.md @@ -0,0 +1,34 @@ +--- +eip: 7199 +title: Linter Scope +description: Relax the policy for updating EIP. +author: Zainan Victor Zhou (@xinbenlv) +discussions-to: https://ethereum-magicians.org/t/proposal-eipw-should-only-complain-about-changing-lines/14762 +status: Withdrawn +type: Meta +created: 2023-06-20 +withdrawal-reason: Policy is documented in EIP-1 and EIP-5069. +--- + +## Abstract + +Currently in practice EIP linter tools (EIPW, for example) will block a Pull Request for lint errors even if that lint errors was not introduced in that Pull Request. +This EIP make it explicit that lint errors for untouched lines shall be considered ignoreable except for status change. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +In an update to an EIP, A Pull Request SHOULD NOT be required to fix linter errors in untouched lines unless it's changing the Status of the EIP. + +## Rationale + +This policy allows micro contributions for anyone who just want to fix a typo or change a section of a section in a large EIP. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7201.md b/EIPS/eip-7201.md new file mode 100644 index 00000000000000..04d301d960146a --- /dev/null +++ b/EIPS/eip-7201.md @@ -0,0 +1,7 @@ +--- +eip: 7201 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7201.md diff --git a/EIPS/eip-721.md b/EIPS/eip-721.md index 9ced980dbe1697..423b88555b07ca 100644 --- a/EIPS/eip-721.md +++ b/EIPS/eip-721.md @@ -1,447 +1,7 @@ --- eip: 721 -title: Non-Fungible Token Standard -author: William Entriken (@fulldecent), Dieter Shirley , Jacob Evans , Nastassia Sachs -discussions-to: https://github.com/ethereum/eips/issues/721 -type: Standards Track category: ERC -status: Final -created: 2018-01-24 -requires: 165 +status: Moved --- -## Simple Summary - -A standard interface for non-fungible tokens, also known as deeds. - -## Abstract - -The following standard allows for the implementation of a standard API for NFTs within smart contracts. This standard provides basic functionality to track and transfer NFTs. - -We considered use cases of NFTs being owned and transacted by individuals as well as consignment to third party brokers/wallets/auctioneers ("operators"). NFTs can represent ownership over digital or physical assets. We considered a diverse universe of assets, and we know you will dream up many more: - -- Physical property — houses, unique artwork -- Virtual collectables — unique pictures of kittens, collectable cards -- "Negative value" assets — loans, burdens and other responsibilities - -In general, all houses are distinct and no two kittens are alike. NFTs are *distinguishable* and you must track the ownership of each one separately. - -## Motivation - -A standard interface allows wallet/broker/auction applications to work with any NFT on Ethereum. We provide for simple ERC-721 smart contracts as well as contracts that track an *arbitrarily large* number of NFTs. Additional applications are discussed below. - -This standard is inspired by the ERC-20 token standard and builds on two years of experience since EIP-20 was created. EIP-20 is insufficient for tracking NFTs because each asset is distinct (non-fungible) whereas each of a quantity of tokens is identical (fungible). - -Differences between this standard and EIP-20 are examined below. - -## Specification - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. - -**Every ERC-721 compliant contract must implement the `ERC721` and `ERC165` interfaces** (subject to "caveats" below): - -```solidity -pragma solidity ^0.4.20; - -/// @title ERC-721 Non-Fungible Token Standard -/// @dev See https://eips.ethereum.org/EIPS/eip-721 -/// Note: the ERC-165 identifier for this interface is 0x80ac58cd. -interface ERC721 /* is ERC165 */ { - /// @dev This emits when ownership of any NFT changes by any mechanism. - /// This event emits when NFTs are created (`from` == 0) and destroyed - /// (`to` == 0). Exception: during contract creation, any number of NFTs - /// may be created and assigned without emitting Transfer. At the time of - /// any transfer, the approved address for that NFT (if any) is reset to none. - event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); - - /// @dev This emits when the approved address for an NFT is changed or - /// reaffirmed. The zero address indicates there is no approved address. - /// When a Transfer event emits, this also indicates that the approved - /// address for that NFT (if any) is reset to none. - event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); - - /// @dev This emits when an operator is enabled or disabled for an owner. - /// The operator can manage all NFTs of the owner. - event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); - - /// @notice Count all NFTs assigned to an owner - /// @dev NFTs assigned to the zero address are considered invalid, and this - /// function throws for queries about the zero address. - /// @param _owner An address for whom to query the balance - /// @return The number of NFTs owned by `_owner`, possibly zero - function balanceOf(address _owner) external view returns (uint256); - - /// @notice Find the owner of an NFT - /// @dev NFTs assigned to zero address are considered invalid, and queries - /// about them do throw. - /// @param _tokenId The identifier for an NFT - /// @return The address of the owner of the NFT - function ownerOf(uint256 _tokenId) external view returns (address); - - /// @notice Transfers the ownership of an NFT from one address to another address - /// @dev Throws unless `msg.sender` is the current owner, an authorized - /// operator, or the approved address for this NFT. Throws if `_from` is - /// not the current owner. Throws if `_to` is the zero address. Throws if - /// `_tokenId` is not a valid NFT. When transfer is complete, this function - /// checks if `_to` is a smart contract (code size > 0). If so, it calls - /// `onERC721Received` on `_to` and throws if the return value is not - /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. - /// @param _from The current owner of the NFT - /// @param _to The new owner - /// @param _tokenId The NFT to transfer - /// @param data Additional data with no specified format, sent in call to `_to` - function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; - - /// @notice Transfers the ownership of an NFT from one address to another address - /// @dev This works identically to the other function with an extra data parameter, - /// except this function just sets data to "". - /// @param _from The current owner of the NFT - /// @param _to The new owner - /// @param _tokenId The NFT to transfer - function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; - - /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE - /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE - /// THEY MAY BE PERMANENTLY LOST - /// @dev Throws unless `msg.sender` is the current owner, an authorized - /// operator, or the approved address for this NFT. Throws if `_from` is - /// not the current owner. Throws if `_to` is the zero address. Throws if - /// `_tokenId` is not a valid NFT. - /// @param _from The current owner of the NFT - /// @param _to The new owner - /// @param _tokenId The NFT to transfer - function transferFrom(address _from, address _to, uint256 _tokenId) external payable; - - /// @notice Change or reaffirm the approved address for an NFT - /// @dev The zero address indicates there is no approved address. - /// Throws unless `msg.sender` is the current NFT owner, or an authorized - /// operator of the current owner. - /// @param _approved The new approved NFT controller - /// @param _tokenId The NFT to approve - function approve(address _approved, uint256 _tokenId) external payable; - - /// @notice Enable or disable approval for a third party ("operator") to manage - /// all of `msg.sender`'s assets - /// @dev Emits the ApprovalForAll event. The contract MUST allow - /// multiple operators per owner. - /// @param _operator Address to add to the set of authorized operators - /// @param _approved True if the operator is approved, false to revoke approval - function setApprovalForAll(address _operator, bool _approved) external; - - /// @notice Get the approved address for a single NFT - /// @dev Throws if `_tokenId` is not a valid NFT. - /// @param _tokenId The NFT to find the approved address for - /// @return The approved address for this NFT, or the zero address if there is none - function getApproved(uint256 _tokenId) external view returns (address); - - /// @notice Query if an address is an authorized operator for another address - /// @param _owner The address that owns the NFTs - /// @param _operator The address that acts on behalf of the owner - /// @return True if `_operator` is an approved operator for `_owner`, false otherwise - function isApprovedForAll(address _owner, address _operator) external view returns (bool); -} - -interface ERC165 { - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} -``` - -A wallet/broker/auction application MUST implement the **wallet interface** if it will accept safe transfers. - -```solidity -/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. -interface ERC721TokenReceiver { - /// @notice Handle the receipt of an NFT - /// @dev The ERC721 smart contract calls this function on the recipient - /// after a `transfer`. This function MAY throw to revert and reject the - /// transfer. Return of other than the magic value MUST result in the - /// transaction being reverted. - /// Note: the contract address is always the message sender. - /// @param _operator The address which called `safeTransferFrom` function - /// @param _from The address which previously owned the token - /// @param _tokenId The NFT identifier which is being transferred - /// @param _data Additional data with no specified format - /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - /// unless throwing - function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); -} -``` - -The **metadata extension** is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your smart contract to be interrogated for its name and for details about the assets which your NFTs represent. - -```solidity -/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension -/// @dev See https://eips.ethereum.org/EIPS/eip-721 -/// Note: the ERC-165 identifier for this interface is 0x5b5e139f. -interface ERC721Metadata /* is ERC721 */ { - /// @notice A descriptive name for a collection of NFTs in this contract - function name() external view returns (string _name); - - /// @notice An abbreviated name for NFTs in this contract - function symbol() external view returns (string _symbol); - - /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. - /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC - /// 3986. The URI may point to a JSON file that conforms to the "ERC721 - /// Metadata JSON Schema". - function tokenURI(uint256 _tokenId) external view returns (string); -} -``` - -This is the "ERC721 Metadata JSON Schema" referenced above. - -```json -{ - "title": "Asset Metadata", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Identifies the asset to which this NFT represents" - }, - "description": { - "type": "string", - "description": "Describes the asset to which this NFT represents" - }, - "image": { - "type": "string", - "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." - } - } -} -``` - -The **enumeration extension** is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your contract to publish its full list of NFTs and make them discoverable. - -```solidity -/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension -/// @dev See https://eips.ethereum.org/EIPS/eip-721 -/// Note: the ERC-165 identifier for this interface is 0x780e9d63. -interface ERC721Enumerable /* is ERC721 */ { - /// @notice Count NFTs tracked by this contract - /// @return A count of valid NFTs tracked by this contract, where each one of - /// them has an assigned and queryable owner not equal to the zero address - function totalSupply() external view returns (uint256); - - /// @notice Enumerate valid NFTs - /// @dev Throws if `_index` >= `totalSupply()`. - /// @param _index A counter less than `totalSupply()` - /// @return The token identifier for the `_index`th NFT, - /// (sort order not specified) - function tokenByIndex(uint256 _index) external view returns (uint256); - - /// @notice Enumerate NFTs assigned to an owner - /// @dev Throws if `_index` >= `balanceOf(_owner)` or if - /// `_owner` is the zero address, representing invalid NFTs. - /// @param _owner An address where we are interested in NFTs owned by them - /// @param _index A counter less than `balanceOf(_owner)` - /// @return The token identifier for the `_index`th NFT assigned to `_owner`, - /// (sort order not specified) - function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); -} -``` - -### Caveats - -The 0.4.20 Solidity interface grammar is not expressive enough to document the ERC-721 standard. A contract which complies with ERC-721 MUST also abide by the following: - -- Solidity issue #3412: The above interfaces include explicit mutability guarantees for each function. Mutability guarantees are, in order weak to strong: `payable`, implicit nonpayable, `view`, and `pure`. Your implementation MUST meet the mutability guarantee in this interface and you MAY meet a stronger guarantee. For example, a `payable` function in this interface may be implemented as nonpayable (no state mutability specified) in your contract. We expect a later Solidity release will allow your stricter contract to inherit from this interface, but a workaround for version 0.4.20 is that you can edit this interface to add stricter mutability before inheriting from your contract. -- Solidity issue #3419: A contract that implements `ERC721Metadata` or `ERC721Enumerable` SHALL also implement `ERC721`. ERC-721 implements the requirements of interface ERC-165. -- Solidity issue #2330: If a function is shown in this specification as `external` then a contract will be compliant if it uses `public` visibility. As a workaround for version 0.4.20, you can edit this interface to switch to `public` before inheriting from your contract. -- Solidity issues #3494, #3544: Use of `this.*.selector` is marked as a warning by Solidity, a future version of Solidity will not mark this as an error. - -*If a newer version of Solidity allows the caveats to be expressed in code, then this EIP MAY be updated and the caveats removed, such will be equivalent to the original specification.* - -## Rationale - -There are many proposed uses of Ethereum smart contracts that depend on tracking distinguishable assets. Examples of existing or planned NFTs are LAND in Decentraland, the eponymous punks in CryptoPunks, and in-game items using systems like DMarket or EnjinCoin. Future uses include tracking real-world assets, like real-estate (as envisioned by companies like Ubitquity or Propy). It is critical in each of these cases that these items are not "lumped together" as numbers in a ledger, but instead each asset must have its ownership individually and atomically tracked. Regardless of the nature of these assets, the ecosystem will be stronger if we have a standardized interface that allows for cross-functional asset management and sales platforms. - -**"NFT" Word Choice** - -"NFT" was satisfactory to nearly everyone surveyed and is widely applicable to a broad universe of distinguishable digital assets. We recognize that "deed" is very descriptive for certain applications of this standard (notably, physical property). - -*Alternatives considered: distinguishable asset, title, token, asset, equity, ticket* - -**NFT Identifiers** - -Every NFT is identified by a unique `uint256` ID inside the ERC-721 smart contract. This identifying number SHALL NOT change for the life of the contract. The pair `(contract address, uint256 tokenId)` will then be a globally unique and fully-qualified identifier for a specific asset on an Ethereum chain. While some ERC-721 smart contracts may find it convenient to start with ID 0 and simply increment by one for each new NFT, callers SHALL NOT assume that ID numbers have any specific pattern to them, and MUST treat the ID as a "black box". Also note that NFTs MAY become invalid (be destroyed). Please see the enumeration functions for a supported enumeration interface. - -The choice of `uint256` allows a wide variety of applications because UUIDs and sha3 hashes are directly convertible to `uint256`. - -**Transfer Mechanism** - -ERC-721 standardizes a safe transfer function `safeTransferFrom` (overloaded with and without a `bytes` parameter) and an unsafe function `transferFrom`. Transfers may be initiated by: - -- The owner of an NFT -- The approved address of an NFT -- An authorized operator of the current owner of an NFT - -Additionally, an authorized operator may set the approved address for an NFT. This provides a powerful set of tools for wallet, broker and auction applications to quickly use a *large* number of NFTs. - -The transfer and accept functions' documentation only specify conditions when the transaction MUST throw. Your implementation MAY also throw in other situations. This allows implementations to achieve interesting results: - -- **Disallow transfers if the contract is paused** — prior art, CryptoKitties deployed contract, line 611 -- **Blocklist certain address from receiving NFTs** — prior art, CryptoKitties deployed contract, lines 565, 566 -- **Disallow unsafe transfers** — `transferFrom` throws unless `_to` equals `msg.sender` or `countOf(_to)` is non-zero or was non-zero previously (because such cases are safe) -- **Charge a fee to both parties of a transaction** — require payment when calling `approve` with a non-zero `_approved` if it was previously the zero address, refund payment if calling `approve` with the zero address if it was previously a non-zero address, require payment when calling any transfer function, require transfer parameter `_to` to equal `msg.sender`, require transfer parameter `_to` to be the approved address for the NFT -- **Read only NFT registry** — always throw from `safeTransferFrom`, `transferFrom`, `approve` and `setApprovalForAll` - -Failed transactions will throw, a best practice identified in ERC-223, ERC-677, ERC-827 and OpenZeppelin's implementation of SafeERC20.sol. ERC-20 defined an `allowance` feature, this caused a problem when called and then later modified to a different amount, as on OpenZeppelin issue \#438. In ERC-721, there is no allowance because every NFT is unique, the quantity is none or one. Therefore we receive the benefits of ERC-20's original design without problems that have been later discovered. - -Creation of NFTs ("minting") and destruction of NFTs ("burning") is not included in the specification. Your contract may implement these by other means. Please see the `event` documentation for your responsibilities when creating or destroying NFTs. - -We questioned if the `operator` parameter on `onERC721Received` was necessary. In all cases we could imagine, if the operator was important then that operator could transfer the token to themself and then send it -- then they would be the `from` address. This seems contrived because we consider the operator to be a temporary owner of the token (and transferring to themself is redundant). When the operator sends the token, it is the operator acting on their own accord, NOT the operator acting on behalf of the token holder. This is why the operator and the previous token owner are both significant to the token recipient. - -*Alternatives considered: only allow two-step ERC-20 style transaction, require that transfer functions never throw, require all functions to return a boolean indicating the success of the operation.* - -**ERC-165 Interface** - -We chose Standard Interface Detection (ERC-165) to expose the interfaces that a ERC-721 smart contract supports. - -A future EIP may create a global registry of interfaces for contracts. We strongly support such an EIP and it would allow your ERC-721 implementation to implement `ERC721Enumerable`, `ERC721Metadata`, or other interfaces by delegating to a separate contract. - -**Gas and Complexity** (regarding the enumeration extension) - -This specification contemplates implementations that manage a few and *arbitrarily large* numbers of NFTs. If your application is able to grow then avoid using for/while loops in your code (see CryptoKitties bounty issue \#4). These indicate your contract may be unable to scale and gas costs will rise over time without bound. - -We have deployed a contract, XXXXERC721, to Testnet which instantiates and tracks 340282366920938463463374607431768211456 different deeds (2^128). That's enough to assign every IPV6 address to an Ethereum account owner, or to track ownership of nanobots a few micron in size and in aggregate totalling half the size of Earth. You can query it from the blockchain. And every function takes less gas than querying the ENS. - -This illustration makes clear: the ERC-721 standard scales. - -*Alternatives considered: remove the asset enumeration function if it requires a for-loop, return a Solidity array type from enumeration functions.* - -**Privacy** - -Wallets/brokers/auctioneers identified in the motivation section have a strong need to identify which NFTs an owner owns. - -It may be interesting to consider a use case where NFTs are not enumerable, such as a private registry of property ownership, or a partially-private registry. However, privacy cannot be attained because an attacker can simply (!) call `ownerOf` for every possible `tokenId`. - -**Metadata Choices** (metadata extension) - -We have required `name` and `symbol` functions in the metadata extension. Every token EIP and draft we reviewed (ERC-20, ERC-223, ERC-677, ERC-777, ERC-827) included these functions. - -We remind implementation authors that the empty string is a valid response to `name` and `symbol` if you protest to the usage of this mechanism. We also remind everyone that any smart contract can use the same name and symbol as *your* contract. How a client may determine which ERC-721 smart contracts are well-known (canonical) is outside the scope of this standard. - -A mechanism is provided to associate NFTs with URIs. We expect that many implementations will take advantage of this to provide metadata for each NFT. The image size recommendation is taken from Instagram, they probably know much about image usability. The URI MAY be mutable (i.e. it changes from time to time). We considered an NFT representing ownership of a house, in this case metadata about the house (image, occupants, etc.) can naturally change. - -Metadata is returned as a string value. Currently this is only usable as calling from `web3`, not from other contracts. This is acceptable because we have not considered a use case where an on-blockchain application would query such information. - -*Alternatives considered: put all metadata for each asset on the blockchain (too expensive), use URL templates to query metadata parts (URL templates do not work with all URL schemes, especially P2P URLs), multiaddr network address (not mature enough)* - -**Community Consensus** - -A significant amount of discussion occurred on the original ERC-721 issue, additionally we held a first live meeting on Gitter that had good representation and well advertised (on Reddit, in the Gitter #ERC channel, and the original ERC-721 issue). Thank you to the participants: - -- [@ImAllInNow](https://github.com/imallinnow) Rob from DEC Gaming / Presenting Michigan Ethereum Meetup Feb 7 -- [@Arachnid](https://github.com/arachnid) Nick Johnson -- [@jadhavajay](https://github.com/jadhavajay) Ajay Jadhav from AyanWorks -- [@superphly](https://github.com/superphly) Cody Marx Bailey - XRAM Capital / Sharing at hackathon Jan 20 / UN Future of Finance Hackathon. -- [@fulldecent](https://github.com/fulldecent) William Entriken - -A second event was held at ETHDenver 2018 to discuss distinguishable asset standards (notes to be published). - -We have been very inclusive in this process and invite anyone with questions or contributions into our discussion. However, this standard is written only to support the identified use cases which are listed herein. - -## Backwards Compatibility - -We have adopted `balanceOf`, `totalSupply`, `name` and `symbol` semantics from the ERC-20 specification. An implementation may also include a function `decimals` that returns `uint8(0)` if its goal is to be more compatible with ERC-20 while supporting this standard. However, we find it contrived to require all ERC-721 implementations to support the `decimals` function. - -Example NFT implementations as of February 2018: - -- CryptoKitties -- Compatible with an earlier version of this standard. -- CryptoPunks -- Partially ERC-20 compatible, but not easily generalizable because it includes auction functionality directly in the contract and uses function names that explicitly refer to the assets as "punks". -- Auctionhouse Asset Interface -- The author needed a generic interface for the Auctionhouse ÐApp (currently ice-boxed). His "Asset" contract is very simple, but is missing ERC-20 compatibility, `approve()` functionality, and metadata. This effort is referenced in the discussion for EIP-173. - -Note: "Limited edition, collectible tokens" like Curio Cards and Rare Pepe are *not* distinguishable assets. They're actually a collection of individual fungible tokens, each of which is tracked by its own smart contract with its own total supply (which may be `1` in extreme cases). - -The `onERC721Received` function specifically works around old deployed contracts which may inadvertently return 1 (`true`) in certain circumstances even if they don't implement a function (see Solidity DelegateCallReturnValue bug). By returning and checking for a magic value, we are able to distinguish actual affirmative responses versus these vacuous `true`s. - -## Test Cases - -0xcert ERC-721 Token includes test cases written using Truffle. - -## Implementations - -0xcert ERC721 -- a reference implementation - -- MIT licensed, so you can freely use it for your projects -- Includes test cases -- Active bug bounty, you will be paid if you find errors - -Su Squares -- an advertising platform where you can rent space and place images - -- Complete the Su Squares Bug Bounty Program to seek problems with this standard or its implementation -- Implements the complete standard and all optional interfaces - -ERC721ExampleDeed -- an example implementation - -- Implements using the OpenZeppelin project format - -XXXXERC721, by William Entriken -- a scalable example implementation - -- Deployed on testnet with 1 billion assets and supporting all lookups with the metadata extension. This demonstrates that scaling is NOT a problem. - -## References - -**Standards** - -1. [ERC-20](./eip-20.md) Token Standard. -1. [ERC-165](./eip-165.md) Standard Interface Detection. -1. [ERC-173](./eip-173.md) Owned Standard. -1. [ERC-223](https://github.com/ethereum/EIPs/issues/223) Token Standard. -1. [ERC-677](https://github.com/ethereum/EIPs/issues/677) `transferAndCall` Token Standard. -1. [ERC-827](https://github.com/ethereum/EIPs/issues/827) Token Standard. -1. Ethereum Name Service (ENS). https://ens.domains -1. Instagram -- What's the Image Resolution? https://help.instagram.com/1631821640426723 -1. JSON Schema. https://json-schema.org/ -1. Multiaddr. https://github.com/multiformats/multiaddr -1. RFC 2119 Key words for use in RFCs to Indicate Requirement Levels. https://www.ietf.org/rfc/rfc2119.txt - -**Issues** - -1. The Original ERC-721 Issue. https://github.com/ethereum/eips/issues/721 -1. Solidity Issue \#2330 -- Interface Functions are External. https://github.com/ethereum/solidity/issues/2330 -1. Solidity Issue \#3412 -- Implement Interface: Allow Stricter Mutability. https://github.com/ethereum/solidity/issues/3412 -1. Solidity Issue \#3419 -- Interfaces Can't Inherit. https://github.com/ethereum/solidity/issues/3419 -1. Solidity Issue \#3494 -- Compiler Incorrectly Reasons About the `selector` Function. https://github.com/ethereum/solidity/issues/3494 -1. Solidity Issue \#3544 -- Cannot Calculate Selector of Function Named `transfer`. https://github.com/ethereum/solidity/issues/3544 -1. CryptoKitties Bounty Issue \#4 -- Listing all Kitties Owned by a User is `O(n^2)`. https://github.com/axiomzen/cryptokitties-bounty/issues/4 -1. OpenZeppelin Issue \#438 -- Implementation of `approve` method violates ERC20 standard. https://github.com/OpenZeppelin/zeppelin-solidity/issues/438 -1. Solidity DelegateCallReturnValue Bug. https://solidity.readthedocs.io/en/develop/bugs.html#DelegateCallReturnValue - -**Discussions** - -1. Reddit (announcement of first live discussion). https://www.reddit.com/r/ethereum/comments/7r2ena/friday_119_live_discussion_on_erc_nonfungible/ -1. Gitter #EIPs (announcement of first live discussion). https://gitter.im/ethereum/EIPs?at=5a5f823fb48e8c3566f0a5e7 -1. ERC-721 (announcement of first live discussion). https://github.com/ethereum/eips/issues/721#issuecomment-358369377 -1. ETHDenver 2018. https://ethdenver.com - -**NFT Implementations and Other Projects** - -1. CryptoKitties. https://www.cryptokitties.co -1. 0xcert ERC-721 Token. https://github.com/0xcert/ethereum-erc721 -1. Su Squares. https://tenthousandsu.com -1. Decentraland. https://decentraland.org -1. CryptoPunks. https://www.larvalabs.com/cryptopunks -1. DMarket. https://www.dmarket.io -1. Enjin Coin. https://enjincoin.io -1. Ubitquity. https://www.ubitquity.io -1. Propy. https://tokensale.propy.com -1. CryptoKitties Deployed Contract. https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code -1. Su Squares Bug Bounty Program. https://github.com/fulldecent/su-squares-bounty -1. XXXXERC721. https://github.com/fulldecent/erc721-example -1. ERC721ExampleDeed. https://github.com/nastassiasachs/ERC721ExampleDeed -1. Curio Cards. https://mycuriocards.com -1. Rare Pepe. https://rarepepewallet.com -1. Auctionhouse Asset Interface. https://github.com/dob/auctionhouse/blob/master/contracts/Asset.sol -1. OpenZeppelin SafeERC20.sol Implementation. https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/SafeERC20.sol - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-721.md diff --git a/EIPS/eip-7212.md b/EIPS/eip-7212.md new file mode 100644 index 00000000000000..37f49cd9654be8 --- /dev/null +++ b/EIPS/eip-7212.md @@ -0,0 +1,188 @@ +--- +eip: 7212 +title: Precompile for secp256r1 Curve Support +description: Proposal to add precompiled contract that performs signature verifications in the “secp256r1” elliptic curve. +author: Ulaş Erdoğan (@ulerdogan), Doğan Alpaslan (@doganalpaslan), DC Posch (@dcposch), Nalin Bhardwaj (@nalinbhardwaj) +discussions-to: https://ethereum-magicians.org/t/eip-7212-precompiled-for-secp256r1-curve-support/14789 +status: Review +type: Standards Track +category: Core +created: 2023-06-22 +--- + +## Abstract + +This proposal creates a precompiled contract that performs signature verifications in the “secp256r1” elliptic curve by given parameters of message hash, `r` and `s` components of the signature, `x` and `y` coordinates of the public key. So that, any EVM chain - principally Ethereum rollups - will be able to integrate this precompiled contract easily. + +## Motivation + +“secp256r1” elliptic curve is a standardized curve by NIST which has the same calculations by different input parameters with “secp256k1” elliptic curve used by the “ecrecover” precompiled contract. The cost of combined attacks and the security conditions are almost the same for both curves. Adding a precompiled contract which is similar to "ecrecover" can provide signature verifications using the “secp256r1” elliptic curve in the smart contracts and multi-faceted benefits can occur. One important factor is that this curve is widely used and supported in many modern devices such as Apple’s Secure Enclave, Webauthn, Android Keychain which proves the user adoption. Additionally, the introduction of this precompiled contract could enable valuable features in the account abstraction which allows more efficient and flexible management of accounts by transaction signs in mobile devices. +Most of the modern devices and applications rely on the “secp256r1” elliptic curve. The addition of this precompiled contract enables the verification of device native transaction signing mechanisms. For example: + +1. **Apple's Secure Enclave:** There is a separate “Trusted Execution Environment” in Apple hardware which can sign arbitrary messages and can only be accessed by biometric identification. +2. **Webauthn:** Web Authentication (WebAuthn) is a web standard published by the World Wide Web Consortium (W3C). WebAuthn aims to standardize an interface for authenticating users to web-based applications and services using public-key cryptography. It is being used by almost all of the modern web browsers. +3. **Android Keystore:** Android Keystore is an API that manages the private keys and signing methods. The private keys are not processed while using Keystore as the applications’ signing method. Also, it can be done in the “Trusted Execution Environment” in the microchip. +4. **Passkeys:** Passkeys is utilizing FIDO Alliance and W3C standards. It replaces passwords with cryptographic key-pairs which is also can be used for the elliptic curve cryptography. + +Modern devices have these signing mechanisms that are designed to be more secure and they are able to sign transaction data, but none of the current wallets are utilizing these signing mechanisms. So, these secure signing methods can be enabled by the proposed precompiled contract to initiate the transactions natively from the devices and also, can be used for the key management. This proposal aims to reach maximum security and convenience for the key management. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +As of `FORK_TIMESTAMP` in the integrated EVM chain, add precompiled contract `P256VERIFY` for signature verifications in the “secp256r1” elliptic curve at address `PRECOMPILED_ADDRESS` in `0x0b`. + +### Elliptic Curve Information + +“secp256r1” is a specific elliptic curve, also known as “P-256” and “prime256v1” curves. The curve is defined with the following equation and domain parameters: + +``` +# curve: short weierstrass form +y^2 ≡ x^3 + ax + b + +# p: curve prime field modulus +0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff + +# a: elliptic curve short weierstrass first coefficient +0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc + +# b: elliptic curve short weierstrass second coefficient +0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b + +# G: base point of the subgroup +(0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, + 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5) + +# n: subgroup order (number of points) +0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 + +# h: cofactor of the subgroup +0x1 + +``` + +### Elliptic Curve Signature Verification Steps + +The signature verifying algorithm takes the signed message hash, the signature components provided by the “secp256r1” curve algorithm, and the public key derived from the signer private key. The verification can be done with the following steps: + +``` +# h (message hash) +# pubKey = (public key of the signer private key) + +# Calculate the modular inverse of the signature proof: +s1 = s^(−1) (mod n) + +# Recover the random point used during the signing: +R' = (h * s1) * G + (r * s1) * pubKey + +# Take from R' its x-coordinate: +r' = R'.x + +# Calculate the signature validation result by comparing whether: +r' == r + +``` + +### Required Checks in Verification + +The following requirements **MUST** be checked by the precompiled contract to verify signature components are valid: + +- Verify that the `r` and `s` values are in `(0, n)` (exclusive) where `n` is the order of the subgroup. +- Verify that the point formed by `(x, y)` is on the curve and that both `x` and `y` are in `[0, p)` (inclusive 0, exclusive p) where `p` is the prime field modulus. Note that many implementations use `(0, 0)` as the reference point at infinity, which is not on the curve and should therefore be rejected. + +### Precompiled Contract Specification + +The `P256VERIFY` precompiled contract is proposed with the following input and outputs, which are big-endian values: + +- **Input data:** 160 bytes of data including: + - 32 bytes of the signed data `hash` + - 32 bytes of the `r` component of the signature + - 32 bytes of the `s` component of the signature + - 32 bytes of the `x` coordinate of the public key + - 32 bytes of the `y` coordinate of the public key +- **Output data:** 32 bytes of result data and error + - If the signature verification process succeeds, it returns 1 in 32 bytes format. + +### Precompiled Contract Gas Usage + +The use of signature verification cost by `P256VERIFY` is `3450` gas. Following reasons and calculations are provided in the [Rationale](#rationale) and [Test Cases](#test-cases) sections. + +## Rationale + +“secp256r1” ECDSA signatures consist of `v`, `r`, and `s` components. While the `v` value makes it possible to recover the public key of the signer, most signers do not generate the `v` component of the signature since `r` and `s` are sufficient for verification. In order to provide an exact and more compatible implementation, verification is preferred over recovery for the precompile. + +Existing P256 implementations verify `(x, y, r, s)` directly. We've chosen to match this style here, encoding each argument for the EVM as a `uint256`. + +This is different from the `ecrecover` precompiled address specification. The advantage is that it 1. follows the NIST specification (as defined in NIST FIPS 186-5 Digital Signature Standard (DSS)), 2. matches the rest of the (large) P256 ecosystem, and most importantly 3. allows execution clients to use existing well-vetted verifier implementations and test vectors. + +Another important difference is that the NIST FIPS 186-5 specification does not include a malleability check. We've matched that here in order to maximize compatibility with the large existing NIST P-256 ecosystem. + +Wrapper libraries **SHOULD** add a malleability check by default, with functions wrapping the raw precompile call (exact NIST FIPS 186-5 spec, without malleability check) clearly identified. For example, `P256.verifySignature` and `P256.verifySignatureWithoutMalleabilityCheck`. Adding the malleability check is straightforward and costs minimal gas. + +The `PRECOMPILED_ADDRESS` is chosen as `0x0b` as it is the next available address in the precompiled address set. + +The gas cost is proposed by comparing the performance of the `P256VERIFY` and the `ECRECOVER` precompiled contract which is implemented in the EVM at `0x01` address. It is seen that “secp256r1” signature verification is ~15% slower (elaborated in [test cases](#test-cases)) than “secp256k1” signature recovery, so `3450` gas is proposed by comparison which causes similar “mgas/op” values in both precompiled contracts. + +## Backwards Compatibility + +No backward compatibility issues found as the precompiled contract will be added to `PRECOMPILED_ADDRESS` at the next available address in the precompiled address set. + +## Test Cases + +Functional tests are applied for multiple cases in the [reference implementation](#reference-implementation) of `P256VERIFY` precompiled contract and they succeed. Benchmark tests are also applied for both `P256VERIFY` and `ECRECOVER` with some pre-calculated data and signatures in the “go-ethereum”s precompile testing structure to propose a meaningful gas cost for the “secp256r1” signature verifications by the precompiled contract implemented in the [reference implementation](#reference-implementation). The benchmark test results by example data in the assets can be checked: + +- [P256Verify Benchmark Test Results](../assets/eip-7212/p256Verify_benchmark_test) +- [Ecrecover Benchmark Test Results](../assets/eip-7212/ecrecover_benchmark_test) + +``` +# results of geth benchmark tests of +# ECRECOVER and P256VERIFY (reference implementation) +# by benchstat tool + +goos: darwin +goarch: arm64 +pkg: github.com/ethereum/go-ethereum/core/vm + │ compare_p256Verify │ compare_ecrecover │ + │ sec/op │ sec/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 57.75µ ± 1% +PrecompiledEcrecover/-Gas=3000-8 50.48µ ± 1% +geomean 57.75µ 50.48µ + + │ compare_p256Verify │ compare_ecrecover │ + │ gas/op │ gas/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 3.450k ± 0% +PrecompiledEcrecover/-Gas=3000-8 3.000k ± 0% +geomean 3.450k 3.000k + + │ compare_p256Verify │ compare_ecrecover │ + │ mgas/s │ mgas/s │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 59.73 ± 1% +PrecompiledEcrecover/-Gas=3000-8 59.42 ± 1% +geomean 59.73 59.42 + + │ compare_p256Verify │ compare_ecrecover │ + │ B/op │ B/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 1.523Ki ± 0% +PrecompiledEcrecover/-Gas=3000-8 800.0 ± 0% +geomean 1.523Ki 800.0 + + │ compare_p256Verify │ compare_ecrecover │ + │ allocs/op │ allocs/op │ +PrecompiledP256Verify/p256Verify-Gas=3450-8 33.00 ± 0% +PrecompiledEcrecover/-Gas=3000-8 7.000 ± 0% +geomean 33.00 7.000 + +``` + +## Reference Implementation + +Implementation of the `P256VERIFY` precompiled contract is applied to go-ethereum client to create a reference. Also, a “secp256r1” package has already been included in the Besu Native library which is used by Besu client. Other client implementations are in the future roadmap. + +## Security Considerations + +The changes are not directly affecting the protocol security, it is related with the applications using `P256VERIFY` for the signature verifications. The “secp256r1” curve has been using in many other protocols and services and there is not any security issues in the past. + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7231.md b/EIPS/eip-7231.md new file mode 100644 index 00000000000000..0f9488023b4d1a --- /dev/null +++ b/EIPS/eip-7231.md @@ -0,0 +1,7 @@ +--- +eip: 7231 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7231.md diff --git a/EIPS/eip-725.md b/EIPS/eip-725.md index 08452e2464d570..bf82fa147c2b32 100644 --- a/EIPS/eip-725.md +++ b/EIPS/eip-725.md @@ -1,353 +1,7 @@ --- eip: 725 -title: General data key/value store and execution -description: An interface for a smart contract based account with attachable data key/value store -author: Fabian Vogelsteller (@frozeman), Tyler Yasaka (@tyleryasaka) -discussions-to: https://ethereum-magicians.org/t/discussion-for-eip725/12158 -status: Draft -type: Standards Track category: ERC -created: 2017-10-02 -requires: 165, 173 +status: Moved --- -## Abstract - -The following describes two standards that allow for a generic data storage in a smart contract and a generic execution through a smart contract. These can be used separately or in conjunction and can serve as building blocks for smart contract accounts, upgradable metadata, and other means. - -## Motivation - -The initial motivation came out of the need to create a smart contract account system that's flexible enough to be viable long-term but also defined enough to be standardized. They are a generic set of two standardized building blocks to be used in all forms of smart contracts. - -This standard consists of two sub-standards, a generic data key/value store (`ERC725Y`) and a generic execute function (`ERC725X`). Both of these in combination allow for a very flexible and long-lasting account system. The account version of `ERC725` is standardized under `LSP0-ERC725Account`. - -These standards (`ERC725` X and Y) can also be used separately as `ERC725Y` can be used to enhance NFTs and Token metadata or other types of smart contracts. `ERC725X` allows for a generic execution through a smart contract, functioning as an account or actor. - -## Specification - -### Ownership - -This contract is controlled by a single owner. The owner can be a smart contract or an external account. -This standard requires [EIP-173](./eip-173.md) and SHOULD implement the functions: - -- `owner() view` -- `transferOwnership(address newOwner)` - -And the event: - -- `OwnershipTransferred(address indexed previousOwner, address indexed newOwner)` - ---- - -### `ERC725X` - -**`ERC725X`** interface id according to [EIP-165](./eip-165.md): `0x570ef073`. - -Smart contracts implementing the `ERC725X` standard MUST implement the [EIP-165](./eip-165.md) `supportsInterface(..)` function and MUST support the `ERC165` and `ERC725X` interface ids. - -### `ERC725X` Methods - -Smart contracts implementing the `ERC725X` standard SHOULD implement all of the functions listed below: - -#### execute - -```solidity -function execute(uint256 operationType, address target, uint256 value, bytes memory data) external payable returns(bytes memory) -``` - -Function Selector: `0x44c028fe` - -Executes a call on any other smart contracts or address, transfers the blockchains native token, or deploys a new smart contract. - - -_Parameters:_ - -- `operationType`: the operation type used to execute. -- `target`: the smart contract or address to call. `target` will be unused if a contract is created (operation types 1 and 2). -- `value`: the amount of native tokens to transfer (in Wei). -- `data`: the call data, or the creation bytecode of the contract to deploy. - - -_Requirements:_ - -- MUST only be called by the current owner of the contract. -- MUST revert when the execution or the contract creation fails. -- `target` SHOULD be address(0) in case of contract creation with `CREATE` and `CREATE2` (operation types 1 and 2). -- `value` SHOULD be zero in case of `STATICCALL` or `DELEGATECALL` (operation types 3 and 4). - - -_Returns:_ `bytes` , the returned data of the called function, or the address of the contract deployed (operation types 1 and 2). - -**Triggers Event:** [ContractCreated](#contractcreated), [Executed](#executed) - -The following `operationType` COULD exist: - -- `0` for `CALL` -- `1` for `CREATE` -- `2` for `CREATE2` -- `3` for `STATICCALL` -- `4` for `DELEGATECALL` - **NOTE** This is a potentially dangerous operation type - -Others may be added in the future. - -#### data parameter - -- For operationType, `CALL`, `STATICCALL` and `DELEGATECALL` the data field can be random bytes or an abi-encoded function call. - -- For operationType, `CREATE` the `data` field is the creation bytecode of the contract to deploy appended with the constructor argument(s) abi-encoded. - -- For operationType, `CREATE2` the `data` field is the creation bytecode of the contract to deploy appended with: - 1. the constructor argument(s) abi-encoded - 2. a `bytes32` salt. - -``` -data = + + -``` - -> See [EIP-1014: Skinny CREATE2](./eip-1014.md) for more information. - -#### execute (Array) - -```solidity -function execute(uint256[] memory operationsType, address[] memory targets, uint256[] memory values, bytes[] memory datas) external payable returns(bytes[] memory) -``` - -Function Selector: `0x13ced88d` - -Executes a batch of calls on any other smart contracts, transfers the blockchain native token, or deploys a new smart contract. - -_Parameters:_ - -- `operationsType`: the list of operations type used to execute. -- `targets`: the list of addresses to call. `targets` will be unused if a contract is created (operation types 1 and 2). -- `values`: the list of native token amounts to transfer (in Wei). -- `datas`: the list of call data, or the creation bytecode of the contract to deploy. - -_Requirements:_ - -- Parameters array MUST have the same length. -- MUST only be called by the current owner of the contract. -- MUST revert when the execution or the contract creation fails. -- `target` SHOULD be address(0) in case of contract creation with `CREATE` and `CREATE2` (operation types 1 and 2). -- `value` SHOULD be zero in case of `STATICCALL` or `DELEGATECALL` (operation types 3 and 4). - -_Returns:_ `bytes[]` , array list of returned data of the called function, or the address(es) of the contract deployed (operation types 1 and 2). - -**Triggers Event:** [ContractCreated](#contractcreated), [Executed](#executed) on each call iteration - - -**Note:** The `execute()` functions use function overloading, therefore it is better to reference them by the given function signature as follows: - -```js -// web3.js example - -// execute -myContract.methods['execute(uint256,address,uint256,bytes)'](OPERATION_CALL, target.address, 2WEI, "0x").send(); -// execute Array -myContract.methods['execute(uint256[],address[],uint256[],bytes[])']([OPERATION_CALL, OPERATION_CREATE], [target.address, ZERO_ADDRESS], [2WEI, 0WEI], ["0x", CONTRACT_BYTECODE]).send(); - -// OR - -// execute -myContract.methods['0x44c028fe'](OPERATION_CALL, target.address, 2WEI, "0x").send(); -// execute Array -myContract.methods['0x13ced88d']([OPERATION_CALL, OPERATION_CREATE], [target.address, ZERO_ADDRESS], [2WEI, 0WEI], ["0x", CONTRACT_BYTECODE]).send(); -``` - -### `ERC725X` Events - -#### Executed - -```solidity -event Executed(uint256 indexed operationType, address indexed target, uint256 indexed value, bytes4 data); -``` - -MUST be triggered when `execute` creates a new call using the `operationType` `0`, `3`, `4`. - -#### ContractCreated - -```solidity -event ContractCreated(uint256 indexed operationType, address indexed contractAddress, uint256 indexed value, bytes32 salt); -``` - -MUST be triggered when `execute` creates a new contract using the `operationType` `1`, `2`. - ---- - -### `ERC725Y` - -**`ERC725Y`** interface id according to [EIP-165](./eip-165.md): `0x714df77c`. - -Smart contracts implementing the `ERC725Y` standard MUST implement the [EIP-165](./eip-165.md) `supportsInterface(..)` function and MUST support the `ERC165` and `ERC725Y` interface ids. - -### `ERC725Y` Methods - -Smart contracts implementing the `ERC725Y` standard MUST implement all of the functions listed below: - -#### getData - -```solidity -function getData(bytes32 dataKey) external view returns(bytes memory) -``` - -Function Selector: `0x54f6127f` - -Gets the data set for the given data key. - -_Parameters:_ - -- `dataKey`: the data key which value to retrieve. - -_Returns:_ `bytes` , The data for the requested data key. - -#### getData (Array) - -```solidity -function getData(bytes32[] memory dataKeys) external view returns(bytes[] memory) -``` - -Function Selector: `0x4e3e6e9c` - -Gets array of data at multiple given data keys. - -_Parameters:_ - -- `dataKeys`: the data keys which values to retrieve. - -_Returns:_ `bytes[]` , array of data values for the requested data keys. - -#### setData - -```solidity -function setData(bytes32 dataKey, bytes memory dataValue) external -``` - -Function Selector: `0x7f23690c` - -Sets data as bytes in the storage for a single data key. - -_Parameters:_ - -- `dataKey`: the data key which value to set. -- `dataValue`: the data to store. - -_Requirements:_ - -- MUST only be called by the current owner of the contract. - -**Triggers Event:** [DataChanged](#datachanged) - -#### setData (Array) - -```solidity -function setData(bytes32[] memory dataKeys, bytes[] memory dataValues) external -``` - -Function Selector: `0x14a6e293` - -Sets array of data at multiple data keys. MUST only be called by the current owner of the contract. - -_Parameters:_ - -- `dataKeys`: the data keys which values to set. -- `dataValues`: the array of bytes to set. - -_Requirements:_ - -- Array parameters MUST have the same length. -- MUST only be called by the current owner of the contract. - -**Triggers Event:** [DataChanged](#datachanged) - -**Note:** `setData()` and `getData()` uses function overloading, therefore it is better to reference them by the given function signature as follows: - -```js -// web3.js example - -// setData -myContract.methods['setData(bytes32,bytes)'](dataKey, dataValue).send(); -// setData Array -myContract.methods['setData(bytes32[],bytes[])']([dataKeys, ...], [dataValues, ...]).send(); - -// OR - -// setData -myContract.methods['0x7f23690c'](dataKey, dataValue).send(); -// setData Array -myContract.methods['0x14a6e293']([dataKeys, ...], [dataValues, ...]).send(); -``` - -### `ERC725Y` Events - -#### DataChanged - -```solidity -event DataChanged(bytes32 indexed dataKey, bytes dataValue) -``` - -MUST be triggered when a data key was successfully set. - -### `ERC725Y` Data keys - -Data keys, are the way to retrieve values via `getData()`. These `bytes32` values can be freely chosen, or defined by a standard. -A common way to define data keys is the hash of a word, e.g. `keccak256('ERCXXXMyNewKeyType')` which results in: `0x6935a24ea384927f250ee0b954ed498cd9203fc5d2bf95c735e52e6ca675e047` - -The `LSP2-ERC725JSONSchema` standard is a more explicit `ERC725Y` data key standard, that defines key types and value types, and their encoding and decoding. - -## Rationale - -The generic way of storing data keys with values was chosen to allow upgradability over time. Stored data values can be changed over time. Other smart contract protocols can then interpret this data in new ways and react to interactions from a `ERC725` smart contract differently. - -The data stored in an `ERC725Y` smart contract is not only readable/writable by off-chain applications, but also by other smart contracts. Function overloading was used to allow for the retrievable of single and multiple keys, to keep gas costs minimal for both use cases. - -## Backwards Compatibility - -All contracts since `ERC725v2` from 2018/19 should be compatible with the current version of the standard. Mainly interface ID and Event parameters have changed, while `getData(bytes32[])` and `setData(bytes32[], bytes[])` was added as an efficient way to set/get multiple keys at once. The same applies to execution, as `execute(..[])` was added as an efficient way to batch calls. - -## Reference Implementation - -Reference implementations can be found in [`ERC725.sol`](../assets/eip-725/ERC725.sol). - -## Security Considerations - -This contract allows generic executions, therefore special care needs to be taken to prevent re-entrancy attacks and other forms of call chain attacks. - -When using the operation type `4` for `delegatecall`, it is important to consider that the called contracts can alter the state of the calling contract and also change owner variables and `ERC725Y` data storage entries at will. Additionally calls to `selfdestruct` are possible and other harmful state-changing operations. - -### Solidity Interfaces - -```solidity -// SPDX-License-Identifier: CC0-1.0 - -pragma solidity >=0.5.0 <0.7.0; - -// ERC165 identifier: `0x570ef073` -interface IERC725X /* is ERC165, ERC173 */ { - - event Executed(uint256 indexed operationType, address indexed target, uint256 indexed value, bytes4 data); - event ContractCreated(uint256 indexed operationType, address indexed contractAddress, uint256 indexed value, bytes32 salt); - - - function execute(uint256 operationType, address target, uint256 value, bytes memory data) external payable returns(bytes memory); - - function execute(uint256[] memory operationsType, address[] memory targets, uint256[] memory values, bytes memory datas) external payable returns(bytes[] memory); -} - -// ERC165 identifier: `0x714df77c` -interface IERC725Y /* is ERC165, ERC173 */ { - - event DataChanged(bytes32 indexed dataKey, bytes dataValue); - - function getData(bytes32 dataKey) external view returns(bytes memory); - function getData(bytes32[] memory dataKeys) external view returns(bytes[] memory); - - function setData(bytes32 dataKey, bytes memory dataValue) external; - function setData(bytes32[] memory dataKeys, bytes[] memory dataValues) external; -} -interface IERC725 /* is IERC725X, IERC725Y */ { -} -``` - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-725.md diff --git a/EIPS/eip-7251.md b/EIPS/eip-7251.md new file mode 100644 index 00000000000000..b947bdf83501e6 --- /dev/null +++ b/EIPS/eip-7251.md @@ -0,0 +1,609 @@ +--- +eip: 7251 +title: Increase the MAX_EFFECTIVE_BALANCE +description: Allow validators to have larger effective balances, while maintaining the 32 ETH lower bound. +author: mike (@michaelneuder), Francesco (@fradamt), dapplion (@dapplion), Mikhail (@mkalinin), Aditya (@adiasg), Justin (@justindrake), lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-7251-increase-the-max-effective-balance/15982 +status: Review +type: Standards Track +category: Core +created: 2023-06-28 +requires: 7002, 7685 +--- +## Abstract + +Increases the constant `MAX_EFFECTIVE_BALANCE`, while keeping the minimum staking balance `32 ETH`. This permits large node operators to consolidate into fewer validators while also allowing solo-stakers to earn compounding rewards and stake in more flexible increments. + +## Motivation + +As of October 3, 2023, there are currently over 830,000 validators participating in the consensus layer. The size of this set continues to grow due, in part, to the `MAX_EFFECTIVE_BALANCE`, which limits the stake of a single validator to `32 ETH`. This leads to large amounts of "redundant validators", which are controlled by a single entity, possibly running on the same beacon node, but with distinct BLS signing keys. The limit on the `MAX_EFFECTIVE_BALANCE` is technical debt from the original sharding design, in which subcommittees (not the attesting committee but the committee calculated in `is_aggregator`) needed to be majority honest. As a result, keeping the weights of subcommittee members approximately equal reduced the risk of a single large validator containing too much influence. Under the current design, these subcommittees are only used for attestation aggregation, and thus only have a `1/N` honesty assumption. + +With the security model of the protocol no longer dependent on a low value for `MAX_EFFECTIVE_BALANCE`, we propose raising this value while keeping the minimum validator threshold of `32 ETH`. This increase aims to reduce the validator set size, thereby reducing the number of P2P messages over the network, the number of BLS signatures that need to be aggregated each epoch, and the `BeaconState` memory footprint. This change adds value for both small and large validators. Large validators can consolidate to run fewer validators and thus fewer beacon nodes. Small validators now benefit from compounding rewards and the ability to stake in more flexible increments (e.g., the ability to stake `40 ETH` instead of needing to accumulate `64 ETH` to run two validators today). + +## Specification + +### Constants + +#### Execution layer + +| Name | Value | Comment | +| - | - | - | +| `CONSOLIDATION_REQUEST_TYPE` | `0x02` | The [EIP-7685](./eip-7685.md) type prefix for consolidation request | +| `CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS` | `0x` | Where to call and store relevant details about consolidation requests mechanism | +| `SYSTEM_ADDRESS` | `0xfffffffffffffffffffffffffffffffffffffffe` | Address used to invoke system operation on contract | +| `EXCESS_CONSOLIDATION_REQUESTS_STORAGE_SLOT` | `0` | | +| `CONSOLIDATION_REQUEST_COUNT_STORAGE_SLOT` | `1` | | +| `CONSOLIDATION_REQUEST_QUEUE_HEAD_STORAGE_SLOT` | `2` | Pointer to head of the consolidation request message queue | +| `CONSOLIDATION_REQUEST_QUEUE_TAIL_STORAGE_SLOT` | `3` | Pointer to the tail of the consolidation request message queue | +| `CONSOLIDATION_REQUEST_QUEUE_STORAGE_OFFSET` | `4` | The start memory slot of the in-state consolidation request message queue | +| `MAX_CONSOLIDATION_REQUESTS_PER_BLOCK` | `1` | Maximum number of consolidation requests that can be dequeued into a block | +| `TARGET_CONSOLIDATION_REQUESTS_PER_BLOCK` | `1` | | +| `MIN_CONSOLIDATION_REQUEST_FEE` | `1` | | +| `CONSOLIDATION_REQUEST_FEE_UPDATE_FRACTION` | `17` | | +| `EXCESS_INHIBITOR` | `1181` | Excess value used to compute the fee before the first system call | +| `FORK_TIMESTAMP` | *TBD* | Mainnet | + +#### Consensus layer + +| Name | Value | +| - | - | +| `COMPOUNDING_WITHDRAWAL_PREFIX` | `Bytes1('0x02')` | +| `MIN_ACTIVATION_BALANCE` | `Gwei(2**5 * 10**9)` (32 ETH) | +| `MAX_EFFECTIVE_BALANCE` | `Gwei(2**11 * 10**9)` (2048 ETH) | + +### Execution layer + +#### Consolidation request + +The new consolidation request is an [EIP-7685](./eip-7685.md) request with type `0x02` consisting of the following fields: + +1. `source_address`: `Bytes20` +2. `source_pubkey`: `Bytes48` +3. `target_pubkey`: `Bytes48` + +The [EIP-7685](./eip-7685.md) encoding of a withdrawal request **MUST** be computed as the follows: + +```python +encoded = CONSOLIDATION_REQUEST_TYPE ++ rlp([source_address, source_pubkey, target_pubkey]) +``` + +#### Consolidation request contract + +The contract has three different code paths, which can be summarized at a high level as follows: + +1. Add consolidation request - requires a `96` byte input, concatenated public keys of the source and the target validators. +2. Excess consolidation requests getter - if the input length is zero, return the current excess consolidation requests count. +3. System process - if called by system address, pop off the consolidation requests for the current block from the queue. + +##### Add Consolidation Request + +If call data input to the contract is exactly `96` bytes, perform the following: + +1. Ensure enough ETH was sent to cover the current consolidation request fee (`check_fee()`) +2. Increase consolidation request count by `1` for the current block (`increment_count()`) +3. Insert a consolidation request into the queue for the source address and pubkeys of the source and the target (`insert_withdrawal_request_into_queue()`) + +Specifically, the functionality is defined in pseudocode as the function `add_consolidation_request()`: + +```python +def add_consolidation_request(Bytes48: source_pubkey, Bytes48: target_pubkey): + """ + Add consolidaiton request adds new request to the consolidation request queue, so long as a sufficient fee is provided. + """ + + # Verify sufficient fee was provided. + fee = get_fee() + require(msg.value >= fee, 'Insufficient value for fee') + + # Increment consolidaiton request count. + count = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_COUNT_STORAGE_SLOT) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_COUNT_STORAGE_SLOT, count + 1) + + # Insert into queue. + queue_tail_index = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_TAIL_STORAGE_SLOT) + queue_storage_slot = CONSOLIDATION_REQUEST_QUEUE_STORAGE_OFFSET + queue_tail_index * 4 + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot, msg.sender) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 1, source_pubkey[0:32]) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2, source_pubkey[32:48] ++ target_pubkey[0:16]) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 3, target_pubkey[16:48]) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_TAIL_STORAGE_SLOT, queue_tail_index + 1) +``` + +###### Fee calculation + +The following pseudocode can compute the cost an individual consolidation request, given a certain number of excess consolidation requests. + +```python +def get_fee() -> int: + excess = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, EXCESS_CONSOLIDATION_REQUESTS_STORAGE_SLOT) + return fake_exponential( + MIN_CONSOLIDATION_REQUEST_FEE, + excess, + CONSOLIDATION_REQUEST_FEE_UPDATE_FRACTION + ) + +def fake_exponential(factor: int, numerator: int, denominator: int) -> int: + i = 1 + output = 0 + numerator_accum = factor * denominator + while numerator_accum > 0: + output += numerator_accum + numerator_accum = (numerator_accum * numerator) // (denominator * i) + i += 1 + return output // denominator +``` + +##### Excess Consolidation Requests Getter + +```python +def get_excess_consolidation_requests(): + count = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, EXCESS_CONSOLIDATION_REQUESTS_STORAGE_SLOT) + return count +``` + +##### System Call + +If the contract is called as `SYSTEM_ADDRESS` with an empty input data, perform the following: + +* The contract's queue is updated based on consolidation requests dequeued and the consolidation requests queue head/tail are reset if the queue has been cleared (`dequeue_consolidation_requests()`) +* The contract's excess consolidation requests are updated based on usage in the current block (`update_excess_consolidation_requests()`) +* The contract's consolidation requests count is reset to `0` (`reset_consolidation_requests_count()`) + +Specifically, the functionality is defined in pseudocode as the function `process_consolidation_requests()`: + +```python +################### +# Public function # +################### + +def process_consolidation_requests(): + reqs = dequeue_consolidation_requests() + update_excess_consolidation_requests() + reset_consolidation_requests_count() + return reqs + +########### +# Helpers # +########### + +class ConsolidationRequest(object): + source_address: Bytes20 + source_pubkey: Bytes48 + target_pubkey: Bytes48 + +def dequeue_consolidation_requests(): + queue_head_index = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_HEAD_STORAGE_SLOT) + queue_tail_index = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_TAIL_STORAGE_SLOT) + num_in_queue = queue_tail_index - queue_head_index + num_dequeued = min(num_in_queue, MAX_CONSOLIDATION_REQUESTS_PER_BLOCK) + + reqs = [] + for i in range(num_dequeue): + queue_storage_slot = CONSOLIDATION_REQUEST_QUEUE_STORAGE_OFFSET + (queue_head_index + i) * 4 + source_address = address(sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot)[0:20]) + source_pubkey = ( + sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 1)[0:32] + sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2)[0:16] + ) + target_pubkey = ( + sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 2)[16:32] + sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, queue_storage_slot + 3)[0:32] + ) + req = ConsolidationRequest( + source_address=Bytes20(source_address), + source_pubkey=Bytes48(source_pubkey), + target_pubkey=Bytes48(target_pubkey) + ) + reqs.append(req) + + new_queue_head_index = queue_head_index + num_dequeued + if new_queue_head_index == queue_tail_index: + # Queue is empty, reset queue pointers + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_HEAD_STORAGE_SLOT, 0) + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_TAIL_STORAGE_SLOT, 0) + else: + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_QUEUE_HEAD_STORAGE_SLOT, new_queue_head_index) + + return reqs + +def update_excess_consolidation_requests(): + previous_excess = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, EXCESS_CONSOLIDATION_REQUESTS_STORAGE_SLOT) + # Check if excess needs to be reset to 0 for first iteration after activation + if previous_excess == EXCESS_INHIBITOR: + previous_excess = 0 + + count = sload(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_COUNT_STORAGE_SLOT) + + new_excess = 0 + if previous_excess + count > TARGET_CONSOLIDATION_REQUESTS_PER_BLOCK: + new_excess = previous_excess + count - TARGET_CONSOLIDATION_REQUESTS_PER_BLOCK + + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, EXCESS_CONSOLIDATION_REQUESTS_STORAGE_SLOT, new_excess) + +def reset_consolidation_requests_count(): + sstore(CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_COUNT_STORAGE_SLOT, 0) +``` + +##### Bytecode + +```asm +caller +push20 0xfffffffffffffffffffffffffffffffffffffffe +eq +push1 0x98 +jumpi + +calldatasize +iszero +iszero +push1 0x28 +jumpi + +push0 +sload +push0 +mstore +push1 0x20 +push0 +return + +jumpdest +calldatasize +push1 0x60 +eq +iszero +push2 0x0144 +jumpi + +push1 0x11 +push0 +sload +push1 0x01 +dup3 +mul +push1 0x01 +swap1 +push0 + +jumpdest +push0 +dup3 +gt +iszero +push1 0x59 +jumpi + +dup2 +add +swap1 +dup4 +mul +dup5 +dup4 +mul +swap1 +div +swap2 +push1 0x01 +add +swap2 +swap1 +push1 0x3e +jump + +jumpdest +swap1 +swap4 +swap1 +div +callvalue +lt +push2 0x0144 +jumpi + +push1 0x01 +sload +push1 0x01 +add +push1 0x01 +sstore +push1 0x03 +sload +dup1 +push1 0x04 +mul +push1 0x04 +add +caller +dup2 +sstore +push1 0x01 +add +push0 +calldataload +dup2 +sstore +push1 0x01 +add +push1 0x20 +calldataload +dup2 +sstore +push1 0x01 +add +push1 0x40 +calldataload +swap1 +sstore +push1 0x01 +add +push1 0x03 +sstore +stop + +jumpdest +push1 0x03 +sload +push1 0x02 +sload +dup1 +dup3 +sub +dup1 +push1 0x01 +gt +push1 0xac +jumpi + +pop +push1 0x01 + +jumpdest +push0 + +jumpdest +dup2 +dup2 +eq +push1 0xf1 +jumpi + +dup1 +push1 0x74 +mul +dup4 +dup3 +add +push1 0x04 +mul +push1 0x04 +add +dup1 +sload +swap1 +push1 0x01 +add +dup1 +sload +swap1 +push1 0x01 +add +dup1 +sload +swap1 +push1 0x01 +add +sload +swap3 +push1 0x60 +shl +dup5 +mstore +swap1 +dup4 +push1 0x14 +add +mstore +dup3 +push1 0x34 +add +mstore +swap1 +push1 0x54 +add +mstore +push1 0x01 +add +push1 0xae +jump + +jumpdest +swap2 +add +dup1 +swap3 +eq +push2 0x0103 +jumpi + +swap1 +push1 0x02 +sstore +push2 0x010e +jump + +jumpdest +swap1 +pop +push0 +push1 0x02 +sstore +push0 +push1 0x03 +sstore + +jumpdest +push0 +sload +dup1 +push2 0x049d +eq +iszero +push2 0x011d +jumpi + +pop +push0 + +jumpdest +push1 0x01 +sload +push1 0x01 +dup3 +dup3 +add +gt +push2 0x0132 +jumpi + +pop +pop +push0 +push2 0x0138 +jump + +jumpdest +add +push1 0x01 +swap1 +sub + +jumpdest +push0 +sstore +push0 +push1 0x01 +sstore +push1 0x74 +mul +push0 +return + +jumpdest +push0 +push0 +revert +``` + +##### Deployment + +The consolidation requests contract is deployed like any other smart contract. A special synthetic address is generated by working backwards from the desired deployment transaction: + +```json +{ + "type": "0x0", + "nonce": "0x0", + "to": null, + "gas": "0x3d090", + "gasPrice": "0xe8d4a51000", + "maxPriorityFeePerGas": null, + "maxFeePerGas": null, + "value": "0x0", + "input": "0x61049d5f5561014880600f5f395ff33373fffffffffffffffffffffffffffffffffffffffe146098573615156028575f545f5260205ff35b36606014156101445760115f54600182026001905f5b5f82111560595781019083028483029004916001019190603e565b90939004341061014457600154600101600155600354806004026004013381556001015f35815560010160203581556001016040359055600101600355005b6003546002548082038060011160ac575060015b5f5b81811460f15780607402838201600402600401805490600101805490600101805490600101549260601b84529083601401528260340152906054015260010160ae565b9101809214610103579060025561010e565b90505f6002555f6003555b5f548061049d141561011d57505f5b6001546001828201116101325750505f610138565b01600190035b5f555f6001556074025ff35b5f5ffd", + "v": "0x1b", + "r": "0x539", + "s": "0x13370066aa8fbe21ca1511", + "hash": "0x6de32a89ba4c0592fd2453f8838d6bb69d93a102723de5f4b0f046ddcf8b8fa9" +} +``` + +``` +Sender: 0xd6e25886D7B986C394156C31a48e84Ee0BA71f72 +Address: 0x00b42dbF2194e931E80326D950320f7d9Dbeac02 +``` + +#### Block processing + +At the end of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e. after processing all transactions and after performing the block body requests validations) clienst software **MUST** take the following steps: + +1. Call the contract as `SYSTEM_ADDRESS` and empty input data to trigger the system subroutine execute. +2. Check that consolidation requests in the [EIP-7685](./eip-7685.md) requests list matches the list returned from `dequeue_consolidation_requests()` function of the smart contract respecting the order of the returned requests. If this condition does not hold, the block **MUST** be deemed *invalid*. + +### Consensus layer + +The defining features of this EIP are: + +1. ***Increasing the `MAX_EFFECTIVE_BALANCE`, while creating a `MIN_ACTIVATION_BALANCE`.*** The core feature of allowing variable size validators. +2. ***Allowing for multiple validator indices to be combined through the protocol.*** A mechanism by which large node operators can combine validators without cycling through the exit and activation queues. +3. ***Permitting validators to set custom ceilings for their validator to indicate where the partial withdrawal sweep activates.*** Allows more flexibility in defining the "ceiling" of a validator's effective balance. +4. ***Adding execution layer partial withdrawals (part of [EIP-7002](./eip-7002.md)).*** Allowing Execution Layer messages to trigger partial withdrawals in addition to full exits (e.g., a `100 ETH` validator can remove up to `68 ETH` without exiting the validator). +5. ***Removing the initial slashing penalty (still in discussion).*** This reduces the risk of consolidation for large validators. + +The [Rationale](#rationale) section contains an explanation for each of these proposed core features. A sketch of the resulting changes to the consensus layer is included below. + +1. Add `COMPOUNDING_WITHDRAWAL_PREFIX` and `MIN_ACTIVATION_BALANCE` constants, while updating the value of `MAX_EFFECTIVE_BALANCE`. +2. Create the `PendingDeposit` container, which is used to track incoming deposits in the weight-based rate limiting mechanism. +3. Update the `BeaconState` with fields needed for deposit and exit queue weight-based rate limiting. +4. Modify `is_eligible_for_activation_queue` to check against `MIN_ACTIVATION_BALANCE` rather than `MAX_EFFECTIVE_BALANCE`. +5. Modify `get_validator_churn_limit` to depend on the validator weight rather than the validator count. +6. Create a helper `compute_exit_epoch_and_update_churn` to calculate the exit epoch based on the current pending withdrawals. +6. Modify `initiate_validator_exit` to rate limit the exit queue by balance rather than the number of validators. +7. Modify `initialize_beacon_state_from_eth1` to use `MIN_ACTIVATION_BALANCE`. +9. Modify `process_registry_updates` to activate all eligible validators. +10. Add a per-epoch helper, `process_pending_balance_deposits`, to consume some of the pending deposits. +10. Modify `get_validator_from_deposit` to initialize the effective balance to zero (it's updated by the pending deposit flow). +11. Modify `apply_deposit` to store incoming deposits in `state.pending_balance_deposits`. +12. Modify `is_aggregator` to be weight-based. +13. Modify `compute_weak_subjectivity_period` to use the new churn limit function. +14. Add `has_compounding_withdrawal_credential` to check for the `0x02` credential. +15. Modify `is_fully_withdrawable_validator` to check for compounding credentials. +16. Add `get_validator_excess_balance` to calculate the excess balance of validators. +17. Modify `is_partially_withdrawable_validator` to check for excess balance. +18. Modify `get_expected_withdrawals` to use excess balance. + + + +## Rationale + +This EIP aims to reduce the total number of validators without changing anything about the economic security of the protocol. It provides a mechanism by which large node operators who control significant amounts of stake can consolidate into fewer validators. We analyze the reasoning behind each of the core features. + +1. ***Increasing the `MAX_EFFECTIVE_BALANCE`, while creating a `MIN_ACTIVATION_BALANCE`.*** + * *While increasing the `MAX_EFFECTIVE_BALANCE` to allow larger-stake validators, it is important to keep the lower bound of `32 ETH` (by introducing a new constant – `MIN_ACTIVATION_BALANCE`) to encourage solo-staking.* +2. ***Allowing for multiple validator indices to be combined through the protocol.*** + * *For large staking pools that already control thousands of validators, exiting and re-entering would be extremely slow and costly. The adoption of the EIP will be much higher by allowing in-protocol consolidation.* +3. ***Permitting validators to set custom ceilings for their validator to indicate where the partial withdrawal sweep activates.*** + * *To get access to rewards, validators might want the flexibility to set custom ceilings for their effective balance. This gives them more optionality and is a clean way to continue supporting the partial-withdrawal sweep (a gasless way to extract rewards).* +4. ***Adding execution layer partial withdrawals (part of [EIP-7002](./eip-7002.md)).*** + * *For validators that choose to raise their effective balance ceiling, allowing for custom partial withdrawals triggered from the execution layer increases the flexibility of the staking configurations. Validators can choose when and how much they withdraw but will have to pay gas for the EL transaction.* +5. ***Removing the initial slashing penalty (still in discussion).*** + * *To encourage consolidation, we could modify the slashing penalties. The biggest hit comes from the initial penalty of `1/32` of the validator's effective balance. Since this scales linearly on the effective balance, the higher-stake validators directly incur higher risk. By changing the scaling properties, we could make consolidation more attractive.* + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. These changes do not break anything related to current user activity and experience. + +## Security Considerations + +This change modifies committees and churn, but doesn't significantly impact the security properties. + +### Security of attestation committees + +Given full consolidation as the worst case, the probability of an adversarial takeover of a committee remains low. Even in a high consolidation scenario, the required share of honest validators remains well below the 2/3 supermajority needed for finality. + +### Aggregator selection + +In the original sharding roadmap, subcommittees were required to be secure with extremely high probability. Now with the sole responsibility of attestation aggregation, we only require each committee to have at least one honest aggregator. Currently, aggregators are selected through a VRF lottery, targeting several validator units that can be biased by non-consolidated attackers. This proposal changes the VRF lottery to consider weight, so the probability of having at least one honest aggregator is not worse. + +### Proposer selection probability + +Proposer selection is already weighted by the ratio of their effective balance to `MAX_EFFECTIVE_BALANCE`. Due to the lower probabilities, this change will slightly increase the time it takes to calculate the next proposer index. + +### Sync committee selection probability + +Sync committee selection is also already weighted by effective balance, so this proposal does not require modifications to the sync protocol. Light clients can still check that a super-majority of participants have signed an update irrespective of their weights since we maintain a weight-based selection probability. + +### Churn invariants + +This proposal maintains the activation and exit churn invariants limiting active weight instead of validator count. Balance top-ups are now handled explicitly, being subject to the same activation queue as full deposits. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7266.md b/EIPS/eip-7266.md new file mode 100644 index 00000000000000..5780c0723ffb98 --- /dev/null +++ b/EIPS/eip-7266.md @@ -0,0 +1,46 @@ +--- +eip: 7266 +title: Remove BLAKE2 compression precompile +description: Remove the blake2f (0x09) precompile by changing the precompile behaviour to result in an exceptional abort +author: Pascal Caversaccio (@pcaversaccio) +discussions-to: https://ethereum-magicians.org/t/discussion-removal-of-ripemd-160-and-blake2f-precompiles/14857 +status: Stagnant +type: Standards Track +category: Core +created: 2023-07-03 +--- + +## Abstract + +This EIP removes the [`blake2f`](./eip-152.md) (`0x09`) precompile by changing the precompile behaviour to result in an exceptional abort. + +## Motivation + +[EIP-152](./eip-152.md) has never capitalised on a real-world use case. This fact is clearly reflected in the number of times the address `0x09` has been invoked (numbers from the date this EIP was created): + +- The most recent call took place on 6 October 2022. +- Since its gone live as part of the Istanbul network upgrade on December 7 2019 (block number 9,069,000), `0x09` has been called only 22,131 times. + +One of the reasons why [EIP-152](./eip-152.md) has failed is that the envisioned use cases were not validated before inclusion. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +All `CALL`, `CALLCODE`, `DELEGATECALL`, and `STATICCALL` invocations to the `blake2f` precompile address `0x09` MUST result in an exceptional abort. + +## Rationale + +The EVM should be optimised for simplicity and future-proofness. The original Yellow Paper states: _these are so-called 'precompiled' contracts, meant as a preliminary piece of architecture that may later become native extensions_. Considering that no use cases have been realised in the last 3.5 years, we can conclude that the precompile `blake2f` (`0x09`) will never transition into a native opcode. In that sense, the precompile `blake2f` (`0x09`) is an obsolete carry-along with no real-world traction and thus should be removed. This removal will simplify the EVM to the extent that it only consists of clear instructions with real-world use cases. Eventually, the precompile `blake2f` (`0x09`) can be safely used as a test run for the phase-out and removal of EVM functions. + +## Backwards Compatibility + +This EIP requires a hard fork as it modifies the consensus rules. Note that very few applications are affected by this change and a lead time of 6-12 months can be considered sufficient. + +## Security Considerations + +There are no known additional security considerations introduced by this change. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7303.md b/EIPS/eip-7303.md new file mode 100644 index 00000000000000..2257e0af5d95b5 --- /dev/null +++ b/EIPS/eip-7303.md @@ -0,0 +1,7 @@ +--- +eip: 7303 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7303.md diff --git a/EIPS/eip-7329.md b/EIPS/eip-7329.md new file mode 100644 index 00000000000000..248cfd961974b6 --- /dev/null +++ b/EIPS/eip-7329.md @@ -0,0 +1,273 @@ +--- +eip: 7329 +title: ERC/EIP Repository split +description: Split the ERC specifications out of the EIP repository into a new repository, so that only core protocol EIPs remain +author: Lightclient (@lightclient), Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/proposal-forking-ercs-from-eips-repository/12804 +status: Final +type: Meta +created: 2023-07-13 +requires: 1 +--- + +## Abstract + +Describes the motivation and rational for splitting the EIP repositories into an +EIP repository, targeting core ethereum changes and an ERC repository, targeting +application layer specifications. + +## Motivation + +Long ago when the EIPs repository was created, there was a vision of a single +home for all standards related to Ethereum. The community was small and most +people were interacting at every level of the ecosystem. It made sense to +combine application standards with core consensus changes. + +Since then, the ecosystem has grown. Today, the chasm between application +development and core development is wide. Fewer people are involved across the +ecosystem (for better or worse); yet the repository remains unified. + +For years, we've considered separating the repository. This would allow ERC and +EIP specifications to evolve more naturally due to the independence. But it's +always difficult to reach critical threshold to make a change like this happen. +Each time we get lost in the details of the migration and the debate grinds +progress to a halt. + +Now that the Consensus Layer is also utilizing the EIP process, the cracks are +becoming more visible. There are changes we could make to the process that might +benefit them more, but because we also need to ensure the quality of ERCs, we +are restricted. + +There are also many more efforts to catalyze applications around the ERC +process. Attempts have been made to develop working groups and review groups for +certain ERC "categories" (a distinction that doesn't even technically exist +because of the unified repo). + +## Specification + +This specification only details with the initial mechanism of the split. The +particulars of how each repository will govern itself is out of scope for this +EIP, as it is the motivating point of this EIP that the divergent needs of the +community will require highly divergent methods. + +1. All ERCs and Interface-category EIPs are removed from this repository and + migrated to a new repo. The history should be intact so that repo should be + forked of this one with the non-ERCs removed. +2. The new ERCs repository goes live and includes the changes from the script. +3. Setup ercs.ethereum.org subdomain and update the CI to point to the ERCs + repo. +4. Set up a redirect for ERCs on eips.ethereum.org to go to the new website. +5. Create a unified document for editors to assign EIP/ERC numbers. EIPs and + ERCs will no longer be based on an initial PR number but on a number + incremented by the EIP editors of their respective repositories. EIPs will be + assigned even numbers and ERCs will be assigned odd numbers. The exact timing + of this migration is a policy decision of the editors. + +The EIP repository will be associated with core protocol changes, specifically +the kind that would be discussed in one of the AllCoreDevs calls; whereas the +ERC repository will be affiliated with all remaining areas such as smart +contract application interfaces, wallet standards, DeFi protocol standards, and +all other such improvements that do not require core protocol changes. + +This association is to persist across any other process changes the EIP editors +may introduce such as working groups, topic groups, expert groups, special +interest groups, splitting of the process, or other such changes. Any +sub-groupings that includes core protocol changes would be associated with the +EIP repository and other sub-groupings are associated with the ERC repository. +Any such process change are out of scope of this EIP and are independent of the +structural changes to the repositories specified in this EIP. + +There may be further structural changes to repository layouts to accommodate +more sub-groupings. Such proposals are out of scope of this EIP. + +## Rationale + +There are two major communities served by the EIP process that are highly +divergent and very differentiated in their needs. + +Let's consider the impact of specification ambiguity, the impacts are different +based on the community. The core protocol community has a low tolerance for +difference of implementation and a high penalty for specification ambiguity. An +improperly implemented part of a new spec could cause the ethereum mainnet to +split, possibly costing millions to billions of value lost to node operators as +well as community members using the services offered by the Ethereum protocols. +A poorly specified solidity interface, however, can be adapted and implemented +in multiple compatible ways across any smart choosing to implement it. A missing +RPC API (such as a configuration option specifying the number of decimals in the +chains native currency) can have limited to zero impact on the rest of the +community not choosing to use that wallet. + +Timeframe for delivery of a feature is also similarly differentiated. A Core +protocol EIP adjusting the gas cost for transaction data needs to be rolled out +at a specific time uniformly across the network. Whereas a new RPC to support +new semantics to gas estimation would not need uniform rollout across the +Ethereum clients, and in fact would also need to be rolled out by service +provides that provide RPC services for Ethereum networks. Wallets can use early +support as a differentiating factor in their appeal to community members. + +To address this divergence the AllCoreDevs call has adopted a lifecycle for EIPs +different from the Draft -> Review -> Last Call -> Final lifecycle of the EIP +repository. It would best be described as Draft -> Eligible for Inclusion -> +Considered for Inclusion -> Testnet -> Mainnet. The EIPs also get slotted for a +fork in the third step, a consideration that simply does not apply to a smart +contract or wallet standard. + +Several alternatives have been proposed, but the actual implementation only +further underscores the specialization that each side of the split encounters. + +### Alternative: Working Groups + +One repeated concern of editors is that they often lack the technical experience +to adequately judge if an EIP is complete and sound. Considering that EIPs +covers wide variety of topics such as elliptic curve cryptography, VM +performance, DeFi market dynamics, compression protocols, NFT Royalties, and +consensus protocols it is impossible for a single editor to provide sensible +feedback on every one of those topics. + +When examining how the core protocol and ERC communities would approach the +working group process, however, it underscores how different they would handle +it. For core protocol change the working group would be one of the two +AllCoreDevs meetings, either AllCoreDevs-Execution or AllCoreDevs-Consensus. And +sometimes both. There is no EIP that would be shipped in mainnet that would not +first be extensively considered by one of these two groups. + +ERC proposals have no such standing groups. Wallet impacting changes may go +through the AllWalletDevs group, but it is entirely possible for a wallet or +group of wallets to collaborate on a protocol outside AllWalletDevs. Smart +contract APIs have no such standing meeting. + +The Working Group model, however, would be a critical social signal for the ERC +community. It would signal a critical mass for a particular proposal issue if +enough experts could get together to agree to review a set of changes. + +While working groups are excellent for the ERC community, it is overhead for the +core protocol community that would only add friction to an already established +process with know governance checkpoints. + +### Alternative: Specialized Editors + +This alternative has already been implemented with the introduction of the +`eip-editors.yml` file. This allows for different groups of editors to review +different types of EIPs. + +There has been no measurable impact on the divergence of the community. Most +categories have a significant overlap with other categories. + +This alternative does not address the governance and workflow issues that the +Core Protocol Developers would want to implement. All subgroups would still be +subject to the same workflow as other groups. + +### Alternative: Pain unrelated to process divergences + +This is a catch-all for a number of proposals, from allowing discord links in +discussion-to to allowing more freedom in external links. + +While the theory that this may reduce the total amount of pain felt by users and +editors, bringing the pain level down to a more acceptable level, this does not +address the core divergence issue. Many of these pain relief proposals should +probably be done anyway, weather or not the EIP repository splits. + +### Alternative: Replace EIP Editors with AI Chatbots + +Nobody wins in this proposal. We would instead end up debating training sets, +competing implementations, and whether to use commercial providers. And +that's if things go well. + +AI chatbots, however, would not be able to compartmentalize the divergent needs +of the multiple groups if all adjudication were to be handled with one model or +one chat session. Higher quality output would be received if separate training +repositories were used for each major functional area. + +### Alternatives are not Mutually Exclusive + +It is critical to note that most of the discussed alternatives all have merits +and address important pain points. The adoption of a split should not be viewed +as a rejection of those alternatives. To quote a famous internet meme "Why Not +Both?" + +### Objection: This splits the ethereum community + +One objection is that splitting the repository would result in the community no +longer being able to say "we are all of us Ethereum Magicians." + +First it is important to note that such splits are already occurring. The +AllCoreDevs call has split into a Consensus and Execution layer call. ACD calls +no longer discuss client issues like wallet apis, the AllWalletDevs call has +adopted those issues and has grown into user experience issues. Cross chain +issues have been adopted by the Chain Agnostic Improvement Process (CAIP) group. + +Rather than splitting this should be viewed as "sharding", where a sub-community +of interest rallies around a shared sub issue, and by gathering are able to +increase the total scope of the community. CAIP is a perfect example where +operating separate from EIPs have allowed them to strengthen the ethereum +community. + +Is a single cell organism weakened when it grows large and then splits into two? +Is an animal weakened when cells split and specialize into different tasks? It +is this very act of division and specialization that allows it to accomplish the +things that would be impossible as a single uniform cell. + +### Objection: This should be an [EIP-1](./eip-1.md) proposal + +Since this is directly impacting the ERC process it should be documented +in [EIP-1](./eip-1.md) first. + +As the old programming adage goes: "Refactor first before adding any new +features." Adding new processes specific to the post-split governing docs would +only confuse the existing process, adding special cases for one class of EIPs +that don't apply to another. It is precisely this kind of problem the proposed +split is aiming to change. + +This is also valid grounds for a Meta category EIP, as how many and which +repository to put a proposal in is core to the "procedures, guidelines, \[and\] +changes to the decision-making process". + +Some process changes that can be expected in a Core Protocol EIP may include: + +* Changing the work flow to add the Eligible for Inclusion/Considered for + Inclusion stages to a pre-last-call EIP. +* Adding test net and mainnet steps to the lifecycle +* Adding a "fork" header to the RFCs section, for EIPs that are (or will be) + implemented in a specific fork +* Changing the testing section to a header link to reference tests + +Some process change ERC may want to adopt: + +* A strong working group model and adding an optional "forming working group" + step editors may require. +* Add an "outdated" or "replaced" lifecycle step for EIPs that are abrogated by + future specs. +* Deputize single-eip reviewers for specific EIPs + +### Objection: Structural changes to a repository and process changes do not need to be bundled. + +It is possible to split the structure of the repositories separately from any +EIP process changes related to this. Bundling the changes is unnecessary and +such structure and process changes should be handled independently. + +To accommodate this objection this EIP has been revised to only address +structural changes in the repository and can be adapted to any other, +independent, process changes and mapped onto those outcomes. + +## Backwards Compatibility + +### Old Links + +Old ERC links pointing to the old url `https://eips.ethereum.org/` will continue +to work. Redirect instructions will be put into place to redirect to the new ERC +repos for their corresponding location. + +### Stray Proposals + +ERC community members may continue to post new ERCs in the EIP proposal. Editors +will be able to redirect them to the new repository. ERCs that do not respond to +editor requests would not be merged anyway. + +## Security Considerations + +This proposal only addresses the EIP and ERC proposal process and is not +expected to expose any new attack surfaces by virtue of its adoption. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7377.md b/EIPS/eip-7377.md new file mode 100644 index 00000000000000..1b0b5c07fdde28 --- /dev/null +++ b/EIPS/eip-7377.md @@ -0,0 +1,132 @@ +--- +eip: 7377 +title: Migration Transaction +description: Allow EOAs to send a one-time transaction which deploys code at their account. +author: lightclient (@lightclient), Sam Wilson (@samwilsn), Ansgar Dietrichs (@adietrichs) +discussions-to: https://ethereum-magicians.org/t/eip-xxxx-migration-transaction/15144 +status: Draft +type: Standards Track +category: Core +created: 2023-07-21 +requires: 170, 1559, 2200, 2718 +--- + +## Abstract + +Introduce a new [EIP-2718](./eip-2718.md) transaction type with the format `0x04 || rlp([chainId, nonce, maxFeePerGas, maxPriorityFeePerGas, gasLimit, codeAddr, storage, data, value, accessList, yParity, r, s])` which sets the sending account's `code` field in the state trie to the `code` value at `codeAddr` and applies the storage tuples to the sender's storage trie. + +## Motivation + +Smart contract wallets have long been touted as the solution to Ethereum's user experience woes. As early as 2015, there were proposals for allowing smart contracts to originate transactions in hopes that new users would flock to smart contract wallets to store their assets. So far, only a fraction of users have elected to do so. + +Today, account abstraction is still an important goal in Ethereum and there are many efforts attempting to realize it. We're getting closer to succeeding at this, but unfortunately the years of failure have caused many users to simply rely on EOA. + +After a user has accumulated enough assets in an EOA, it is not tenable to migrate each individual asset to a new address. This is due both to the cost and to needing to manually sign and verify potentially hundreds of transactions. + +This is an overlooked piece of the problem. Converting *existing* users to smart contract wallets efficiently will expedite adoption and push forward better support and integrations for smart contract wallets. They will no longer be dismissed as a niche use case. + +Therefore, we must provide a mechanism, embedded in the protocol, to migrate EOAs to smart contracts. This EIP proposes such mechanism. + +## Specification + +At the fork block `X`, introduce the migration transaction type. + +### Migration Transaction + +#### Definition + +| field | type | +|------------------------|-----------| +| `chainId` | `uint256` | +| `nonce` | `uint64` | +| `maxFeePerGas` | `uint256` | +| `maxPriorityFeePerGas` | `uint256` | +| `gasLimit` | `uint64` | +| `codeAddr` | `address` | +| `storage` | `List[Tuple[uint256, uint256]]` | +| `data` | `bytes` | +| `value` | `uint256` | +| `accessList` | `List[Tuple[address, List[uint256]]]` | +| `yParity` | `uint8` | +| `r` | `uint256` | +| `s` | `uint256` | + +The EIP-2718 `TransactionType` is `0x04` and the `TransactionPayload` is `rlp([chainId, nonce, maxFeePerGas, maxPriorityFeePerGas, gasLimit, codeAddr, storage, data, value, accessList, yParity, r, s])`. + +The transaction's signature hash is `keccak256(0x04 || rlp([chainId, nonce, maxFeePerGas, maxPriorityFeePerGas, gasLimit, codeAddr, storage, data, value, accessList])` + +#### Validation + +A migration transaction is considered valid if the follow properties hold: + +* all [EIP-1559](./eip-1559.md) properties, unless specified otherwise +* the code at `codeAddr` is less than the [EIP-170](./eip-170.md) limit of `24576` +* the code at `codeAddr` must not have size `0` + +The intrinsic gas calculation modified from [EIP-1559](./eip-1559.md) to be `21000 + 16 * non-zero calldata bytes + 4 * zero calldata bytes + 1900 * access list storage key count + 2400 * access list address count + 20000 * length of storage`. + +#### Processing + +Executing a migration transaction has two parts. + +##### Contract Deployment + +Unlike standard contract deployment, a migration transaction directly specifies what `code` value the sender's account should be set to. + +As the first step of processing the transaction, set the sender's `code` to `state[tx.codeAddr].code`. Next, for each tuple in `tx.storage` and the sender's storage trie, set `storage[t.first] = t.second`. + +##### Transaction Execution + +Now instantiate an EVM call into the sender's account using the same rules as [EIP-1559](./eip-1559.md) and set the transaction's origin to be `keccak256(sender)[0..20]`. + +## Rationale + +### No `to` address field + +This transaction is only good for one-time use to migrate an EOA to a smart contract. It is designed to immediately call the deployed contract, which is at the sender's address, after deployment to allow the sender to do any kind of further processing. + +### Code pointer for deployment + +Naively, one could design the migration transaction to have a field `code` of type `bytes`. However, there would be substantial duplication of code calldata, since many users will want to deploy the exact same thing (often a wallet). Using a pointer instead acknowledges this overwhelming use case for the transaction type, and exploits it as an optimization. + +### Cheaper storage + +Since the storage is guaranteed to be empty, there is no need to read before write. This means only 20,000 gas is needed to pay for the [EIP-2200](./eip-2200.md) `SSTORE_SET_GAS` value. This is a small discount to the normal cost of `22,100`, which is `SSTORE_SET_GAS` plus the [EIP-2929](./eip-2929.md) `COLD_SLOAD_COST` of `2100`, because no load occurs. + +### Intrinsic does not account for contract deployment + +This takes advantage of the fact that clients tend to store a single, unique copy of code; no matter the number of deployments. Therefore, the only operation here is changing a pointer in the state trie to the desired code. + +Additionally, the EOA already exists because it has enough balance for the migration transaction to be considered valid. Therefore, we don't need to pay a premium for adding a new account into the state trie. + +### Manipulating transaction origin + +Many applications have a security check `caller == origin` to verify the caller is an EOA. This is done to "protect" assets. While it is usually more of a bandage than an actual fix, we attempt to placate these projects by modifying the origin of the transaction so the check will continue performing its duty. + +### One-time migration + +There is no technical reason we couldn't allow EOAs to change their code at any time with this transaction type. The only inhibitor at the moment is [EIP-3607](./eip-3607.md) which will cause migration transactions to be considered invalid if they come from an account with code already deployed. A functional reason for retaining this behavior though is that it makes it simpler to reason about contracts and their upgradability. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +### Blind Signing + +As with all sufficiently sophisticated account designs, if a user can be convinced to sign an arbitrary message, that message could be a migration transaction which is owned by a malicious actor instead of the user. This can generally be avoided if wallets treat these transactions with *extreme* care and create as much friction and verification as possible before completing the signature. + +### On `ecrecover` + +Applications standards such as [ERC-2612: Permit Extension](./eip-2612.md) have exploited the cryptographic relationship between EOA addresses and their private keys. Many tokens today support this extension, allowing EOAs to approve the transfer of fund from their account using only a signature. Although collisions between EOAs and contract accounts are considered unlikely and [maybe impossible](./eip-3607.md) given today's computing power, this EIP would make it common place for private keys to exist for contract accounts. There are some considerations here regarding security: + +* The obvious attack is a defi protocol deploys some their contract using this EIP and later sign an [ERC-2612](./eip-2612.md) message to steal the funds accrued in the contract. This can be avoided by wallets simply not allowing users to interact with protocols deployed in this manner. +* It's also worth mentioning that there are concerns around how this EIP will affect the cross chain experience. Ultimately a users private key may still have some control over the account's assets, depending on the exact protocols used on Ethereum and on other chains. It isn't really possible perfectly migrate the EOA at the same time, on all chains. The best thing that can be done is to educate the user that just because their account has been migrated doesn't mean that they are safe to now publicly reveal their private key. This seems like a reasonable request, especially since they'll want to retain the private key in case they want to use the address on any other EVM-like chain. + +Something that may alleviate these issues to some degree would be to add an `EXTCODEHASH` check in `ecrecover`. If the recovered account has code, the precompile will revert. This would disallow migrated EOAs from using standards like [ERC-2612](./eip-2612.md). + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-7378.md b/EIPS/eip-7378.md new file mode 100644 index 00000000000000..3a9726446ea99a --- /dev/null +++ b/EIPS/eip-7378.md @@ -0,0 +1,85 @@ +--- +eip: 7378 +title: Add time-weighted averaging to the base fee +description: Using geometric weights to average past block sizes into consideration +author: Guy Goren (@guy-goren) +discussions-to: https://ethereum-magicians.org/t/add-time-weighted-averaging-to-the-base-fee-mechanism/15142 +status: Stagnant +type: Standards Track +category: Core +created: 2023-07-22 +--- + +## Abstract + +This EIP proposes a new formula to update the base fee, derived from [EIP-1559](./eip-1559.md). The existing base fee update formula, + +$$b[i+1]\triangleq b[i] \cdot \left( 1+\frac{1}{8} \cdot \frac{s[i]-s^* }{s^* }\right)$$ + +only considers the last block size $s[i]$. This mechanism incentivizes proposers to collude with users to manipulate the base fee. + +We propose that even previous block sizes be considered by replacing the last block size with an exponential moving average. In particular, we suggest the following base fee update formula: + +$$b[i+1]\triangleq b[i] \cdot \left( 1+\frac{1}{8} \cdot \frac{s_{\textit{avg}}[i]-s^* }{s^* }\right)$$ + +where $s_{\textit{avg}}[i]$ is defined by: + +$$s_{\textit{avg}}[i] \triangleq \alpha\sum_{k=1}^{\infty} (1-\alpha)^k\cdot s[i-k+1]$$ + +and $\alpha\in(0,1)$ is a smoothing factor. + +## Motivation + +To reduce bribe motivation when the demand for blockspace is high (see Incentive Considerations section) and to reduce oscillations, thus, having a more stable fee setting mechanism. + +Proposers use a mechanism described in EIP-1559 to determine which messages to include in a block. This mechanism includes a "base fee": a portion of the transaction fee that is burned. The base fee varies according to the fill rate of blocks. A target block size is defined. If a block exceeds the target size, the base fee increases, and if it is smaller, the base fee lowers. + +Research on the subject have revealed issues with this transaction fee mechanism. It has been shown to be [unstable in cases](../assets/eip-7378/LMRSP.pdf). Moreover, it has been shown that the dynamic nature of the base fee, which is influenced by the fill rate of blocks, opens the door for [manipulation by miners (proposers) and users](../assets/eip-7378/AGHH.pdf). The desired behavior of the system under a stable high demand, is for it to reach an equilibrium where the base fee -- $b$ -- is the significant part of the gas fee, and the tip is relatively small -- denoted $\varepsilon$ (for reference, Ethereum's base fee often has $\frac{b}{\varepsilon}\approx 20$). According to [Roughgarden](../assets/eip-7378/TR1559.pdf) this is a rational equilibrium under the assumption that proposers do not think ahead. However, we expect a proposer to optimize its behavior by also considering its future payoffs. In essence, since neither the proposer nor the user are getting the burnt fee, by colluding they can both tap into the burnt fee for a win-win situation for them both. + +A [theoretical work](../assets/eip-7378/AGHH.pdf) describes how both proposers and users can initiate such an attack. For example, we can imagine that users who wish to pay lower costs will coordinate the attack. Roughly, a user (or group of users) that has transactions with a total $g$ amount of gas bribes the proposer of the current block (no matter the proposer's power) to propose an empty block instead. The cost of such a bribe is only $\varepsilon \times {s^* }$ -- the tip times the target block size. Consequently, the base fee reduces in the next block. If we accept that EIP-1559 reaches its goals, e.g., users would typically use a simple and honest bidding strategy of reporting their maximal willingness to pay plus adding a small tip ($\varepsilon$), then in the honest users' steady state, gas proposals leave the proposers with an $\varepsilon$ tip. Given that other users are naive (or slow to react), our bribing user will include its transactions with any tip larger than $\varepsilon$ -- making the attack profitable whenever $g \frac{b^* }{8} >s^* \varepsilon$. + + +## Specification + +$s[i]$ is replaced by $s_{\textit{avg}}[i]$, where: + +$$s_{\textit{avg}}[i] \triangleq \alpha\sum_{k=1}^{\infty} (1-\alpha)^k\cdot s[i-k+1]$$ + +which simplifies to the recursive form + +$$s_{\textit{avg}}[i] = \alpha\cdot s[i] + (1-\alpha)\cdot s_{\textit{avg}}[i-1]$$ + +where $\alpha\in(0, 1)$ is the smoothing factor. A higher smoothing factor means that the average responds more quickly to changes in block size (e.g., if $\alpha = 1$ the proposed formula degenerates to the existing rule). + +## Rationale + +An intuitive option for the Transaction Fee Mechanism (TFM) that adjusts supply and demand economically is *First price auction*, which is well known and studied. Nevertheless, the Ethereum network choice was to use EIP-1559 for the TFM (one stated reason was to try and simplify the fee estimation for users, and reduce the advantage of sophisticated users). In this proposal, our design goal is to improve the TFM (of EIP-1559) by mitigating known problems that it raises. It is important to note that these problems severity are in direct relation to the demand for block space, and currently only mildly impact the Ethereum network. If demand to use Ethereum increases, however, these problems are expected to exacerbate. We may want to prepare for this beforehand. + +The change is based on [this work](../assets/eip-7378/AGHH.pdf) that described a rational strategy in which bribes are profitable. Choosing to average based on a geometric series weights results in two desired properties: (i) the computation and space complexity are both in O(1), and (ii) the average gradually phases out the impact of a single outlier block without causing significant future fluctuations in the base fee. +Moreover, the theoretical analysis does not consider the income from classic MEV strategies. (Actually, the described strategy may be seen as another form of MEV.) The fact that classic MEV (sandwich, front running, etc.) are not included in the analysis, means that the proposed solutions to classic MEV (obscuring transactions etc.) will also not help against the described strategy. The problem that we tackle in this EIP is at the core of the base fee mechanism, with no further assumptions (such as MEV or predictability of randomness). + +Remark: An additional alternative strategy that is not fully discussed [here](../assets/eip-7378/AGHH.pdf) but one may consider is to reduce the 'max change denominator' (the learning rate) from 1/8 to something smaller. However, this is problematic since it significantly affects the responsiveness of the base fee, making it slow to respond to actual persistent changes. The reason for using geometric series weights is precisely to achieve the favorable tradeoff of still responding quickly while mitigating incentive misalignments. + +### Incentive Considerations + +The proposal is designed to improve the incentive compatibility of the TFM. A [game theoretic analysis](../assets/eip-7378/AGHH.pdf) shows that the current TFM, which is based on EIP-1559, encourages bribes. + +One of the main goals of EIP-1559 was to simplify the bidding for users. It was articulated [theoretically by Roughgarden](../assets/eip-7378/TR1559.pdf) as users bidding their honest valuations being an optimal strategy. In contrast, when using first price auctions for the TFM (as done by Bitcoin and previously in Ethereum), it is typically sub-optimal for a user to bid its honest valuation. In other words, a TFM that encourages users to not fully reveal their preferences is considered less good. However, one may argue that a TFM that encourages bribes is worse than a TFM that encourages not revealing one's full preferences. + +Although a first price auction is a safe bet regarding TFMs, the Ethereum network chose to use EIP-1559 and burn transaction fees (perhaps for reasons other than game-theoretic ones). We therefore suggest to mitigate the current incentives for bribes using the above proposal. + +## Backwards Compatibility + +This change requires a hard fork since the base fee is enforced (for blocks to be considered valid). + +## Test Cases + +TBD + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7401.md b/EIPS/eip-7401.md new file mode 100644 index 00000000000000..c085f02443494c --- /dev/null +++ b/EIPS/eip-7401.md @@ -0,0 +1,7 @@ +--- +eip: 7401 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7401.md diff --git a/EIPS/eip-7405.md b/EIPS/eip-7405.md new file mode 100644 index 00000000000000..a7e2b7f64ed7d1 --- /dev/null +++ b/EIPS/eip-7405.md @@ -0,0 +1,7 @@ +--- +eip: 7405 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7405.md diff --git a/EIPS/eip-7406.md b/EIPS/eip-7406.md new file mode 100644 index 00000000000000..dccef232e2259c --- /dev/null +++ b/EIPS/eip-7406.md @@ -0,0 +1,7 @@ +--- +eip: 7406 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7406.md diff --git a/EIPS/eip-7409.md b/EIPS/eip-7409.md new file mode 100644 index 00000000000000..e3f405fc6c30c6 --- /dev/null +++ b/EIPS/eip-7409.md @@ -0,0 +1,7 @@ +--- +eip: 7409 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7409.md diff --git a/EIPS/eip-7412.md b/EIPS/eip-7412.md new file mode 100644 index 00000000000000..ecaa9f75aaf1c0 --- /dev/null +++ b/EIPS/eip-7412.md @@ -0,0 +1,7 @@ +--- +eip: 7412 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7412.md diff --git a/EIPS/eip-7417.md b/EIPS/eip-7417.md new file mode 100644 index 00000000000000..6b10d08ff092fd --- /dev/null +++ b/EIPS/eip-7417.md @@ -0,0 +1,7 @@ +--- +eip: 7417 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7417.md diff --git a/EIPS/eip-7425.md b/EIPS/eip-7425.md new file mode 100644 index 00000000000000..47b138dda7a718 --- /dev/null +++ b/EIPS/eip-7425.md @@ -0,0 +1,7 @@ +--- +eip: 7425 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7425.md diff --git a/EIPS/eip-7432.md b/EIPS/eip-7432.md new file mode 100644 index 00000000000000..a826f35c373624 --- /dev/null +++ b/EIPS/eip-7432.md @@ -0,0 +1,7 @@ +--- +eip: 7432 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7432.md diff --git a/EIPS/eip-7441.md b/EIPS/eip-7441.md new file mode 100644 index 00000000000000..56f80238d32f84 --- /dev/null +++ b/EIPS/eip-7441.md @@ -0,0 +1,101 @@ +--- +eip: 7441 +title: Upgrade block proposer election to Whisk +description: Allow elected block proposers to remain private until block publishing, to prevent DoS attacks +author: George Kadianakis (@asn-d6), Justin Drake (@JustinDrake), dapplion (@dapplion) +discussions-to: https://ethereum-magicians.org/t/eip-7441-upgrade-block-proposer-election-to-whisk-ssle/15316 +status: Stagnant +type: Standards Track +category: Core +created: 2023-09-01 +--- + +## Abstract + +Upgrades the block proposer election mechanism to Whisk, a single secret leader election (SSLE) protocol. Currently, block proposers are publicly known in advance, sufficiently to allow sequential DoS attacks that could disable Ethereum. This upgrade allows the next block proposer to remain secret until its block is published. + +## Motivation + +The beacon chain currently elects the next 32 block proposers at the beginning of each epoch. The results of this election are public and everyone gets to learn the identity of those future block proposers. + +This information leak enables attackers to launch DoS attacks against each proposer sequentially in an attempt to disable Ethereum. + +## Specification + +### Execution layer + +This requires no changes to the Execution Layer. + +### Consensus layer + +The protocol can be summarized in the following concurrent steps: + +- Validators register a tracker and unique commitment on their first proposal after the fork +- At the start of a shuffling phase a list of candidate trackers is selected using public randomness from RANDAO +- During each shuffling phase each proposer shuffles a subset of the candidate trackers using private randomness +- After each shuffling phase an ordered list of proposer trackers is selected from the candidate set using RANDAO + +The full specification of the proposed change can be found in [`/_features/whisk/beacon-chain.md`](https://github.com/ethereum/consensus-specs/blob/a39abe388bc2d1abd5b4fd62fd18aed497956b30/specs/_features/whisk/beacon-chain.md). In summary: + +- Update `BeaconState` with fields needed to track validator trackers, commitments, and the two rounds of candidate election. +- Add `select_whisk_candidate_trackers` to compute the next vector of candidates from the validator set. +- Add `select_whisk_proposer_trackers` to compute the next vector of proposers from current candidates. +- Add `process_whisk_updates` to epoch processing logic. +- Add `process_whisk_opening_proof` to validate block proposer has knowledge of this slot's elected tracker. +- Modify `process_block_header` to not assert proposer election with `get_beacon_proposer_index`, instead assert valid opening proof. +- Update `BeaconBlockBody` with fields to submit opening proof, shuffled trackers with proof, and tracker registration with proof. +- Add `get_shuffle_indices` to compute pre-shuffle candidate selection +- Add `process_shuffled_trackers` to submit shuffled candidate trackers. +- Add `process_whisk` to block processing logic. +- Modify `apply_deposit` to register an initial unique tracker and commitment without entropy. + +## Rationale + +### Fields per validator + +Whisk requires having one tracker `(rG,krG)` and one unique commitment `kG` per validator. Both are updated only once on a validator's first proposal after the fork. + +Trackers are registered with a randomized base `(rG,krG)` to make it harder for adversaries to track them through shuffling gates. It can become an issue if the set of honest shufflers is small. + +### Identity binding + +Each tracker must be bound to a validator's identity to prevent multiple parties to claim the same proposer slot. Otherwise, it would allow proposers to sell their proposer slot, and cause fork-choice issues if two competing blocks appear. + +Whisk does identity binding by storing a commitment to the tracker's secret `kG` in the validator record. Storing the commitment also ensures the uniqueness of `k`. + +Alternatively, identity binding can be achieved by forcing the hash prefix of `hash(kG)` to match its validator index. However, validators would have to brute force `k` making bootstrap of the system harder for participants with fewer computational resources. + +Identity binding can also be achieved by setting `k = hash(nonce + pubkey)`. However, proposers will need to reveal `k` and be de-anonymized for repeated proposals on adjacent shuffling phases. + +### Alternative: non-single secret election + +Secret non-single leader election could be based on protocol engineering rather than cryptography, thus much simpler and cheaper than Whisk. However, it complicates the fork-choice and opens it up to potential MEV time-buying attacks, making it an unsuitable option at the time of writing. + +### Alternative: network anonymity + +Privacy-preserving networking protocols like Dandelion or Dandelion++ increase the privacy of network participants but not sufficiently for Ethereum's use case. + +SASSAFRAS is a simpler alternative SSLE protocol consensus-wise, but it relies on a network anonymity layer. Its specific trade-offs do not fit Ethereum's overall threat model better than Whisk. + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. + +PBS participants (e.g. builders) will not know the next proposer validator index to use a specific pre-registered fee recipient; unless the proposer chooses to reveal itself ahead of time. Block explorers and tooling will not be able to attribute missing slots to a specific validator index. + +## Security Considerations + +The shuffling strategy is analyzed in a companion paper and considered sufficiently safe for Whisk's use case. The data and computational complexity of this EIP are significant but constant, thus does not open new DoS vectors. + +### Anonymity set + +The anonymity set in Whisk is the set of 8,192 candidates that did not get selected as proposers. That count of validators corresponds to a smaller number of p2p nodes. Assuming a Pareto principle where "20% of the nodes run 80% of the validators" the anonymity corresponds to 2,108 nodes on average. A bigger candidate pool could make the shuffling strategy unsafe while shuffling more trackers per round would increase the cost of the ZK proofs. + +### RANDAO biasing + +Whisk uses RANDAO in the candidate selection and proposer selection events, and is susceptible to potential RANDAO biasing attacks by malicious proposers. Whisk security could be made identical to the status quo by spreading the selection events over an entire shuffling period. However, status quo security is not ideal either and it would complicate the protocol further. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-7444.md b/EIPS/eip-7444.md new file mode 100644 index 00000000000000..b0127aa3b5743e --- /dev/null +++ b/EIPS/eip-7444.md @@ -0,0 +1,7 @@ +--- +eip: 7444 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7444.md diff --git a/EIPS/eip-747.md b/EIPS/eip-747.md index 2a1aa65e93bd0f..e60995651dfcda 100644 --- a/EIPS/eip-747.md +++ b/EIPS/eip-747.md @@ -2,13 +2,13 @@ eip: 747 title: wallet_watchAsset RPC Method description: Adds a new RPC method that allows websites to prompt users to watch an asset -author: Dan Finlay (@danfinlay), Esteban Mino (@estebanmino), Pandapip1 (@Pandapip1) +author: Dan Finlay (@danfinlay), Esteban Mino (@estebanmino), Gavin John (@Pandapip1) discussions-to: https://ethereum-magicians.org/t/eip-747-eth-watchtoken/1048 -status: Review +status: Final type: Standards Track category: Interface created: 2018-08-13 -requires: 1193 +requires: 20, 1046, 1193 --- ## Abstract @@ -24,96 +24,104 @@ In the second case, the user experience is terrible. ## Specification -A new RPC method, `wallet_watchAsset` is added. `wallet_watchAsset` requests that a specified asset be added to the user's wallet. It returns `true` if the asset was successfully added, or errors if it was not. The meaning of "added to the user's wallet" is dependent on the wallet implementation. A successful call to `wallet_watchAsset` should indicate that the specified asset is listed in the user's wallet (regardless of whether it already was listed). +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +A new RPC method, `wallet_watchAsset` is added. `wallet_watchAsset` requests that a specified asset be listed to the user's wallet. It MUST immediately (i.e. before prompting the user) return `true` if the request was valid, or error if it was not. The meaning of "listed to the user's wallet" is dependent on the wallet implementation. A successful call to `wallet_watchAsset` MUST indicate that the wallet recognized the request and that it contained no issues, but doesn't indicate whether the user was prompted or whether the asset was actually added to the wallet. ### `wallet_watchAsset` Parameters The `wallet_watchAsset` method takes a single parameter, a `WatchAssetParameters` object, which is defined as follows: - + ```typescript interface WatchAssetParameters { - type: string; // The asset's interface, e.g. 'ERC20' - options: { - address: string; // The hexadecimal Ethereum address of the token contract - symbol?: string; // A ticker symbol or shorthand, up to 5 alphanumerical characters - decimals?: number; // The number of asset decimals - image?: string; // A string url of the token logo - }; + type: string; // The asset's interface, e.g. 'ERC1046' + options: any; } ``` -The `type` string should be the commonly accepted name of the interface implemented by the asset's contract, e.g. `ERC20`. Defining the global identifiers for different asset types is beyond the scope of this EIP. The `options` object should contain the following fields: `address`, `symbol`, `decimals`, and `image`. `address` is required, and the other fields are optional. `address` should be the hexadecimal Ethereum address of the token contract. `symbol` is a ticker symbol or shorthand, up to 5 alphanumerical characters. `decimals` is the number of asset decimals. `image` is a string url of the token logo. The following image formats must be supported: - -- GIF -- PNG -- JPG/JPEG -- SVG +The `type` string SHOULD be the commonly accepted name of the interface implemented by the asset's contract, e.g. `ERC1046`. Defining the global identifiers for different asset types is beyond the scope of this EIP. -If the resolved image is a bitmap, its dimensions should not exceed 512x512 pixels. Neither the URI nor the image it resolves to should have a size larger than 256kb. - -This interface should be extended or modified depending on the asset `type`. These changes must be specified in a separate EIP. +This interface SHOULD be extended or modified depending on the asset `type`. These changes MUST be specified in separate EIPs. ### `wallet_watchAsset` Returns -`wallet_watchAsset` returns the boolean value `true` if the the asset was added successfully, and an error otherwise. An error might occur in the following cases (but is not limited to these cases): +`wallet_watchAsset` immediately (i.e. without waiting for user interaction) returns the boolean value `true` to indicate that the request was recognized (regardless of whether the user was prompted), or errors if the request is invalid. An error might occur in the following circumstances (not comprehensive): -- The user declines the request - The asset type is unrecognized/unsupported +- The asset was blocked due to an allowlist or denylist (this makes the request 'invalid' since the root cause requires developer action) - Downloading the image failed to load + - The wallet didn't load some of the metadata required to display the asset, in order to protect against a potential SSRF attack -## Rationale +### `ERC1046` type -Displaying a user's assets is a basic feature that every modern dapp user expects. However, keeping this list, and polling for it from the network can be costly, especially on bandwidth constrained devices. +The format of the options field is: -Most wallets today either manage their own assets list, which they store client side, or they query a centralized API for balances, which reduces decentralization, letting that API's owner easily correlate account holders with their IP addresses. +```typescript +interface ERC1046WatchAssetOptions { +{ + address: string; // The hexadecimal address of the token contract + chainId?: number; // The chain ID of the asset. If empty, defaults to the current chain ID. + }; +} +``` -Maintaining one of these assets lists becomes a political act, and maintainers can be subject to regular harassment and pressure to list otherwise unknown assets. +`address` is required, and the other fields are optional. `address` MUST be the `0x`-prefixed checksummed hexadecimal address of the token contract. `chainId` MUST be the chain ID to which the asset belongs. -Furthermore, automatically listing assets makes assets into a sort of spam mail: Users suddenly seeing new assets that they don't care about in their wallet can be used to bombard them with information that they didn't opt into. +If the checksum fails, the request MUST be considered invalid. -This phenomenon is exacerbated by the trend towards airdropped tokens, which has been a cause of network congestion, because spamming people with new tokens has so far been rewarded with user attention. +If the wallet does not recognize the `chainId`, or the `chainId` is blank and the wallet does not have a concept of "active" chain, the call MUST fail. -While some people might suggest we begin a TCR of trusted tokens to watch, this would not solve the client-side bandwidth issues, nor the airdropped token spam issues. What we really want is a small list of tokens the user cares about. +`wallet_watchAsset` MUST fetch the [ERC-1046](./eip-1046.md) `tokenURI` and check the `interop` field to determine the type of the token. If the parsing fails, or the type is unknown, the RPC call MUST error. -Most of the time a user is adding a asset, they learned about it on a website. At that moment, there is a natural alignment of interests, where the website wants the user to track their asset, and the user wants to track it. This is a natural point to introduce an API to easily allow these parties to collaborate, without involving the politics of the wallet's developers. +`wallet_watchAsset` SHOULD check the `name` and `symbol` fields, and the contract `address` and `chainId` against a list of well-known tokens. If the name and/or symbol are similar to ones on the list but the `chainId`/`address` don't match, a warning SHOULD be presented to the user. -## Test Cases +The wallet SHOULD whitelist and/or blacklist specific ports and schemes to avoid SSRF attacks. -In the case of assets of type `ERC20`, this method works as follows. +### Legacy `ERC20` type -```javascript -ethereum.request({ - method: 'wallet_watchAsset', - params: { - type: 'ERC20', - options: { - address: '0xb60e8dd61c5d32be8058bb8eb970870f07233155', - symbol: 'FOO', - decimals: 18, - image: 'https://foo.io/token-image.svg', - }, - }, -}); - .then((success) => { - if (success) { - console.log('FOO successfully added to wallet!') - } else { - throw new Error('Something went wrong.') - } - }) - .catch(console.error) +The format of the options field is: + +```typescript +interface ERC20WatchAssetOptions { +{ + address: string; // The hexadecimal address of the token contract + chainId?: number; // The chain ID of the asset. If empty, defaults to the current chain ID. + }; +} ``` -Upon calling this request, the user must be prompted with the opportunity to add this token to their wallet: +`address` is required, and the other fields are optional. `address` MUST be the `0x`-prefixed checksummed hexadecimal address of the token contract. `chainId` MUST be the chain ID to which the asset belongs. + +If the checksum fails, the request MUST be considered invalid. + +If the wallet does not recognize the `chainId`, or the `chainId` is blank and the wallet does not have a concept of "active" chain, the call MUST fail. + +`wallet_watchAsset` SHOULD check the `name` and `symbol` fields, and the contract `address` and `chainId` against a list of well-known tokens. If the name and/or symbol are similar to ones on the list but the `chainId`/`address` don't match, a warning SHOULD be presented to the user. + +If possible, it is RECOMMENDED to instead use the `ERC1046` type, which supports images and custom metadata. + +## Rationale -![add-token-prompt 1](../assets/eip-747/add-token-prompt.gif) +Displaying a user's assets is a basic feature that every modern DApp user expects. Most wallets currently either manage their own asset lists, which they store client-side, or they query a centralized API for balances, which reduces decentralization and allows correlating account holders with IP addresses. Additionally, refreshing/polling an asset list from the network can be costly, especially on bandwidth-constrained devices. Also, maintaining an asset list becomes a political act, provoking harassment and inducing pressure to list obscure assets. + +Automatically listing assets makes assets into a sort of spam mail: Users suddenly see new assets that they don't care about in their wallet. This can be used to send unsolicited information, or even to conduct phishing scams. This phenomenon is already common with airdropped tokens, a major cause of network congestion, because spamming people with new tokens has, so far, been rewarded with increased user attention. + +When a user is manually adding a asset, they had likely previously learned about it from a website. At that moment, there was a natural alignment of interests, where both parties wanted the user to track the token. This is a natural point to introduce an API to easily allow these parties to collaborate. ## Security Considerations -### SSRF +### Server-Side Request Forgery Wallets should be careful about making arbitrary requests to URLs. As such, it is recommended for wallets to sanitize the URI by whitelisting specific schemes and ports. A vulnerable wallet could be tricked into, for example, modifying data on a locally-hosted redis database. +### Validation + +Wallets should warn users if the symbol or name matches or is similar to another token, to avoid phishing scams. + +### Fingerprinting + +To avoid fingerprinting based on wallet behavior and/or listed assets, the RPC call must return as soon as the user is prompted or an error occurs, without waiting for the user to accept or deny the prompt. + ## Copyright Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7480.md b/EIPS/eip-7480.md new file mode 100644 index 00000000000000..d1cafe61fa83c0 --- /dev/null +++ b/EIPS/eip-7480.md @@ -0,0 +1,102 @@ +--- +eip: 7480 +title: EOF - Data section access instructions +description: Instructions to read data section of EOF container +author: Andrei Maiboroda (@gumb0), Alex Beregszaszi (@axic), Paweł Bylica (@chfast) +discussions-to: https://ethereum-magicians.org/t/eip-7480-eof-data-instructions/15414 +status: Review +type: Standards Track +category: Core +created: 2023-08-11 +requires: 3540, 3670 +--- + +## Abstract + +Four new instructions are introduced, that allow to read EOF container's data section: `DATALOAD` loads 32-byte word to stack, `DATALOADN` loads 32-byte word to stack where the word is addressed by a static immediate argument, `DATASIZE` loads data section size and `DATACOPY` copies a segment of data section to memory. + +## Motivation + +Clear separation between code and data is one of the main features of EOF1. Data section may contain anything, e.g. compiler's metadata, but to make it useful for smart contracts, EVM has to have instructions that allow to read from data section. Previously existing instructions for bytecode inspection (`CODECOPY`, `CODESIZE` etc.) are deprecated in EOF1 and cannot be used for this purpose. + +The `DATALOAD`, `DATASIZE`, `DATACOPY` instruction pattern follows the design of existing instructions for reading other kinds of data (i.e. returndata and calldata). + +`DATALOADN` is an optimized version of `DATALOAD`, where data offset to read is set at compilation time, and therefore need not be validated at run-time, which makes the instruction cheaper. + +## Specification + +We introduce four new instructions on the same block number [EIP-3540](./eip-3540.md) is activated on: + +1 `DATALOAD` (0xd0) +2.`DATALOADN` (0xd1) +3.`DATASIZE` (0xd2) +4.`DATACOPY` (0xd3) + +If the code is legacy bytecode, all of these instructions result in an *exceptional halt*. (*Note: This means no change to behaviour.*) + +If the code is valid EOF1, the following execution rules apply: + +### `DATALOAD` + +1. Pops one value, `offset`, from the stack. +2. Reads `[offset:offset+32]` segment from the data section and pushes it as 32-byte value to the stack. +3. If `offset + 32` is greater than the data section size, bytes after the end of data section are set to 0. +4. Deducts 4 gas. + +### `DATALOADN` + +1. Has one immediate argument,`offset`, encoded as a 16-bit unsigned big-endian value. +2. Pops nothing from the stack. +3. Reads `[offset:offset+32]` segment from the data section and pushes it as 32-byte value to the stack. +4. Deducts 3 gas. + +`[offset:offset+32]` is guaranteed to be within data bounds by [code validation](#code-validation). + +### `DATASIZE` + +1. Pops nothing from the stack. +2. Pushes the size of the data section of the active container to the stack. +3. Deducts 2 gas. + +### `DATACOPY` + +1. Pops three values from the stack: `mem_offset`, `offset`, `size`. +2. Performs memory expansion to `mem_offset + size` and deducts memory expansion cost. +3. Deducts `3 + 3 * ((size + 31) // 32)` gas for copying. +4. Reads `[offset:offset+size]` segment from the data section and writes it to memory starting at offset `mem_offset`. +5. If `offset + size` is greater than data section size, 0 bytes will be copied for bytes after the end of the data section. + + +### Code Validation + +We extend code section validation rules (as defined in [EIP-3670](./eip-3670.md)). + +1. Code section is invalid in case an immediate argument `offset` of any `DATALOADN` is such that `offset + 32` is greater than data section size, as indicated in the container header *before deployment*. +2. `RJUMP`, `RJUMPI` and `RJUMPV` immediate argument value (jump destination relative offset) validation: code section is invalid in case offset points to one of two bytes directly following `DATALOADN` instruction. + + +## Rationale + +### Zero-padding on out of bounds access + +Existing instructions for reading other kinds of data implicitly pad with zeroes on out of bounds access, with the only exception of return data copying. + +It is beneficial to avoid exceptional failures, because compilers can employ optimizations like removing a code that copies data, but never accesses this copy afterwards, but such optimization is possible only if instruction never has other side effects like exceptional abort. + +### Lack of `EXTDATACOPY` + +`EXTCODECOPY` instruction is deprecated and rejected in EOF contracts and does not copy contract code when being called in legacy with an EOF contract as target. A replacement instruction `EXTDATACOPY` has been considered, but decided against in order to reduce the scope of changes. + +Data-only contracts which previously relied on `EXTCODECOPY` are thereby discouraged, but if there is a strong need, support for them can be easily brought back by introducing `EXTDATACOPY` in a future upgrade. + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced only for EOF1 contracts, for which deploying undefined instructions is not allowed, therefore there are no existing contracts using these instructions. The new instructions are not introduced for legacy bytecode (code which is not EOF formatted). + +## Security Considerations + +TBA + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7484.md b/EIPS/eip-7484.md new file mode 100644 index 00000000000000..499d431f56267f --- /dev/null +++ b/EIPS/eip-7484.md @@ -0,0 +1,7 @@ +--- +eip: 7484 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7484.md diff --git a/EIPS/eip-7495.md b/EIPS/eip-7495.md new file mode 100644 index 00000000000000..f76cf5423491f4 --- /dev/null +++ b/EIPS/eip-7495.md @@ -0,0 +1,234 @@ +--- +eip: 7495 +title: SSZ StableContainer +description: New SSZ type to represent a flexible container with stable serialization and merkleization +author: Etan Kissling (@etan-status), Cayman (@wemeetagain) +discussions-to: https://ethereum-magicians.org/t/eip-7495-ssz-stablecontainer/15476 +status: Review +type: Standards Track +category: Core +created: 2023-08-18 +--- + +## Abstract + +This EIP introduces two new [Simple Serialize (SSZ) types](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md) to enable forward-compatible containers. + +A `StableContainer[N]` extends an SSZ `Container` with stable merkleization and forward-compatible serialization even when individual fields are deprecated or new fields are introduced in the future. + +Furthermore, `Profile[B]` is introduced to support specialized sub-types of `StableContainer[N]` while retaining the merkleization of the base type. This is useful, e.g., for fork-specific data structures that only use a subset of the base fields and/or when required base fields are known. Verifiers of Merkle proofs for these data structures will not break on new forks. + +## Motivation + +Stable containers and profiles are currently not representable in SSZ. Adding support provides these benefits: + +1. **Stable signatures:** Signing roots derived from a `StableContainer[N]` never change. In the context of Ethereum, this is useful for transaction signatures that are expected to remain valid even when future updates introduce additional transaction fields. Likewise, the overall transaction root remains stable and can be used as a perpetual transaction ID. + +2. **Stable merkle proofs:** Merkle proof verifiers that check specific fields of a `StableContainer[N]` or `Profile[B]` do not need continuous updating when future updates introduce additional fields. Common fields always merkleize at the same [generalized indices](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/merkle-proofs.md). + +3. **Optional fields:** Current SSZ formats do not support optional fields, prompting designs to use zero values instead. With `StableContainer[N]` and `Profile[B]`, the SSZ serialization is compact; inactive fields do not consume space. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +**Note:** In this document, `Optional[T]` exclusively refers to Python's `typing.Optional`. Specifically, `Optional[T]` is NOT an SSZ type itself! + +### `StableContainer[N]` + +Similar to the regular [SSZ `Container`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#composite-types), `StableContainer[N]` defines an ordered heterogeneous collection of fields. `N` indicates the potential maximum number of fields to which it can ever grow in the future. `N` MUST be `> 0`. + +All fields of a `StableContainer[N]` MUST be of of type `Optional[T]`. Such fields can either represent a present value of SSZ type `T`, or indicate absence of a value (indicated by `None`). The [default value](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#default-values) of an `Optional[T]` is `None`. + +```python +class Example(StableContainer[32]): + a: Optional[uint64] + b: Optional[uint32] + c: Optional[uint16] +``` + +For the purpose of serialization, `StableContainer[N]` is always considered ["variable-size"](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#variable-size-and-fixed-size) regardless of the individual field types. + +#### Stability guarantees + +The serialization and merkleization of a `StableContainer[N]` remains stable as long as: + +- The maximum capacity `N` does not change +- The order of fields does not change +- New fields are always appended to the end +- All fields have immutable SSZ schemas, or recursively adopt `StableContainer[N]` +- `List`/`Bitlist` capacities do not change; shortening is possible via application logic + +#### JSON serialization + +JSON serialization follows the [canonical JSON mapping](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#json-mapping) of SSZ `Container`. + +Fields of type `Optional[T]` with a `None` value SHALL be omitted when serializing to JSON. + +#### Binary serialization + +Serialization of `StableContainer[N]` is defined similarly to the [existing logic](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#vectors-containers-lists) for `Container`. Notable changes are: + +- A [`Bitvector[N]`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#composite-types) is constructed, indicating active fields within the `StableContainer[N]`. For fields with a present value (not `None`), a `True` bit is included. For fields with a `None` value, a `False` bit is included. The `Bitvector[N]` is padded with `False` bits up through length `N` +- Only active fields are serialized, i.e., fields with a corresponding `True` bit in the `Bitvector[N]` +- The serialization of the `Bitvector[N]` is prepended to the serialized active fields +- If variable-length fields are serialized, their offsets are relative to the start of serialized active fields, after the `Bitvector[N]` + +```python +# Determine active fields +active_fields = Bitvector[N](([element is not None for element in value] + [False] * N)[:N]) +active_values = [element for element in value if element is not None] + +# Recursively serialize +fixed_parts = [serialize(element) if not is_variable_size(element) else None for element in active_values] +variable_parts = [serialize(element) if is_variable_size(element) else b"" for element in active_values] + +# Compute and check lengths +fixed_lengths = [len(part) if part != None else BYTES_PER_LENGTH_OFFSET for part in fixed_parts] +variable_lengths = [len(part) for part in variable_parts] +assert sum(fixed_lengths + variable_lengths) < 2**(BYTES_PER_LENGTH_OFFSET * BITS_PER_BYTE) + +# Interleave offsets of variable-size parts with fixed-size parts +variable_offsets = [serialize(uint32(sum(fixed_lengths + variable_lengths[:i]))) for i in range(len(active_values))] +fixed_parts = [part if part != None else variable_offsets[i] for i, part in enumerate(fixed_parts)] + +# Return the concatenation of the active fields `Bitvector` with the active +# fixed-size parts (offsets interleaved) and the active variable-size parts +return serialize(active_fields) + b"".join(fixed_parts + variable_parts) +``` + +#### Deserialization + +Deserialization of a `StableContainer[N]` starts by deserializing a `Bitvector[N]`. That value MUST be validated: + +- All extra bits in the `Bitvector[N]` that exceed the number of fields MUST be `False` + +The rest of the data is [deserialized](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#deserialization) same as a regular [SSZ `Container`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#vectors-containers-lists), consulting the `Bitvector[N]` to determine which fields are present in the data. Absent fields are skipped during deserialization and assigned `None` values. + +#### Merkleization + +The [merkleization specification](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#merkleization) is extended with the following helper functions: + +- `chunk_count(type)`: calculate the amount of leafs for merkleization of the type. + - `StableContainer[N]`: always `N`, regardless of the actual number of fields in the type definition +- `mix_in_aux`: Given a Merkle root `root` and an auxiliary SSZ object root `aux` return `hash(root + aux)`. + +To merkleize a `StableContainer[N]`, a `Bitvector[N]` is constructed, indicating active fields within the `StableContainer[N]`, using the same process as during serialization. + +Merkleization `hash_tree_root(value)` of an object `value` is extended with: + +- `mix_in_aux(merkleize(([hash_tree_root(element) if element is not None else Bytes32() for element in value.data] + [Bytes32()] * N)[:N]), hash_tree_root(value.active_fields))` if `value` is a `StableContainer[N]`. + +### `Profile[B]` + +`Profile[B]` also defines an ordered heterogeneous collection of fields, a subset of fields of a base `StableContainer` type `B` with the following constraints: + +- Fields in `Profile[B]` correspond to fields with the same field name in `B`. +- Fields in `Profile[B]` follow the same order as in `B`. +- Fields in the base `StableContainer` type `B` are all `Optional`. + - Fields MAY be disallowed in `Profile[B]` by omitting them. + - Fields MAY be kept optional in `Profile[B]` by retaining them as `Optional`. + - Fields MAY be required in `Profile[B]` by unwrapping them from `Optional`. +- All field types in `Profile[B]` MUST be compatible with the corresponding field types in `B`. + - Field types are compatible with themselves. + - `byte` is compatible with `uint8` and vice versa. + - `Bitlist[N]` / `Bitvector[N]` field types are compatible if they share the same capacity `N`. + - `List[T, N]` / `Vector[T, N]` field types are compatible if `T` is compatible and if they also share the same capacity `N`. + - `Container` / `StableContainer[N]` field types are compatible if all inner field types are compatible, if they also share the same field names in the same order, and for `StableContainer[N]` if they also share the same capacity `N`. + - `Profile[X]` field types are compatible with `StableContainer` types compatible with `X`, and are compatible with `Profile[Y]` where `Y` is compatible with `X` if also all inner field types are compatible. Differences solely in optionality do not affect merkleization compatibility. + +#### Serialization + +Serialization of `Profile[B]` is similar to the one of its base `StableContainer[N]`, except that the leading `Bitvector` is replaced by a sparse representation that only includes information about fields that are optional in `Profile[B]`. Bits for required fields of `Profile[B]` as well as the zero-padding to capacity `N` are not included. If there are no optional fields in `Profile[B]`, the `Bitvector` is omitted. + +`Profile[B]` is considered ["variable-size"](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#variable-size-and-fixed-size) iff it contains any `Optional[T]` or any "variable-size" fields. + +#### Merkleization + +Merkleization of `Profile[B]` follows the merkleization of base type `B`. + +```python +# Defines the common merkleization format and a portable serialization format +class Shape(StableContainer[4]): + side: Optional[uint16] + color: Optional[uint8] + radius: Optional[uint16] + +# Inherits merkleization format from `Shape`, but is serialized more compactly +class Square(Profile[Shape]): + side: uint16 + color: uint8 + +# Inherits merkleization format from `Shape`, but is serialized more compactly +class Circle(Profile[Shape]): + color: uint8 + radius: uint16 +``` + +Serialization examples: + +- `03420001` + + ```Shape(side=0x42, color=1, radius=None)``` + +- `420001` + + ```Square(side=0x42, color=1)``` + +- `06014200` + + ```Shape(side=None, color=1, radius=0x42)``` + +- `014200` + + ```Circle(radius=0x42, color=1)``` + +While this serialization of `Profile[B]` is more compact, note that it is not forward-compatible and that context information that determines the underlying data type has to be indicated out of bands. If forward-compatibility is required, `Profile[B]` SHALL be converted to its base type `B` and subsequently serialized according to `B`. + +## Rationale + +### What are the problems solved by `StableContainer[N]`? + +Current SSZ types are only stable within one version of a specification, i.e., one fork of Ethereum. This is alright for messages pertaining to a specific fork, such as attestations or beacon blocks. However, it is a limitation for messages that are expected to remain valid across forks, such as transactions or receipts. In order to support evolving the features of such perpetually valid message types, a new SSZ scheme needs to be defined. Furthermore, consumers of Merkle proofs may have a different software update cadence as Ethereum; an implementation should not break just because a new fork introduces unrelated new features. + +To avoid restricting design space, the scheme has to support extension with new fields, obsolescence of old fields, and new combinations of existing fields. When such adjustments occur, old messages must still deserialize correctly and must retain their original Merkle root. + +### What are the problems solved by `Profile[B]`? + +The forward-compatible merkleization of `StableContainer` may be desirable even in situations where only a single sub-type is valid at any given time, e.g., as determined by the fork schedule. In such situations, message size can be reduced and type safety increased by exchanging `Profile[B]` instead of the underlying base type. This can be useful, e.g., for consensus data structures such as `BeaconState`, to ensure that Merkle proofs for its fields remain compatible across forks. + +### Why not `Union[T, U, V]`? + +There is combinatorial complexity when new optional features are introduced. For example, if there are three transaction types, and then priority fees are introduced as an optional feature, one has to define three additional transaction types to allow inclusion of a priority fee, raising the total to six transaction types. If, subsequently, optional access lists are introduced, that doubles again, to twelve transaction types. + +`Union` also requires each participant of the network to know about all existing `Union` cases. For example, if the execution layer provides transactions via engine API as a `Union`, the consensus layer would also have to know about all concrete `Union` cases, even though it only wishes to package them and forward them. Using `StableContainer[N]` provides a more similar situation as JSON where the underlying type is determined based on the presence / absence of fields and their values. + +Typically, the individual `Union` cases share some form of thematic overlap, sharing certain fields with each other. In a `Union`, shared fields are not necessarily merkleized at the same [generalized indices](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/merkle-proofs.md). Therefore, Merkle proof systems would have to be updated each time that a new flavor is introduced, even when the actual changes are not of interest to the particular system. + +Furthermore, SSZ Union types are currently not used in any final Ethereum specification and do not have a finalized design themselves. The `StableContainer[N]` serializes very similar to current `Union[T, U, V]` proposals, with the difference being a `Bitvector[N]` as a prefix instead of a selector byte. This means that the serialized byte lengths are comparable. + +### Why not model `Optional[T]` as an SSZ type? + +If `Optional[T]` is modeled as an SSZ type, each individual field introduces serialization and merkleization overhead. As an `Optional[T]` would be required to be ["variable-size"](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/ssz/simple-serialize.md#variable-size-and-fixed-size), lots of additional offset bytes would have to be used in the serialization. For merkleization, each individual `Optional[T]` would require mixing in a bit to indicate presence or absence of the value. + +Additionally, every time that the number of fields reaches a new power of 2, the Merkle roots break, as the number of chunks doubles. The `StableContainer[N]` solves this by artificially extending the Merkle tree to `N` chunks regardless of the actual number of fields currently specified. Because `N` is constant across specification versions, the Merkle tree shape remains stable. The overhead of the additional empty placeholder leaves only affects serialization of the `Bitvector[N]` (1 byte per 8 leaves); the number of required hashes during merkleization only grows logarithmically with `N`. + +## Backwards Compatibility + +`StableContainer[N]` and `Profile[B]` are new SSZ types and do not conflict with other SSZ types currently in use. + +## Test Cases + +See [EIP assets](../assets/eip-7495/tests.py). + +## Reference Implementation + +See [EIP assets](../assets/eip-7495/stable_container.py), based on `protolambda/remerkleable`. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7503.md b/EIPS/eip-7503.md new file mode 100644 index 00000000000000..9a1547405e58d5 --- /dev/null +++ b/EIPS/eip-7503.md @@ -0,0 +1,110 @@ +--- +eip: 7503 +title: Zero-Knowledge Wormholes +description: Enable minting of secretly burnt Ethers as a native privacy solution for Ethereum +author: Keyvan Kambakhsh (@keyvank), Hamid Bateni (@irnb), Amir Kahoori , Nobitex Labs +discussions-to: https://ethereum-magicians.org/t/eip-7503-zero-knowledge-wormholes-private-proof-of-burn-ppob/15456 +status: Stagnant +type: Standards Track +category: Core +created: 2023-08-14 +--- + +## Abstract + +While researching on privacy solutions and applications of ZKP, we discovered a technique, +by which people can burn their digital asset (E.g ETH) by sending it to an unspendable address, +and later build a ZK proof showing that some amount of tokens reside in an account that are +unspendable, without revealing the account. + +The EIP proposes to add a minting functionality to Ethereum, so that people can re-mint +Ethers they have purposefully burnt. The mentioned privacy solution will bring strong levels of +***plausible deniability*** for the sender, since there is no way one can prove that the sender +has been participating in a privacy protocol. This will also make an anonymity pool that includes +all of the Ethereum accounts with zero outgoing transactions by default. + +## Specification + +In Elliptic-Curve based digital signatures, normally there is a secret scalar $s$, from which +a public-key is calculated (By multiplying the generator point with the scalar: $s \times G$). An +Ethereum EOA-address is the keccak hash of a public-key. + +Also, the funds in an Ethereum address might be spendable by a smart-contract, if the keccak hash +of the smart-contract's parameters is equal with that address. + +Therefore, an Ethereum address $A$ is spendable if and only if: + + 1. A private-key $s$ exists. such that $A = keccak(s \times G)$. + 2. There exists a smart-contract $c$, such that $A = keccak(c_{params})$. + +The preimage resistance property of hash functions implies that, you can't find $x$ where $keccak(x)=r$, +in case $r$ is a random value. So the funds sent to a random Ethereum address $r$ is unspendable, but +how can other people be sure that $r$ is indeed random and not the result of calculating $s \times G$? + +A great source of randomness is a hash function. If the address is equal with the hash of a secret preimage +$s$, we can conclude that the address is unspendable, since there isn't a polynomially bounded algorithm +to find $x$ where $keccak(x)=h(s)$. This is only true if the second hash function is a different hash +function, and it assumes it is impossible to find $x_1$ and $x_2$ such that $h_1(x_1)=h_2(x_2)$ in case +$h_1$ and $h_2$ are different hash functions. + +Using the help of Zero-Knowledge proofs, we can hide the value of $s$! We just need to prove that +we know a secret value $s$ where the address is $h(s)$. We can go even further. We can prove +that an Ethereum accounts exists in the state-root, which holds some amount of ETH and is unspendable. + +By revealing this to the Ethereum blockchain and providing something like a nullifier +(E.g. $h(s | 123)$ so that double minting of same burnt tokens are not possible), we can add a new +***minting*** functionality for ETH so that people can migrate their secretly burnt tokens to a +completely new address, without any trace on the blockchain. The target addresses can also be burn +addresses, keeping the re-minted funds in the anonymity pool. + +## Rationale + +Cryptocurrency mixers like TornadoCash can successfully obfuscate Ethereum transactions, but it's +easy for the governments to ban usage of them. Anybody who has interactions with a mixer contract, +whether the sender or receiver, can get marked. However this EIP tries to minimize the privacy leakage +of the senders, by requiring zero smart-contract interactions in order to send money, so +we only use plain EOA-to-EOA transfers. In order to have a "teleportation" mechanism we divide +the set of all Secp256k1 points $E(K)$ into two subsets/address-spaces: + + - The spendable address-space: $\\{p \in \\{0,1\\}^{160} | \exists s : keccak(s \times G)=p \lor \exists c : keccak(c_{params})=p \\}$ + - The unspendable address-space: $\\{p \in \\{0,1\\}^{160} | \nexists s : keccak(s \times G)=p \land \nexists c : keccak(c_{params})=p \\}$ + +The spendable/unspendable addresses are not distinguishable, so we can exploit this fact and define +a spendability rule for the money sent to addresses that can't be spent using regular elliptic-curve +signatures. Using the help of Zero-Knowledge proofs, we can hide the transaction trace and design +a new privacy protocol, which is what this EIP is proposing. + +### Scalability Implications + +In case the circuits are able to simultaneously re-mint the sum of multiple burns in a single-proof, +merchants and CEXs will be able to accept their payments in burn-addresses and accumulate their funds +in a single address by storing a single proof (And a bunch of nullifiers) on the blockchain, which +significantly reduces the transaction count on the blockchain. The people who will use this EIP as a +scalability solution, will also increase the privacy guarantees of the protocol. + +## Backwards Compatibility + +The Ethers generated using the mint function should not have any difference with original Ethers. +People should be able to use those minted Ethers for paying the gas fees. + +## Reference Implementation + +A reference implementation is not ready yet, but here is a design: + +- We will need to track all of the ETH transfers that are happening on the blockchain (Including those + initiated by smart-contracts), and add them to a ZK-friendly Sparse-Merkle-Tree. The amount sent should + also be included in the leaves. +- We will need a new transaction type responsible for minting Ethers. The initiator should provide a proof + (Along with a nullifier) that proves he owns one of the leaves in the merkle-tree that has specific amount + of ETHers + +Alternatively, we can use the already maintained state-trie and provide merkle-patricia-trie proofs, showing +that there exists some amount of ETH in an unspendable account, and mint them. + +## Security Considerations + +In case of faulty implementation of this EIP, people may mint infinite amount of ETH, collapsing the price of Ethereum. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7507.md b/EIPS/eip-7507.md new file mode 100644 index 00000000000000..db0d6b48a9a222 --- /dev/null +++ b/EIPS/eip-7507.md @@ -0,0 +1,7 @@ +--- +eip: 7507 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7507.md diff --git a/EIPS/eip-7508.md b/EIPS/eip-7508.md new file mode 100644 index 00000000000000..4e049b0bbe4510 --- /dev/null +++ b/EIPS/eip-7508.md @@ -0,0 +1,7 @@ +--- +eip: 7508 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7508.md diff --git a/EIPS/eip-7511.md b/EIPS/eip-7511.md new file mode 100644 index 00000000000000..2b1f2863c2d8c2 --- /dev/null +++ b/EIPS/eip-7511.md @@ -0,0 +1,7 @@ +--- +eip: 7511 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7511.md diff --git a/EIPS/eip-7512.md b/EIPS/eip-7512.md new file mode 100644 index 00000000000000..519d31a50c4921 --- /dev/null +++ b/EIPS/eip-7512.md @@ -0,0 +1,7 @@ +--- +eip: 7512 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7512.md diff --git a/EIPS/eip-7514.md b/EIPS/eip-7514.md new file mode 100644 index 00000000000000..80e303a23f1762 --- /dev/null +++ b/EIPS/eip-7514.md @@ -0,0 +1,93 @@ +--- +eip: 7514 +title: Add Max Epoch Churn Limit +description: Modify the churn limit function to upper bound it to a max value +author: dapplion (@dapplion), Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-7514-add-max-epoch-churn-limit/15709 +status: Final +type: Standards Track +category: Core +created: 2023-09-07 +--- + +## Abstract + +Update the maximum validator growth rate from an exponential to a linear increase by capping the epoch churn limit. + +## Motivation + +This proposal aims to mitigate the negative externalities of very high level of total ETH supply staked before a proper solution is implemented. In other words, this proposal accepts the complexities of changing the rewards curve and is meant only to slow down growth. + +In the event that the deposit queue stays 100% full, the share of ETH supply staked will reach 50% by May 2024, 75% by September 2024, and 100% by December 2024. While rewards decrease as the validator set size increases, at 100% of ETH supply staked, yearly consensus rewards alone (excluding MEV/transaction fees) for validators still represent ~1.6% of their stake. This small yield does not necessarily dissuade additional capital staking due to the often much higher and unpredictable yields from MEV. As such, the equilibrium point of the validator set size can be close to its maximum possible. Liquid staking tokens (LSTs) also contribute to this, given stakers can use them as they use unstaked ETH. + +As the levels of ETH staked increase, more strain is put on the consensus layer. A larger number of validators leads to an increase in gossip messages, as well as a growing Beacon state size. Additionally, as the amount of stake grows, it's unclear how much marginal security benefits come from additional economic weight. + +The Beacon Chain validator reward function was chosen before its launch in 2020. PoS research and reward curve design were performed in a pre-MEV world. Much has changed since then, including the Beacon chain achieving unprecedented success, beyond the original intended targets of stake rate. In light of this, it is worth discussing whether Beacon chain validator rewards should be adjusted to better match today's reality, potentially to discourage staking past a certain point. + +This EIP does not attempt to do this, but to allow more time for the community to have these discussions. By limiting the epoch churn limit now, the time to reach critical milestones of total ETH supply staked are significantly delayed. This allows more time for research into more comprehensive solutions, and for community consensus around them to emerge. + +## Specification + +### Constants + +| Name | Value | +| ---- | ----- | +| `MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT` | 8 | + +### Execution layer + +This requires no changes to the Execution Layer. + +### Consensus layer + +- Add `get_validator_activation_churn_limit` with upper bound `MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT` +- Modify `process_registry_updates` to use bounded activation churn limit + +The full specification of the proposed change can be found in [`/specs/deneb/beacon-chain.md`](https://github.com/ethereum/consensus-specs/blob/69d34dc4ee3d026ca437d1b6875b218e8aaf3a5c/specs/deneb/beacon-chain.md). + +## Rationale + +### `MAX_PER_EPOCH_CHURN_LIMIT` value + +Depending on the specific constant selection the churn can _decrease_ at the activation fork epoch. The Beacon chain spec can handle this without issues. During 2023 Q4 (projected Dencun activation) the churn value will range 14-16. The table below compares the projected validator set assuming a continuous full deposit queue. + +#### `MAX_PER_EPOCH_CHURN_LIMIT` activation date: Dec 01, 2023 + +| Max Churn Limit | 50% ETH staked | 75% ETH staked | 100% ETH staked | +|------------------:|:-----------------|:-----------------|:------------------| +| inf | May 28, 2024 | Sep 25, 2024 | Dec 18, 2024 | +| 16 | Jul 23, 2024 | Apr 10, 2025 | Dec 26, 2025 | +| 12 | Oct 09, 2024 | Sep 21, 2025 | Sep 04, 2026 | +| 8 | Mar 15, 2025 | Aug 18, 2026 | Jan 21, 2028 | +| 6 | Aug 19, 2025 | Jul 14, 2027 | Jun 08, 2029 | +| 4 | Jun 29, 2026 | May 05, 2029 | Mar 12, 2032 | + +#### `MAX_PER_EPOCH_CHURN_LIMIT` activation date: Apr 01, 2024 + +| Max Churn Limit | 50% ETH staked | 75% ETH staked | 100% ETH staked | +|------------------:|:-----------------|:-----------------|:------------------| +| inf | May 28, 2024 | Sep 25, 2024 | Dec 18, 2024 | +| 16 | Jul 01, 2024 | Mar 18, 2025 | Dec 04, 2025 | +| 12 | Aug 01, 2024 | Jul 14, 2025 | Jun 26, 2026 | +| 8 | Oct 01, 2024 | Mar 05, 2026 | Aug 08, 2027 | +| 6 | Dec 01, 2024 | Oct 26, 2026 | Sep 20, 2028 | +| 4 | Apr 02, 2025 | Feb 07, 2028 | Dec 15, 2030 | + +Assuming that the earliest the next fork can happen is at the start of 2024 Q3, a value of 8 provides a significant reduction in projected size without causing a big drop in churn at a projected Dencun fork date. A value of 8 prevents reaching a level of 50% ETH staked for at least 1 full year even with a delayed dencun fork. + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. + +## Test Cases + +Test cases for this EIP can be found in the [`deneb`](https://github.com/ethereum/consensus-specs/tree/2297c09b7e457a13f7b2261a28cb45777be82f83/tests/core/pyspec/eth2spec/test/deneb) test suite of the `consensus-specs` repository. + +## Security Considerations + +This EIP breaks the symmetry between the validator entry and exit queues, where the former is bound by `MAX_PER_EPOCH_ACTIVATION_CHURN_LIMIT` while the latter isn't. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-7516.md b/EIPS/eip-7516.md new file mode 100644 index 00000000000000..dcd2f4ede58a6e --- /dev/null +++ b/EIPS/eip-7516.md @@ -0,0 +1,73 @@ +--- +eip: 7516 +title: BLOBBASEFEE instruction +description: Instruction that returns the current data-blob base-fee +author: Carl Beekhuizen (@carlbeek) +discussions-to: https://ethereum-magicians.org/t/eip-7516-blobbasefee-opcode/15761 +status: Final +type: Standards Track +category: Core +created: 2023-09-11 +requires: 3198, 4844 +--- + +## Abstract + +Add a `BLOBBASEFEE (0x4a)` instruction that returns the value of the blob base-fee of the current block it is executing in. It is the identical to [EIP-3198](./eip-3198.md) (`BASEFEE` opcode) except that it returns the blob base-fee as per [EIP-4844](./eip-4844.md). + +## Motivation + +The intended use case would be for contracts to get the value of the blob base-fee. This feature enables blob-data users to programmatically account for the blob gas price, eg: + +- Allow rollup contracts to trustlessly account for blob data usage costs. +- Blob gas futures can be implemented based on it which allows for blob users to smooth out data blob costs. + +## Specification + +Add a `BLOBBASEFEE` instruction with opcode `0x4a`, with gas cost `2`. + +| Op | Input | Output | Cost | +|------|-------|--------|------| +| 0x4a | 0 | 1 | 2 | + +`BLOBBASEFEE` returns the result of the `get_blob_gasprice(header) -> int` function as defined in [EIP-4844 §Gas accounting](./eip-4844.md#gas-accounting). + +## Rationale + +### Gas cost + +The value of the blob base-fee is needed to process data-blob transactions. That means its value is already available before running the EVM code. +The instruction does not add extra complexity and additional read/write operations, hence the choice of `2` gas cost. This is also identical to [EIP-3198](./eip-3198.md) (`BASEFEE` opcode)'s cost as it just makes available data that is in the header. + +## Backwards Compatibility + +There are no known backward compatibility issues with this instruction. + +## Test Cases + +### Nominal Case + +Assume calling `get_blob_gasprice(header)` (as defined in [EIP-4844 §Gas accounting](./eip-4844.md#gas-accounting)) on the current block's header returns `7 wei`: +`BLOBBASEFEE` should push the value `7` (left padded byte32) to the stack. + +Bytecode: `0x4900` (`BLOBBASEFEE, STOP`) + +| Pc | Op | Cost | Stack | RStack | +|----|-------------|------|-------|--------| +| 0 | BLOBBASEFEE | 2 | [] | [] | +| 1 | STOP | 0 | [7] | [] | + +Output: 0x +Consumed gas: `2` + +### Comprehensive Test Suite + +A complete suite of tests can be found [here](https://github.com/ethereum/execution-spec-tests/blob/1983444bbe1a471886ef7c0e82253ffe2a4053e1/tests/cancun/eip7516_blobgasfee/test_blobgasfee_opcode.py). + +## Security Considerations + +The value of the blob base-fee is not sensitive and is publicly accessible in the block header. There are no known security implications with this instruction. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7519.md b/EIPS/eip-7519.md new file mode 100644 index 00000000000000..9f25e9bda6f04d --- /dev/null +++ b/EIPS/eip-7519.md @@ -0,0 +1,200 @@ +--- +eip: 7519 +title: Atomic Storage Operations SCREDIT and SDEBIT +description: Add atomic operations for incrementing and decrementing storage slots +author: Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/eip-7519-atomic-storage-operations-scredit-and-sdebit/15818 +status: Stagnant +type: Standards Track +category: Core +created: 2023-09-16 +requires: 2200, 2929 +--- + +## Abstract + +Two new opcodes that atomically mutate smart contract storage are proposed: +SCREDIT, which increments a storage slot by a specified value, and SDEBIT, which +decrements a storage slot by a specified value. Overflow and underflow errors +are enforced, reverting when an unsigned 256-bit integer would overflow or +underflow. + +## Motivation + +There has been a large amount of energy around parallel EVMs across multiple +chains, however there is a lack of parallel primitives within the EVM to support +any model other than optimistic concurrency control (OCC). By adding concurrent +increment and decrement operations more advanced parallel environments can be +introduced in Layer 2 networks. + +This also provides the opportunity to serve the principal use case of increment +and decrement: token balances. We can introduce failures on overflow and +underflow conditions and provide an operation that is also useful outside of +parallel use cases. + +## Specification + +Two operations to atomically increment and decrement a storage will be +introduced +at `0xTBD`. Each operation takes two stack arguments and has no immediate +arguments. Gas schedule will be the same as SSTORE. + +| Mnemonic | Op | Input | Output | +|-----------|-----------|-------|--------| +| `SCREDIT` | `0xTBD` | `2` | `0` | +| `SDEBIT` | `0xTBD+1` | `2` | `0` | + +### SCREDIT + +`SCREDIT: slot, value` + +#### Description + +Adds `value` to the value stored in contract storage `slot.` If an overflow +would occur the operation halts exceptionally. + +#### Gas Charging + +Gas charging is identical to SSTORE. including interactions with the warm +storage slot list. Any future modifications to the SSTORE gas charges will also +apply to SCREDIT. + +#### Execution + +*Not valid python, not suitable for EELS yet* + +``` +slot = evm_stack.pop() +value = evm_stack.pop() + +storage_value = read_contract_storage(slot) +storage_value = storage_value + value + +if storage_value >= 2**256 : + raise Exception("scredit overflow") + +write_contract_storage(storage_value) +``` + +### SDEBIT + +`SDEBIT: slot, value` + +#### Description + +Subtracts `value` to the value stored in contract storage `slot.` If an +underflow would occur the operation halts exceptionally. + +#### Gas Charging + +Gas charging is identical to SSTORE, including interactions with the warm +storage slot list. Any future modifications to the SSTORE gas charges will also +apply to SDEBIT. + +#### Execution + +*Not valid python, not suitable for EELS yet* + +``` +slot = evm_stack.pop() +value = evm_stack.pop() + +storage_value = read_contract_storage(slot) +storage_value = storage_value - value + +if storage_value < 0 : + raise Exception("sdebit underflow") + +write_contract_storage(storage_value) +``` + +## Rationale + +The primary consideration when choosing between alternatives is that the primary +intended audiences is token contracts and other asset-tracking contracts +combined with a desire to ship the minimum necessary changes to enable that use +case. General concurrency controls is not a goal of this EIP. + +### Enforcing Overflow Semantics + +When allowing for out-of-order execution there needs to be mechanism to handle +any possible order of execution. OCC handles this by validating pre- and +post-conditions, and re-evaluating the transactions if those invariants did not +hold. This technique breaks down around writing to balances and counters. + +Increment/decrement with rollover checking allows for simple handling of +balances and counters while allowing for functional read support ensuring that +sufficient balance or count exists without depending on the exact values. This +allows for evaluation models where the only post-condition checked is to +validate that the storage slots could handle all possible re-ordering of +transactions. + +### Gas Schedule + +The decision to cost the operations at the exact same value as SSTORE is partly +for ease of implementation and partly as an incentive to compilers and +developers. + +These semantics could be implemented in the EVM today, but it would also include +a SLOAD, DUP, LT, JUMPI and REVERT instructions. The EVM, however, can do these +operations much more efficiently than via opcodes. First, each SSTORE always +incurs a slot load in order to apply [EIP-2200](./eip-2200.md) gas calculation +rules. This load is essential if there is no paired SLOAD. Math libraries for +256-bit numbers can all easily be made sensitive to overflow and underflow, if +they are not already present. Conditional logic handling is also much faster in +the operation logic as most of the overhead would be operation parsing and stack +management when interpreted. + +The net impact of the most relevant operations to the most expensive +evaluation (an ADD and LT operation, above the cost of a plain SSTORE) would be +4 gas, or 0.2% of the current cost of a SSTORE. Finally, database access costs +dominate the real cost of the operation. A 0.2% overhead may disappear in I/O +stalls. + +Keeping the cost the same makes implementations of gas charging vert simple. + +### Storage Slots Only + +This most important use case for this EIP asset balances and not general +concurrency controls. Hence, only enabling credit and debit operations on +storage slots (which persist across transactions). Parallel execution within a +transaction and more generic tools like locks and semaphores have very limited +utility within this scope. The lack of in-transaction parallel execution also +precludes the use of such primitives against transient storage (as defined in +[EIP-1153](./eip-1153.md)). + +### Opcode Instead of System Contract + +One alternative, particularly viable for Layer 2 chains, would be to implement +SCREDIT and SDEBIT as system contracts. The primary objection to system +contracts for other operations is the gas cost overhead of constructing a call. +Because a SSTORE is always greater than the cost of a call it would be possible +to build in a discount. However, there is no such accommodation that can be made +for the code size needed to invoke such a call. + +## Backwards Compatibility + +These opcodes are not simple replacements for SLOAD-(ADD|SUB)-SSTORE sequence +because there is an overflow/underflow check + +There is no EVM functionality removed by this proposal. + +## Test Cases + +Test for overflow and non-overflow for the following values and values before +and after: + +1, 2^8, 2^16, 2^32, 2^64, 2^128 2^255, 2^256-1. + +## Reference Implementation + +/# TBD + +## Security Considerations + +The use of revert to handle over/underflow represents a new halt condition that +auditors will need to consider when examining reentrancy concerns. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7521.md b/EIPS/eip-7521.md new file mode 100644 index 00000000000000..59da150e82254c --- /dev/null +++ b/EIPS/eip-7521.md @@ -0,0 +1,7 @@ +--- +eip: 7521 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7521.md diff --git a/EIPS/eip-7522.md b/EIPS/eip-7522.md new file mode 100644 index 00000000000000..0ccca36a4cafff --- /dev/null +++ b/EIPS/eip-7522.md @@ -0,0 +1,7 @@ +--- +eip: 7522 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7522.md diff --git a/EIPS/eip-7523.md b/EIPS/eip-7523.md new file mode 100644 index 00000000000000..55a1e9a3329e45 --- /dev/null +++ b/EIPS/eip-7523.md @@ -0,0 +1,71 @@ +--- +eip: 7523 +title: Empty accounts deprecation +description: Prohibit empty accounts on post-merge networks +author: Peter Davies (@petertdavies) +discussions-to: https://ethereum-magicians.org/t/eip-7523-empty-accounts-deprecation/15870 +status: Last Call +last-call-deadline: 2024-03-26 +type: Standards Track +category: Core +created: 2023-09-19 +requires: 161 +--- + +## Abstract + +This EIP prohibits the state of any post-merge network from containing empty accounts. Since no empty accounts exist outside the testsuite and no new ones can be created this requirement is already achieved in practice. An explicit ban reduces technical debt going forward. + +## Motivation + +The possibility of empty accounts is a historical artifact of the early history of Ethereum. The only networks that have ever been capable of containing them are Ethereum Mainnet, the deprecated testnet Ropsten, Etheruem Classic Mainnet and various Ethereum Classic testnets. All remaining empty accounts on Mainnet were cleared in block `14049881` (transaction `0xf955834bfa097458a9cf6b719705a443d32e7f43f20b9b0294098c205b4bcc3d`) and a similar transaction was sent on Ethereum Classic. None of the other myriad EVM-compatible networks are old enough to have empty accounts and there is no realistic prospect that anyone will encounter an empty account in a production context. + +Despite empty accounts no longer existing, they still impose a legacy of technical debt. [EIP-161](./eip-161.md) imposes complicated rules that require a client to delete an empty account when it is "touched". As the Ethereum specification continues to evolve new edgecases of the "touch" rules arise which must be debated, implemented, tested and documented. If a future client wishes to only support post-merge blocks it must implement unnecessary empty account support solely to pass the test suite. + +By prohibiting empty accounts on post-merge networks, this EIP frees designers and implementers of Ethereum and related blockchains from the burden of having to consider them going forward. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +An empty account is an account with has **no code** and **zero nonce** and **zero balance**. This is the same as the definition in [EIP-161](./eip-161.md). + +On networks that undergo the merge transition, the pre state of the merge block may not contain any empty accounts. For networks that are merged at genesis, none of the genesis accounts may be empty accounts. + +Rather than performing a scan of the state, clients MAY assume the following chains have no post-merge empty accounts: + +1. The Mainnet chain whose merge block has hash `0x56a9bb0302da44b8c0b3df540781424684c3af04d0b7a38d72842b762076a664`. + +2. Any chain which satisfies all of the following: + + - has no empty accounts in the genesis. + + - had a post Spurious Dragon fork at genesis. + +The Ethereum specification is declared to be undefined in the presence of an empty account in a post-merge context. Any testcase involving post-merge empty accounts is invalid. + +## Rationale + +This EIP was drafted to be the simplest possible way of eliminating the long term technical debt imposed by empty accounts. The Merge was chosen as a natural easily identifiable cutoff point. + +Alternative approaches include: + +- Using an earlier cutoff point, such as block `14049881`. + +- Identifying a wider range of edge case behaviour that never happened. + +These approaches were rejected as being unnecessarily complicated. + +## Backwards Compatibility + +As EIP does not change any behaviour that can occur outside the testsuite, it has no backwards compatibility consequences. + +## Security Considerations + +The validity of this EIP is dependent on the assertion that all empty accounts on Ethereum Mainnet were cleared prior to the merge. This should be subject to appropriate verification. + +Any networks artificially created with empty accounts will cause problems with tooling and clients. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7528.md b/EIPS/eip-7528.md new file mode 100644 index 00000000000000..d882dedd83cc2e --- /dev/null +++ b/EIPS/eip-7528.md @@ -0,0 +1,7 @@ +--- +eip: 7528 +category: ERC +status: Moved +--- + +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-7528.md diff --git a/EIPS/eip-7542.md b/EIPS/eip-7542.md new file mode 100644 index 00000000000000..937a145fa37642 --- /dev/null +++ b/EIPS/eip-7542.md @@ -0,0 +1,64 @@ +--- +eip: 7542 +title: eth/70 - available-blocks-extended protocol +description: Adds more info in the handshake about available block range and adds message types to request block ranges and the send them +author: Ahmad Bitar (@smartprogrammer93) +discussions-to: https://ethereum-magicians.org/t/eip-eth-70-available-blocks-extended-protocol-handshake/16188 +status: Draft +type: Standards Track +category: Networking +created: 2023-10-21 +requires: 7642 +--- +## Abstract + +The purpose of this EIP is to introduce a method that allows an Ethereum node to communicate the range of blocks it has available. By knowing the block range a node can serve, peers can make more informed decisions when choosing whom to request blocks from or whom to connect to, especially when looking for specific block ranges. This can lead to more efficient network behavior. + +This EIP proposes extending the Ethereum wire protocol (`eth`) handshake, introducing a new version, `eth/70`, which will contain information regarding the block range a node can serve. Furthermore, it extends the protocol with two new message types to share the updated block ranges when requested. + +## Motivation + +In a first stage of [EIP-4444](./eip-4444.md), some nodes will still need to serve the historical data of the chain and others might be interested in starting to prune it. Currently, nodes need to connect to peers and request specific blocks to determine if a peer has the requested data. This can be inefficient, leading to unnecessary data requests and wasting both bandwidth and time. Consequently, this change empowers nodes that still want to retrieve historical data from the network to do so efficiently. + +As a bonus, This change enhances the efficiency of synchronization by allowing a node to determine if a peer, potentially still in the process of syncing, has the necessary blocks available, thereby avoiding unnecessary block requests and potential empty responses. + +## Specification + +- Advertise a new `eth` protocol capability (version) at `eth/70`. + - The old `eth/69` protocol should still be kept alive side-by-side, until `eth/70` is sufficiently adopted by implementors. +- Modify the `Status (0x00)` message for `eth/70` to add an additional `blockRange` field right after the `forkid`: + - Current packet for `eth/69`: `[version: P, networkid: P, blockhash: B_32, genesis: B_32, forkid]` + - New packet for `eth/70`: `[version: P, networkid: P, blockhash: B_32, genesis: B_32, forkid blockRange]`, + where `blockRange` is `[startBlock: uint64, endBlock: uint64]`. + +- Introduce two new message types: + - `RequestBlockRange (0x0b)` - A message from a node to request the current block range of a peer. + - `SendBlockRange (0x0c): [startBlock: uint64, endBlock: uint64]` - The response to `RequestBlockRange`, informing the requesting node of the current available block range of the peer. + +Upon connecting using `eth/70`, nodes should exchange the `Status` message. Afterwards, they can use the `RequestBlockRange` and `SendBlockRange` messages to keep informed about peer block range changes. + +Nodes must retain connections regardless of a peer's available block range, with an exception, if a node's peer slots are full and it lacks connections to peers with the necessary block range, it may disconnect to seek such peers. + +## Rationale + +Including the available block range in the `eth` handshake allows for immediate understanding of peer capabilities. This can lead to more efficient networking as nodes can prioritize connections based on the data they need. +The new message types are introduced to allow nodes to request updated available block range from other nodes since the range can change by the node syncing or pruning blocks. +Maintaining connections with peers that don't have the desired range ensures network resilience, while the exception facilitates efficient block sync under full peer capacity. + +## Backwards Compatibility + +This EIP extends the `eth` protocol handshake in a backwards incompatible manner and proposes the introduction of a new version, `eth/70`. However, `devp2p` allows for multiple versions of the same wire protocol to run concurrently. Hence, nodes that have not been updated can continue using older versions like `eth/69`, `eth/68` or `eth/67`. + +This EIP doesn't affect the consensus engine and doesn't necessitate a hard fork. + +## Test Cases + +Testing will involve ensuring that nodes can correctly communicate and understand the block range information during the handshake. Additionally, it will involve ensuring nodes can correctly request and share updated block range when requested. + +## Security Considerations + +This change is not a standardization of not storing and serving historical blocks before the implementation of alternative historical blocks storage solutions. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7543.md b/EIPS/eip-7543.md new file mode 100644 index 00000000000000..cf78849e7aac8c --- /dev/null +++ b/EIPS/eip-7543.md @@ -0,0 +1,129 @@ +--- +eip: 7543 +title: EVM arbitrary precision decimal math +description: This EIP adds OPCODEs to allow arbitrary precision decimal float calculation of all elementary functions with precise gas enumeration. +author: 1m1 (@1m1-github) +discussions-to: https://ethereum-magicians.org/t/decimal-math-on-evm/16194 +status: Draft +type: Standards Track +category: Core +created: 2023-10-22 +--- + + +## Abstract + +This EIP adds *arbitrary precision decimal float* OPCODEs for arithmetic via DECADD, DECNEG, DECMUL, DECINV and expression of all elementary functions via DECEXP, DECLN, DECSIN. All decimal values upto the maximal precision allowed by a int256 coefficient and exponent are represented exactly, as c*10^q. All implemented algorithms converge for all inputs given enough precision, as chosen by the user. All calculations are deterministic and gas is precisely embedded bottom-up. Allowing arbitrary precision decimal elementary functions invites the worlds of mathematical finance, machine learning, science, digital art, games and others to Ethereum. The implementation is functional. + +## Motivation + +Currently, to take a power, a^b, of non integer values, requires vast amounts of Solidity code. +The simplest task in trading e.g. is to convert volatilities from yearly to daily, which involves taking the 16th root. + +Giving users/devs the same ability that scientific calculators have allows for the creation of apps with higher complexity. + +The files [BlackScholes.yul](../assets/eip-7543/BlackScholes.yul) and [Neuron.yul](../assets/eip-7543/Neuron.yul) demonstrate how these OPCODEs simplify numerical smart contract code. + +### Why decimal? + +To represent a simple value like 0.1 in binary requires infinite many digits and is therefore not exactly represently in a finite binary machine. Decimal types are much closer to the vast majority of numerical calculations run by humans. + +### eVm + +The EVM is a virtual machine and thereby not restricted by hardware. Usually, assembly languages provide OPCODES that are mimic the ability of hardware. In a virtual machine, we have no such limitations and nothing stops us from adding more complex OPCODEs, as long as fair gas is provided. At the same time, we do not want to clutter the OPCODEs library. EXP, LN and SIN are universal functions that open the path to: powers, trigonometry, integrals, differential equations, machine learning, digital art, etc. + +## Specification + +### Decimal + +A decimal is defined as + +c * 10^q + +where c and q are int256. + +Notationwise: +a = ac * 10^aq +b = bc * 10^bq +etc. + +### OPCODE defs + +0xd0 DECADD a+b -> c : (ac, aq, bc, bq, precision) -> (cc, cq) +0xd1 DECNEG -a -> b : (ac, aq) -> (bc, bq) +0xd2 DECMUL a*b -> c : (ac, aq, bc, bq, precision) -> (cc, cq) +0xd3 DECINV 1/a -> b : (ac, aq, precision) -> (bc, bq) +0xd4 DECEXP exp(a) -> b : (ac, aq, precision, steps) -> (bc, bq) +0xd5 DECLN ln(a) -> b : (ac, aq, precision, steps) -> (bc, bq) +0xd6 DECSIN sin(a) -> b : (ac, aq, precision, steps) -> (bc, bq) + +`precision` is the # of digits kept during all calculations. `steps` for DECEXP and DECSIN are the # of Taylor expansion steps. `steps` for DECLN is the depth of the continued fractions expansion. + +### Why these functions? + +The proposed functions (+,-,*,/,exp,ln,sin) form a small set that combined enable all calculation of all elementary functions, which includes the sets of sums, products, roots and compositions of finitely many polynomial, rational, trigonometric, hyperbolic, and exponential functions, including their inverse functions. + +a^b = exp(b * ln(a)) gives us powers and polynomials. +cos(a) = sin(tau/4-a), tan(a)=sin(a)/cos(a), etc., gives us all of trigonometry. + +Together with arithmetic, we get all elementary functions. + +### DECNEG instead of DECSUB + +Negation is a more general operation vs subtraction. OPCODEs should be as fundamental as possible and as complex as desirable. +For the same reason, we have DECINV instead of DECDIV. + +DECSUB(a,b) = DECADD(a,DECNEG(b)) +DECDIV(a,b) = DECMUL(a,DECINV(b)) + +### DECEXP, DECSIN via Taylor series + +The Taylor series of exp and sin converge everywhere and fast. The error falls as fast as the factorial of steps. + +### DECLN via continued fractions + +Ln converges fast using continued fractions within the interval ]0,2]. The implementation scales the input into this interval and scales the result back correctly. + + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +## Rationale + +### gas + +All the above OPCODEs are deterministic, hence the gas cost can be determined. At the same time, the calculations are complex and depend on the input. + +It is crucial to have accurate gas costs to avoid energy attacks on nodes. + +To this end, the underlying uint256 lib can be wrapped with gas accumulation, as found in the reference implementation in ../assets/eip-EVM+/uint256_wrapped.go. This gives a bottom-up approach to calculating gas, by running the OPCODE. + +Because the EVM interprator expects the gas cost before actually running the OPCODE, we are running the OPCODE twice. the first run, identical to the second, is to get the bottom-up gas cost, which is then doubled to account for the actual run plus the gas calculation. On top, we add a fixed emulation cost. + +This gives an embedded gas calculation, which works well for complex OPCODEs (see gasEVMPlusEmulate in ../assets/eip-EVM+/gasEVMPlusEmulate.go). + +To remove the double gas, we could find an upper bound on gas usage dependent on the function inputs. +Alternatively, a future EIP would suggest the following: allow contract code to run whilst accumulating gas (at runtime) and panicking in case of limit breach, without requiring the cost in advance. This only works for contract code that is pure, defined as code that only depends on the user input and the inner bytecode of the contract. Pure contracts cannot use state from the chain, nor make calls to other contracts. pure mathematical functions would e.g. be pure contracts. pure contracts are fully deterministic given the input, allowing a user to estimate gas costs offline (cheaper) and the EVM to panic at runtime, without knowing gas in advance. + +Since the costs depend on the input, a fuzzing would give us close to the worst cases (TODO). + +## Backwards Compatibility + +No backward compatibility issues found. + +Since the EVM allows contracts to deploy with invalid code, there could be previously invalid code that becomes valid when adding a new OPCODE. The EVM could be designed to expect a version tag at the beginning of all bytecode or (not xor) to only deploy valid code. This is an issue for any new OPCODE. + +## Test Cases + +../assets/eip-EVM+/decimal_float_test.go + +## Reference Implementation + +The reference implementation is found in ../assets/eip-EVM+/decimal_float.go + +## Security Considerations + +There are no security considerations, as long as numerical correctness is guaranteed and gas is collected fairly. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7545.md b/EIPS/eip-7545.md new file mode 100644 index 00000000000000..069a248de97901 --- /dev/null +++ b/EIPS/eip-7545.md @@ -0,0 +1,102 @@ +--- +eip: 7545 +title: Verkle proof verification precompile +description: Add a precompile to help dapps verify verkle proofs +author: Guillaume Ballet (@gballet), Diederik Loerakker (@protolambda) +discussions-to: https://ethereum-magicians.org/t/verkle-proof-verification-precompile/16274 +status: Draft +type: Standards Track +category: Core +created: 2023-10-13 +--- + +## Abstract + +This EIP proposes the addition of a precompiled contract to provide up-to-date state proof verification capabilities to smart contracts in a stateless Ethereum context. + +## Motivation + +The proposed proof systems for stateless Ethereum require an upgrade to many tools and applications, that need a simple path to keep their proving systems up-to-date, without having to develop and deploy new proving libraries each time another proof format must be supported. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +A precompiled contract is added at address `0x21`, wrapping the stateless ethereum proof verification function. + +The precompile's `input` is the tightly packed concatenation of the following fields: + + * `version` (1 byte) specifies which version of the stateless proof verification function should be used. Version 0 is used for an MPT and version 1 is used for the polynomial commitment scheme multiproof used in [EIP-6800](./eip-6800.md). + * `state_root` (32 bytes) specifies the state root that the proof is proving against. + * `proof_data` (arbitrary long) is the proof data. + +Pseudo-code behavior of the precompile: + +```python +def proof_verification_precompile(input): + version = input[0] + state_root = input[1:33] + proof_data = input[33:33+proof_data_size] + + if version == 0: + proof = deserialize_proof(state_root, proof_data) + return verify_mpt_multiproof(proof) + + if version == 1: + proof = deserialize_proof(state_root, proof_data) + return verify_pcs_multiproof(proof) + + return 0 +``` + +If `version` is `0` then the proof is expected to follow the SSZ format described in "the verge" proposal in the consensus spec. + +The precompile returns `1` if it was able to verify the proof, and `0` otherwise. + +### Gas costs + +|Constant name|cost| +|-|-| +|`POINT_COST`|TBD| +|`POLY_EVAL_COST`|TBD| + +The precompile cost is: + +`cost = (POINT_COST + 1)*len(get_commitments(input)) + POLY_EVAL_COST * [leaf_depth(key, get_tree(input)) for key in get_keys(input))]` + +where: + + * `get_commitments` extracts the list of commitments in the proof, as encoded in `input` + * `get_keys` extracts the list of keys in the proof, as encoded in `input` + * `leaf_depth` returns the depth of the leaf in the tree + * `get tree` reconstruct a stateless view of the tree from `input` + +## Rationale + +Stateless Ethereum relies on proofs using advanced mathematical concepts and tools from a fast-moving area of cryptography. As a result, a soft-fork approach is currently favored in the choice of the proof format: proofs are going to be distributed outside of consensus, and in the future, stateless clients will be able to chose their favorite proof format. + +This introduces a burden on several application, e.g. bridges, as they will potentially need to support proof formats designed after the release of the bridge contract. + +Delegating the proof verification burden to a version-aware precompile will ensure that these applications can support newer proving primitives without having to upgrade their contracts. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Test Cases + +TODO + +## Reference Implementation + +WIP + + * First implementation in Optimism, pull request #192 of ethereum-optimism/op-geth by @protolambda + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7547.md b/EIPS/eip-7547.md new file mode 100644 index 00000000000000..7550f1a9fbf791 --- /dev/null +++ b/EIPS/eip-7547.md @@ -0,0 +1,172 @@ +--- +eip: 7547 +title: Inclusion lists +description: Add an inclusion list mechanism to allow forced transaction inclusion. +author: mike (@michaelneuder), Vitalik (@vbuterin), Francesco (@fradamt), Terence (@terencechain), potuz (@potuz), Manav (@manav2401) +discussions-to: https://ethereum-magicians.org/t/eip-7547-inclusion-lists/17474 +status: Review +type: Standards Track +category: Core +created: 2023-10-24 +--- +## Abstract + +Censorship resistance is a core value proposition of blockchains. Inclusion lists aim to provide a mechanism to improve the censorship resistance of Ethereum by allowing proposers to specify a set of transactions that must be promptly included for subsequent blocks to be considered valid. + +## Motivation + +Since the merge, validators have started outsourcing almost all block production to a specialized set of builders who compete to extract the most MEV (this is commonly referred to as Proposer-Builder Separation). As of October 2023, nearly 95% of blocks are built by builders rather than the proposer. While it is great that all proposers have access to competitive blocks through the `mev-boost` ecosystem, a major downside of externally built blocks is the fact that the builders ultimately decide what transactions to include or exclude. Without any forced transaction inclusion mechanism, the proposer is faced with a difficult choice: they either have no say on the transactions that get included, or they build the block locally (thus have the final say on transactions) and sacrifice some MEV rewards. + +Inclusion lists aim to allow proposers to retain some authority by providing a mechanism by which transactions can be forcibly included. The simplest design is for the `slot N` proposer to specify a list of transactions that must be included in the block that is produced for their slot. However, this is not incentive-compatible because builders may choose to abstain from building blocks if the proposer sets some constraints on their behavior. This leads to the idea of "forward" inclusion lists, where the transactions specified by the `slot N` proposer are enforced in the `slot N+1` block. The naïve implementation of the forward inclusion lists presents a different issue of potentially exposing free data availability, which could be exploited to bloat the size of the chain without paying the requisite gas costs. The free data availability problem is solved with observations about nonce reuse and allowing multiple inclusion lists to be specified for each slot. With the incentive compatibility and free data availability problems addressed, we can more safely proceed with the implementation of inclusion lists. + +## Specification + +### Constants + +| Name | Value | +| - | - | +| `MAX_TRANSACTIONS_PER_INCLUSION_LIST` | `2**4 = 16` | +| `MAX_GAS_PER_INCLUSION_LIST` | `2**21` | +| `MIN_SLOTS_FOR_INCLUSION_LIST_REQUEST` | `1` | + +#### Reference Objects + +``` +class InclusionListSummaryEntry(Container): + address: ExecutionAddress + gas_limit: uint64 +``` + +``` +class InclusionListSummary(Container) + slot: Slot + proposer_index: ValidatorIndex + summary: List[InclusionListSummaryEntry, MAX_TRANSACTIONS_PER_INCLUSION_LIST] +``` + +``` +class SignedInclusionListSummary(Container): + message: InclusionListSummary + signature: BLSSignature +``` + +``` +class InclusionList(Container) + summary: SignedInclusionListSummary + transactions: List[Transaction, MAX_TRANSACTIONS_PER_INCLUSION_LIST] +``` + +``` +class ExecutionPayload(Container): + ... + inclusion_list_summary: List[InclusionListSummaryEntry, MAX_TRANSACTIONS_PER_INCLUSION_LIST] + inclusion_list_exclusions: List[uint64, MAX_TRANSACTIONS_PER_INCLUSION_LIST] +``` + +``` +class ExecutionPayloadHeader(Container): + ... + inclusion_list_summary_root: Root + inclusion_list_exclusions_root: Root +``` + +``` +class BeaconBlockBody(Container): + ... + inclusion_list_summary: SignedInclusionListSummary +``` + +### Consensus layer + +#### High-level overview + +**`slot N` proposal:** + +- Proposer broadcasts a signed block and an inclusion list (summary and transactions objects) for `slot N+1`. +- Transactions will be included in `slot N` or `slot N+1`. +- Summaries include the originating address of the transactions and their respective gas limits. +- Summaries are signed, but transactions are not. + +**`slot N` validation:** + +- Validators only consider the block for validation and fork-choice if they have seen at least one inclusion list for that slot. +- They consider the block invalid if the inclusion list transactions are not executable at the start of `slot N` or if the transactions' `maxFeePerGas` are not at least 12.5% higher than the current slot (to ensure the transactions will be valid in `slot N+1`). + +**`slot N+1` validation:** + +- The proposer for `slot N+1` builds their block along with a signed summary from the `slot N` proposer. +- The payload includes a list of transaction indices from the `slot N` payload that satisfy some entry in the signed inclusion list summary. +- The payload is considered valid if: (a) the execution conditions are met, including satisfying the inclusion list summary and being executable from the execution layer perspective, and (b) the consensus conditions are met with a proposer signature of the previous block. + +#### Specific Changes + +**Beacon chain state transition spec:** + +- ***New** `inclusion_list` object:* Introduce a new `inclusion_list` for the proposer to submit and nodes to process. +- ***Modified** `ExecutionPayload` and `ExecutionPayloadHeader` objects:* Update these objects to meet the inclusion list requirements. +- ***Modified** `BeaconBlockBody`:* Modified to cache the inclusion list summary. +- ***Modified** `process_execution_payload` function:* Update this process to include checks for the inclusion list summary satisfaction. + +**Beacon chain fork-choice spec:** + +- ***New** `is_inclusion_list_available` check:* Introduce a new check to determine if the inclusion list is available within the visibility window. +- ***New** notification action:* Implement a new call to notify the Execution Layer (EL) client about a new inclusion list. The corresponding block is considered invalid if the EL client deems the inclusion list invalid. + +**Beacon chain P2P spec:** + +- ***New** gossipnet and validation rules for inclusion list:* Define new rules for handling the inclusion list in the gossip network and validation. +- ***New** RPC request and response network for inclusion list:* Establish a new network for sending and receiving inclusion lists. + + +**Validator spec:** + +- ***New** duty for `inclusion_list`:* Proposer to prepare and sign the inclusion list. +- ***Modified** duty for `BeaconBlockBody`:* Update the duty to prepare the beacon block body to include the `inclusion_list_summary`. + +### Execution layer + +- ***New** `get_inclusion_list`:* Introduce a new function for proposers to retrieve inclusion lists. +- ***New** `new_inclusion_list`:* Define a new function for nodes to validate the execution side of the inclusion list. +- ***Modified** `forkchoice_updated`:* Update the function with a `payload_attribute` to include the inclusion list summary as part of the attribute. +- ***Modified** `new_payload`:* Update the function for EL clients to verify that `payload_transactions` satisfy `payload.inclusion_list_summary` and `payload.inclusion_list_exclusions`. +- ***New** validation rules:* Implement new validation rules based on the changes introduced in the Execution-API spec. + +## Rationale + +We consider a few design decisions present in this EIP. + +1. `ReducedSummary` versus `Summary` + - The original proposal tries to improve data efficiency by using a `ReducedSummary` and a `Rebuilder`. This allows the full summary to be reconstructed. + - This adds a lot of complexity to the spec, so in this initial version, we should consider just using the regular `Summary` and including that in the subsequent block. +3. Gas limit vs no limit. + - One consideration is whether the inclusion list should have a gas limit or use the block’s gas limit. + - Having a separate gas limit simplifies complexity but opens up the possibility for validators to outsource their inclusion list construction for side payments (e.g., if a block is full, the proposer could auction off space in the inclusion list for guaranteed inclusion in the subsequent block). + - Alternatively, inclusion lists could be part of the block gas limit and only satisfied if the block gas limit is not full. However, this could lead to situations where the next block proposer intentionally fills up the block to ignore the inclusion list, albeit at the potential expense of paying to waste the gas. +4. Inclusion list ordering. + - We assume that the inclusion list is processed at the top of the `slot N` block. Transactions in the inclusion list are evaluated for the pre-state of `slot N` but are only guaranteed to be included in `slot N+1`. +3. Inclusion list transaction exclusion. + - Inclusion list transactions proposed at `slot N` may be satisfied in the same slot (e.g., by being included in the `ExecutionPayload`). This is a side effect of validators using `mev-boost` because they don’t know the contents of the block they propose. + - Due to this, there exists an exclusion field, a node looks at each transaction in the payload’s `inclusion_list_exclusion` field and makes sure it matches with a transaction in the current inclusion list. When there’s a match, we remove that transaction from the inclusion list summary. +4. `mev-boost` compatibility. + - There are no significant changes to `mev-boost`. Like any other hard fork, `mev-boost`, relays, and builders must adjust their beacon nodes. + - Builders must know that execution payloads that don’t satisfy the inclusion list summary will be invalid. + - Relays may have additional duties to verify such constraints before passing them to validators for signing. + - When receiving the header, validators can check that the `inclusion_list_summary_root` matches their local version and skip building a block if there’s a mismatch, using the local block instead. +5. Syncing using by range or by root. + - To consider a block valid, a node syncing to the latest head must also have an inclusion list. + - A block without an inclusion list cannot be processed during syncing. + - To address this, there is a parameter called `MIN_SLOTS_FOR_INCLUSION_LIST_REQUEST`. A node can skip inclusion list checks if the block’s slot plus this parameter is lower than the current slot. + - This is similar to [EIP-4844](./eip-4844.md), where a node skips blob sidecar data availability checks if it’s outside the retention window. + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. These changes do not break anything related to current user activity and experience. + +## Security Considerations + +The main potential issue is around the incentivization of the inclusion lists. If the `slot N` proposer constructs an inclusion list that negatively impacts the rewards of the `slot N+1` proposer, the `slot N+1` proposer may attempt to bribe the `slot N` proposer to publish an empty list. This isn't a direct attack on the protocol, but rather a profit-sharing mechanism by which the inclusion list would go unutilized. It seems likely these commitment games could be played no matter the censorship resistance scheme in place, but this remains an active area of research. + + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7549.md b/EIPS/eip-7549.md new file mode 100644 index 00000000000000..113495ba80a5f3 --- /dev/null +++ b/EIPS/eip-7549.md @@ -0,0 +1,89 @@ +--- +eip: 7549 +title: Move committee index outside Attestation +description: Move committee index outside of the signed Attestation message +author: dapplion (@dapplion) +discussions-to: https://ethereum-magicians.org/t/eip-7549-move-committee-index-outside-attestation/16390 +status: Review +type: Standards Track +category: Core +created: 2023-11-01 +--- + +## Abstract + +Move the committee `index` field outside of the signed Attestation message to allow aggregation of equal consensus votes. + +## Motivation + +This proposal aims to make Casper FFG clients more efficient by reducing the average number of pairings needed to verify consensus rules. While all types of clients can benefit from this EIP, ZK circuits proving Casper FFG consensus are likely to have the most impact. + +On a beacon chain network with at least 262144 active indexes it's necessary to verify a minimum of `ceil(32*64 * 2/3) = 1366` attestations to reach a 2/3 threshold. Participants cast two votes at once: LMD GHOST vote and Casper-FFG vote. However, the Attestation message contains three elements: + +1. LMD GHOST vote `(beacon_block_root, slot)`. Note: includes slot in the event (block, slot) voting is adopted. +2. FFG vote `(source, target)` +3. Committee index `(index)` + +Signing over the 3rd item causes tuples of equal votes to produce different signing roots. If the committee index is moved outside of the Attestation message the minimum number of attestations to verify to reach a 2/3 threshold is reduced to `ceil(32 * 2/3) = 22` (a factor of 62). + +On-chain attestations can now be packed more space-efficiently into beacon blocks. This proposal allows to include up to 8 slots worth of votes into a block, compared to 2 today. In order words, a chain with only 1/8 online proposers can still potentially include all votes on-chain. + +## Specification + +### Execution layer + +This requires no changes to the Execution Layer. + +### Consensus layer + +- Set `index` field from `AttestationData` to fixed value of zero +- Move committee indexing data to the outter `Attestation` container with `committee_bits` +- Increase the capacity of `aggregation_bits` to all committees in a slot + +The full specification of the proposed change can be found in [`/specs/electra/beacon-chain.md`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md). + +## Rationale + +### Deprecation strategy + +The `index` field in `AttestationData` can be deprecated by: + +1. Removing the field +2. Preserving the field and setting it to be zero +3. Changing the field type to Optional (from [EIP-7495](./eip-7495.md) StableContainer) + +This EIP chooses the second option to not complicate the inclusion of `AttesterSlashing` objects. While the `Attestation` container changes, `AttesterSlashing` includes indexed attestations without committee data. + +### `MAX_ATTESTATIONS` value + +The maximum size of an attestation increases, with a bitfield 64 times larger on networks with maxed committees. `MAX_ATTESTATIONS` value is reduced to limit the beacon block size while still increase the total capacity of votes. A value of 8 increase the vote capacity by 4 while having the same attestation space size with a network of 1.2M active indices. + +### `MAX_ATTESTER_SLASHINGS` value + +On-chain `AttesterSlashing` includes a list of indices of all participants. With this EIP the worst-case size increases by 64 times, resulting in an uncompressed size of 488 KB per `AttesterSlashing` in a network of 1M validators. Snappy compression reduces it to 320 KB, which is still significant. To bound the maximum size of block this proposal reduces `MAX_ATTESTER_SLASHINGS` from 2 to 1, the minimum value. + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the consensus layer and must be accompanied by a hard fork. + +## Security Considerations + +### First block after fork + +Because the on chain `Attestation` container changes, attestations from the prior fork can't be included into post-electra blocks. Therefore the first block after the fork may have zero attestations. LMD votes can still be applied to fork-choice via on_attestation handler, so there will be only a 1/32 loss of FFG votes. Attesters assigned to the last slot of the fork will incur one epoch worth of offline penalties. One possible mitigation is to change the electra block body type to allow including attestations from both forks. However, the mitigation increases complexity for little gain so this proposal choses to not address the issue. + +### Mutation over gossip + +Moving the `index` field outside of the signed message allows malicious mutation only on the p2p gossip topic `beacon_attestation_${subnet_id}`. Everywhere else, the `Attestation` message is wrapped with an outer signature that prevents mutation. + +Gossip verification rules for the `beacon_attestation_${subnet_id}` topic include: + +> - [IGNORE] There has been no other valid attestation seen on an attestation subnet that has an identical attestation.data.target.epoch and participating validator index. +> - [REJECT] The signature of attestation is valid. + +For an unaggregated attestation, the tuple (slot, index, aggregation_bits) uniquely identifies a single public key. Thus there is a single correct value for the field `index`. If an attacker mutates the `index` field the signature will fail to verify and the message will be dropped. This is the same outcome of mutating the aggregation bits, which is possible today. If implementations verify the attestation signature before registering it in a 'first-seen' cache, there's no risk of cache pollution. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-7568.md b/EIPS/eip-7568.md new file mode 100644 index 00000000000000..158dcb2111cf01 --- /dev/null +++ b/EIPS/eip-7568.md @@ -0,0 +1,92 @@ +--- +eip: 7568 +title: Hardfork Meta Backfill - Berlin to Shapella +description: Pointers to specifications used for the network upgrades from Berlin to Shapella. +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/hardfork-meta-backfill/16923 +status: Final +type: Meta +created: 2023-12-01 +requires: 2070, 2387, 2982, 6122, 6953 +--- + +## Abstract + +Following Muir Glacier hard fork, Meta EIPs were abandoned in favor of other ways to track changes included in Ethereum network upgrades. This EIP aggregates the specifications for these upgrades, which themselves list the specific changes included. Specifically, it covers the Beacon Chain launch (Serenity Phase 0), Berlin, London, Altair, Arrow Glacier, Gray Glacier, The Merge (Paris + Bellatrix) and Shapella (Shanghai + Capella). + +## Motivation + +For many years, Ethereum used Meta EIPs to document network upgrades. Recently, consensus has formed around using them again. This EIP aggregates the network upgrades who did not have Meta EIPs and links out to their specifications. + +## Specification + +The network upgrades below are listed in order of activation. Upgrades to Ethereum's execution layer are marked "[EL]", and those to Ethereum's consensus layer are marked "[CL]". + +### Beacon Chain Launch - Serenity Phase 0 [CL] + +The full specifications for the Beacon Chain at launch can be found in the [`v1.0.0` release of the `ethereum/consensus-specs` repository](https://github.com/ethereum/consensus-specs/blob/579da6d2dc734b269dbf67aa1004b54bb9449784/README.md#phase-0). Additionally, [EIP-2982](./eip-2982.md) provides context on the Beacon Chain design and rationale for its mainnet parametrization. + +### Berlin [EL] + +The set of EIPs included in Berlin were originally specified in [EIP-2070](./eip-6953.md), but then moved to the [`berlin.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/berlin.md) file of the `ethereum/execution-specs` repository. + +### London [EL] + +The set of EIPs included in London are specified in the [`london.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/london.md) file of the `ethereum/execution-specs` repository. + +### Altair [CL] + +The full specifications for the Altair network upgrade can be found in the [`v1.1.0` release of the `ethereum/consensus-specs` repository](https://github.com/ethereum/consensus-specs/blob/67fd7979ffd705bd6b0b5c1aaa842a445cc74d9a/README.md#altair). + +### Arrow Glacier [EL] + +The set of EIPs included in Arrow Glacier are specified in the[`arrow-glacier.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/arrow-glacier.md) file of the `ethereum/execution-specs` repository. + +### Gray Glacier [EL] + +The set of EIPs included in Gray Glacier are specified in the[`gray-glacier.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/gray-glacier.md) file of the `ethereum/execution-specs` repository. + +### The Merge + +The Merge was the first upgrade to require coordination between the execution and consensus layers. The consensus layer first activated the Bellatrix upgrade, which was followed by the activation of Paris on the execution layer. + +#### Bellatrix [CL] + +The full specifications for the Bellatrix network upgrade can be found in the [`v1.2.0` release of the `ethereum/consensus-specs` repository](https://github.com/ethereum/consensus-specs/blob/f8ae982c2fc7dbb03a3c95a638da4486310e09e9/README.md#stable-specifications). + +#### Paris [EL] + +The set of EIPs included in Paris are specified in the [`paris.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/paris.md) file of the `ethereum/execution-specs` repository. + +### Shapella + +The Shapella upgrade was the first upgrade to activate at the same time on both the execution and consensus layers. To enable this, the upgrade activation mechanism on the execution layer was changed to use timestamps instead of blocks. This is described in [EIP-6953](./eip-6953.md) and [EIP-6122](./eip-6122.md). + +#### Shanghai [EL] + +The set of EIPs included in Shanghai are specified in the[`shanghai.md`](https://github.com/ethereum/execution-specs/blob/8dbde99b132ff8d8fcc9cfb015a9947ccc8b12d6/network-upgrades/mainnet-upgrades/shanghai.md) file of the `ethereum/execution-specs` repository. + +#### Capella [CL] + +The full specifications for the Capella network upgrade can be found in the [`v1.3.0` release of the `ethereum/consensus-specs` repository](https://github.com/ethereum/consensus-specs/blob/01b53691dcc36d37a5ad8994b3a32d8de69fb1aa/README.md#stable-specifications). + + +## Rationale + +The EIP repository is well known within the Ethereum community, and Meta EIPs have historically been useful to clearly list the EIPs included in a specific network upgrade. + +While the specification process for the execution and consensus layers differ, there is value in having a single, harmonized, list of EIPs included in each upgrade, and for the lists for both layers to be part of the same repository. + +Re-introducing Hardfork Meta EIPs enables this, and allows for de-duplication in cases where an EIP affects both the execution and consensus layer of Ethereum. This EIP covers the upgrades which did not use a Hardfork Meta EIP. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7569.md b/EIPS/eip-7569.md new file mode 100644 index 00000000000000..8d3f70980d933a --- /dev/null +++ b/EIPS/eip-7569.md @@ -0,0 +1,62 @@ +--- +eip: 7569 +title: Hardfork Meta - Dencun +description: EIPs included in the Deneb/Cancun Ethereum network upgrade. +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/dencun-hardfork-meta/16924 +status: Final +type: Meta +created: 2023-12-01 +requires: 1153, 4788, 4844, 5656, 6780, 7044, 7045, 7514, 7516, 7568 +--- + +## Abstract + +This Meta EIP lists the EIPs included in the Dencun network upgrade across both Ethereum's execution and consensus layers. + +## Specification + +### Included EIPs + +* [EIP-1153](./eip-1153.md): Transient storage opcodes +* [EIP-4788](./eip-4788.md): Beacon block root in the EVM +* [EIP-4844](./eip-4844.md): Shard Blob Transactions +* [EIP-5656](./eip-5656.md): MCOPY - Memory copying instruction +* [EIP-6780](./eip-6780.md): SELFDESTRUCT only in same transaction +* [EIP-7044](./eip-7044.md): Perpetually Valid Signed Voluntary Exits +* [EIP-7045](./eip-7045.md): Increase Max Attestation Inclusion Slot +* [EIP-7514](./eip-7514.md): Add Max Epoch Churn Limit +* [EIP-7516](./eip-7516.md): BLOBBASEFEE opcode + +### Full Specifications + +#### Consensus Layer + +EIPs 4788, 4844, 7044, 7045 and 7514 require changes to Ethereum's consensus layer. These are specified in the `deneb` folder of the `ethereum/consensus-specs` repository. + +#### Execution Layer + +EIPs 1153, 4788, 4844, 5656, 6780 and 7516 require changes to Ethereum's execution layer. The EIPs fully specify the changes. + +### Activation + +| Network Name | Activation Epoch | Activation Timestamp | +|------------------|------------------|----------------------| +| Goerli | `231680` | `1705473120` | +| Sepolia | `132608` | `1706655072` | +| Holešky | `29696` | `1707305664` | +| Mainnet | `269568` | `1710338135` | + +**Note**: rows in the table above will be filled as activation times are decided by client teams. + +## Rationale + +This Meta EIP provides a global view of all changes included in the Dencun network upgrade, as well as links to full specification. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7577.md b/EIPS/eip-7577.md new file mode 100644 index 00000000000000..8997b74a12babc --- /dev/null +++ b/EIPS/eip-7577.md @@ -0,0 +1,110 @@ +--- +eip: 7577 +title: Versioning Scheme for EIPs +description: Use a versioning scheme for EIPs based on changes made to their Specification section. +author: danceratopz (@danceratopz), Ahmad Bitar (@smartprogrammer93) +discussions-to: https://ethereum-magicians.org/t/add-eip-versioning-scheme-for-eips/17295 +status: Draft +type: Meta +created: 2023-12-13 +--- + +## Abstract + +This EIP introduces a versioning scheme for [Standards Track](./eip-1.md#eip-types) EIPs by applying [Semantic Versioning 2.0.0](../assets/eip-7577/semver.md) based on changes made to the EIP's Specification section once its status has changed from `Draft` to `Review`. + +## Motivation + +EIP specifications often receive increasing modifications as more people review them, which is generally the case as client teams start implementing the specifications and the community gains a better understanding of their interaction with the rest of the protocol. These changes can be difficult to track. In particular, as EVM reference tests are often not maintained (and generally not released) by client teams or the EIP's authors, it can be difficult to ascertain whether a release of reference tests is sufficient, or even valid, to test the latest version of an EIP's specifications or the specification as currently implemented by a client. + +This EIP proposes a semantic versioning scheme and an addition of a CHANGELOG section for EIPs that enables clearer communication within the community and allows the scope of a change to be ascertained at first glance. Furthermore, client implementation and testing toolchains can query EIP changes and automatically flag incompatibilities between the EIP's current specification and between client and test implementations. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Once an EIP has moved out of "Draft" status, it MUST use the EIP versioning scheme outlined below. It MAY already use the versioning scheme in "Draft" status, which could be useful if the specification is actively being implemented. If more than one team is implementing the specification, it is RECOMMENDED to change the EIP's status to "Review". + +The EIP versioning scheme MUST apply the following semantic versioning scheme of `MAJOR.MINOR.PATCH`, based on [Semantic Versioning 2.0.0](../assets/eip-7577/semver.md): + +1. `MAJOR`: A breaking change to the specifications that requires an implementation change and a change to the reference tests. +2. `MINOR`: An addition to the specifications that requires additional implementation and additional test coverage to be added to the reference tests. +3. `PATCH`: Any cosmetic change to, or a reformulation of, the EIP without specification change. + +Before the EIP has moved out of Draft status and is being versioned, the version number MUST initially have `MAJOR` version `0`. + +For every change made to an EIP via a pull request (PR) made to ethereum/EIPs, a new entry MUST be added to the CHANGELOG section of the EIP that outlines the changes made within the PR. This CHANGELOG entry MUST include the following: + +1. A new version number that follows the semantic versioning scheme outlined above. +2. The date when the changes where introduced. +3. The ethereum/EIPs PR number that implements the changes. +4. A line for each change made to the EIP's specifications that includes a short description of the change. + +Additionally, the new version MUST be added to the metadata header of the EIP's markdown file (to a new "version" field), so that it may be easily parsed. + +Tooling MUST be added to the ethereum/EIPs repository to help EIP authors apply the versioning scheme. This tooling SHOULD automatically: + +1. Update the EIP version in the metadata header of the EIP's markdown file. If the EIP's status is changed from "Draft" to "Review", the version MUST be updated to `1.0.0`. +2. Add a new CHANGELOG entry based on the EIP Version and the PR's title. + +To allow the tooling to make these changes, the EIP author MUST indicate the scope of change in one of the commit messages pushed to the PR's branch. The scope is indicated by starting a commit message with ("`[Mm]ajor:`", "`[Mm]inor:`", or "`[Pp]atch`"). Multiple commit messages may contain scopes; in this case, the most severe scope change will be applied. If no scope can be detected in any of the commit messages, merging of the PR is blocked until such a commit message is pushed to the PR. + +## Rationale + +Making the version available in the EIP's metadata header allows for programmatic parsing of the version number by tooling used in reference tests or by client teams. Currently, the execution-spec-tests repository, which contains consensus tests for Ethereum execution clients, implements a rudimentary EIP version checker: EIP spec tests are required to declare the EIP's markdown file digest SHA that the test implementation was based on. The current value of the digest SHA is then polled via the Github API to verify that no changes have occurred since the test implementation. While this provides a warning to test implementers that the EIP has changed, it is clearly of limited use. + +A richer versioning scheme, as defined by this EIP, can provide a lot of value to the testing toolchain. Client teams can provide an interface that reports the EIP version currently implemented and reference tests can specify the version they implement in generated tests as metadata. This allows a test runner to mark tests to xfail (expectedly fail) and issue a warning if the `MAJOR` or `MINOR` versions don't match. It would even be possible to automatically select the correct version of the reference tests to run against a client implementation, although given the pace of Ethereum development, it will likely be impractical to maintain and track multiple versions of tests. + +### Case Study + +This section explores how the versioning scheme would be applied to an existing EIPs recently under active development at the time of writing as an example. + +The history of [EIP-4788](./eip-4788.md) contains many changes to its specification. EIP-4788 was updated to status "Review" on 2023-11-28. This case study assumes, however, that the EIP moved to status "Review" as of 2023-04-11 and updated to version 1.0.0 due to the start of a client team implementation. + +#### Changelog + +- 9.0.1 - 2023-09-26: Update ring buffer size rationale for new ring buffer size, #7786. +- 9.0.0 - 2023-09-26: Post audit tweaks, #7672. + - Verify timestamp is non-zero. + - Make `HISTORY_BUFFER_LENGTH` prime (8191). + - Load calldata once. + - Update `BEACON_ROOTS_ADDRESS`. +- 8.0.1 - 2023-08-28: 4788 cleanups, #7532. +- 8.0.0 - 2023-08-24: Initial stab at v2, #7456. + - Require timestamp input to be exactly 32 bytes. + - Revert if timestamp input does not match stored value (instead of returning zeroed word). + - Remove precompile concept, use regular smart contract with provided bytecode. +- 7.0.3 - 2023-08-01: Mention genesis block with no existing beacon block root case, #7445. +- 7.0.2 - 2023-07-07: Explicitly specify header schema, #7297. +- 7.0.1 - 2023-07-07: Fix typo, #7293. +- 7.0.0 - 2023-07-05: Bound precompile storage, #7178. +- 6.0.1 - 2023-06-13: Clarify header and validity sections, #7179. +- 6.0.0 - 2023-06-12: Update precompile address, #7173. +- 5.0.0 - 2023-05-31: Key beacon roots by root, #7107. +- 4.0.0 - 2023-05-24: Favor stateful precompile over opcode, #7065. +- 3.0.0 - 2023-05-17: Send current slot from CL to avoid timestamp conversions, #7037. +- 2.0.1 - 2023-05-15: Fix typo, #7005. +- 2.0.0 - 2023-05-03: Update opcode to avoid clash, #6980. +- 1.0.1 - 2023-04-13: Minor nits, #6870. +- 1.0.0 - 2023-04-11: Use block roots; update to status "Draft", #6859. + - Update to "Draft" due to client implementation (NethermindEth/nethermind#5476). + - Use block roots instead of state roots. + - Roots are stored keyed by slot. + - Use of ring buffer in state. + - Use header timestamps to derive slot numbers, rather than consume additional header space. +- 0.2.1 - 2023-02-04: Update to status "Stagnant", #6432. +- 0.2.0 - 2022-06-29: Rename "beacon block root" to "beacon state root", #5090. +- 0.1.1 - 2022-05-06: Force usage of included LICENSE file, #5055. +- 0.1.0 - 2022-02-17: Add EIP-4788: Beacon state root in EVM, #4788. + +## Backwards Compatibility + +It is not necessary to retroactively add a CHANGELOG or versions for versions of the EIP prior to the introduction of this EIP. Upon the next change to the EIP's Specification section, the author MUST introduce a CHANGELOG section and a version number that follows the semantic versioning scheme outlined above. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7587.md b/EIPS/eip-7587.md new file mode 100644 index 00000000000000..0fb926760da103 --- /dev/null +++ b/EIPS/eip-7587.md @@ -0,0 +1,39 @@ +--- +eip: 7587 +title: Reserve Precompile Address Range for RIPs +description: Reserve precompile address range for use by the RIP process +author: Carl Beekhuizen (@carlbeek), Ansgar Dietrichs (@adietrichs), Danny Ryan (@djrtwo), Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-75xx-reserve-precompile-address-range-for-rips-l2s/17828 +status: Last Call +last-call-deadline: 2024-04-25 +type: Meta +created: 2023-12-21 +--- + +## Abstract + +This EIP reserves precompile ranges to ensure there are no conflicts with those used by the Rollup Improvement Proposal (RIP) process. + +## Motivation + +As L2s begin to deploy RIPs, it is necessary to reserve an address range for use by the RIP process so as to ensure there are no conflicts between precompile addresses used by RIPs and EIPs. + +## Specification + +The address range between `0x0000000000000000000000000000000000000100` and `0x00000000000000000000000000000000000001ff` is reserved for use by the RIP process. + +## Rationale + +By reserving an address range for RIPs, it allows the RIP process to maintain its own registry of precompiles that are not (necessarily) deployed on L1 mainnet, the EIP process is freed from having to maintain a registry of RIP precompiles while still having 255 addresses for its own use. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +Nil. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7591.md b/EIPS/eip-7591.md new file mode 100644 index 00000000000000..d688c489a8e2e0 --- /dev/null +++ b/EIPS/eip-7591.md @@ -0,0 +1,116 @@ +--- +eip: 7591 +title: BLS signed transactions +description: Introduces a new transaction type signed with BLS signatures +author: Marius van der Wijden (@MariusVanDerWijden) +discussions-to: https://ethereum-magicians.org/t/eip-7591-bls-signed-transactions/19911 +status: Draft +type: Standards Track +category: Core +created: 2024-01-10 +--- + +## Abstract + +This EIP introduces a new [EIP-2718](./eip-2718.md) transaction type that is signed with BLS signatures. + +## Motivation + +The BLS signature scheme allows for easy aggregation and verification of aggregated signatures. +If a substantial number of transactions on mainnet were BLS signed transactions, we can aggregate signatures in a block and batch-verify them. +This will reduce growth of the chain history. + + +## Specification + +BLS_TX_TYPE = Bytes1(0x04) + +### Transaction Type + +The transaction type will have the following format: + +``` +[chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, sender, signature] +``` + +with `sender` being the BLS public key of an account with address `address = [0:20](keccak256(sender))`. + +The signature value `signature` is calculated by constructing a BLS signature over the following digest: + +`tx_hash = keccak256(BLS_TX_TYPE || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, sender]))`. + +### Header changes + +The block header will be amended with the `aggregated_sig` field, containing an aggregated signature of all BLS transactions in the block. + +The resulting RLP encoding of the header is therefore: + +``` +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + gas_limit, + gas_used, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + base_fee_per_gas, + withdrawals_root, + blob_gas_used, + excess_blob_gas, + aggregated_sig, +]) +``` + +### Block changes + +The block building algorithm needs to be changed in order to built the aggregated signature of all BLS signed transactions in the block. +All transactions in the block will be added without the signature field set. + +Blocks with transactions containing the `signature` field MUST be rejected. + +On block verification, the `verifyAggregate` algorithm is used as follows: + +``` +valid = verifyAggregate(sender_1, ... sender_n, tx_hash_1, ... tx_hash_n, aggregated_sig) +``` + +## Rationale + +Removing the ECDSA signature from a transaction saves 65 bytes. The BLS public key is 48 bytes, the aggregated signature is 96 bytes. +Thus we save `-96 + (65-48)* #transactions` bytes per block. With ~7000 blocks per day, 1.000.000 transactions per day, the average block contains roughly 150 transactions. + +Thus we would save 2454 bytes or 2.4KB per block. This would equate to ~1.5% saving given an average block size of 160KB. + +In addition to the (admittedly meager) size savings for full nodes, the ability to add a new transaction type to utilize a different signature scheme does have some merit to it. This proposal shows that it would be possible to add for example a quantum safe signature scheme to ethereum. + +## Backwards Compatibility + +This EIP introduces backward incompatible changes to the block validation rule set on the execution layer and introduces a new transaction type and a new header field. Thus a hardfork is needed. + +## Security Considerations + +The messages signed via BLS are distinct (no hash collisions on the txhash), thus the aggregation is secure even without a proof-of-possession. +The public keys are not distinct which is not a problem in BLS. + +We assume that keccak256 and ECDSA and BLS are working as intended. +Suppose we have two addresses `address_1 = keccak256(pk_ecdsa)` and `address_2 = keccak(pk_bls)` with `address_1 == address_2`. +We know that `pk_ecdsa` must be equal to `pk_bls` (follows from keccak). +This would mean that we would either be able to find `x` with `g_bls^x = y` for a given `y` (violates the security of BLS) +or find `z` with `d_ecdsa^z = y` (violates the security of ECDSA). + +Thus it would be impossible (with greater than negligble probability) to find two private keys, one in ECDSA and one in BLS that control the same account. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + + diff --git a/EIPS/eip-7594.md b/EIPS/eip-7594.md new file mode 100644 index 00000000000000..3d9747d143e688 --- /dev/null +++ b/EIPS/eip-7594.md @@ -0,0 +1,52 @@ +--- +eip: 7594 +title: PeerDAS - Peer Data Availability Sampling +description: Introducing simple DAS utilizing gossip distribution and peer requests +author: Danny Ryan (@djrtwo), Dankrad Feist (@dankrad), Francesco D'Amato (@fradamt), Hsiao-Wei Wang (@hwwhww) +discussions-to: https://ethereum-magicians.org/t/eip-7594-peerdas-peer-data-availability-sampling/18215 +status: Review +type: Standards Track +category: Networking +created: 2024-01-12 +requires: 4844 +--- + +## Abstract + +PeerDAS (Peer Data Availability Sampling) is a networking protocol that allows beacon nodes to perform data availability sampling (DAS) to ensure that blob data has been made available while downloading only a subset of the data. PeerDAS utilizes gossip for distribution, discovery for finding peers of particular data custody, and peer requests for sampling. + +## Motivation + +DAS is a method of scaling data availability beyond the levels of [EIP-4844](./eip-4844.md) by not requiring all nodes to download all data while still ensuring that all of the data has been made available. + +Providing additional data availability helps bring scale to Ethereum users in the context of layer 2 systems called "roll-ups" whose dominant bottleneck is layer 1 data availability. + +## Specification + +We extend the blobs introduced in EIP-4844 using a one-dimensional erasure coding extension. Each row consists of the blob data combined with its erasure code. It is subdivided into cells, which are the smallest units that can be authenticated with their respective blob's KZG commitments. Each column, associated with a specific gossip subnet, consists of the cells from all rows for a specific index. Each node is responsible for maintaining and custodying a deterministic set of column subnets and data as a function of their node ID. + +Nodes find and maintain a diverse peer set and sample columns from their peers to perform DAS every slot. + +A node can reconstruct the entire data matrix if it acquires at least 50% of all the columns. If a node has less than 50%, it can request the necessary columns from the peer nodes. + +The detailed specifications are on [ethereum/consensus-specs](https://github.com/ethereum/consensus-specs/blob/b4188829b32139916127827c64ba17c923e66c3c/specs/_features/eip7594/das-core.md). + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +## Rationale + +TBD + +## Backwards Compatibility + +## Test Cases + +## Reference Implementation + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7600.md b/EIPS/eip-7600.md new file mode 100644 index 00000000000000..9ae35add3edddb --- /dev/null +++ b/EIPS/eip-7600.md @@ -0,0 +1,79 @@ +--- +eip: 7600 +title: Hardfork Meta - Pectra +description: EIPs included in the Prague/Electra Ethereum network upgrade. +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-7600-hardfork-meta-prague-electra/18205 +status: Review +type: Meta +created: 2024-01-18 +requires: 2537, 2935, 6110, 7002, 7251, 7549, 7594, 7685, 7692, 7702 +--- + +## Abstract + +This Meta EIP lists the EIPs formally considered for and included in the Prague/Electra network upgrade. + +## Specification + +### EIPs Included + +* [EIP-2537](./eip-2537.md): Precompile for BLS12-381 curve operations +* [EIP-2935](./eip-2935.md): Save historical block hashes in state +* [EIP-6110](./eip-6110.md): Supply validator deposits on chain +* [EIP-7002](./eip-7002.md): Execution layer triggerable exits +* [EIP-7251](./eip-7251.md): Increase the MAX_EFFECTIVE_BALANCE +* [EIP-7549](./eip-7549.md): Move committee index outside Attestation +* [EIP-7594](./eip-7594.md): PeerDAS - Peer Data Availability Sampling +* [EIP-7685](./eip-7685.md): General purpose execution layer requests +* [EIP-7702](./eip-7702.md): Set EOA account code for one transaction +* EOF EIPs listed as part of [EIP-7692](./eip-7692.md), namely: + * [EIP-663](./eip-663.md): SWAPN, DUPN and EXCHANGE instructions + * [EIP-3540](./eip-3540.md): EOF - EVM Object Format v1 + * [EIP-3670](./eip-3670.md): EOF - Code Validation + * [EIP-4200](./eip-4200.md): EOF - Static relative jumps + * [EIP-4750](./eip-4750.md): EOF - Functions + * [EIP-5450](./eip-5450.md): EOF - Stack Validation + * [EIP-6206](./eip-6206.md): EOF - JUMPF and non-returning functions + * [EIP-7069](./eip-7069.md): Revamped CALL instructions + * [EIP-7480](./eip-7480.md): EOF - Data section access instructions + * [EIP-7620](./eip-7620.md): EOF Contract Creation + * [EIP-7698](./eip-7698.md): EOF - Creation transaction + +### EIPs Considered for Inclusion + +* [EIP-7212](./eip-7212.md): Precompile for secp256r1 Curve Support +* [EIP-7547](./eip-7547.md): Inclusion lists +* [EIP-7623](./eip-7623.md): Increase calldata cost + +### Full Specifications + +#### Consensus Layer + +EIP-6110, EIP-7002 EIP-7251, EIP-7549 and EIP-7594 require changes to Ethereum's consensus layer. While the EIPs present an overview of these changes, the full specifications can be found in the `specs/electra` and `specs/_features` directories of the `ethereum/consensus-specs` repository. + +#### Execution Layer + +All EOF EIPs, listed in EIP-7692, as well as EIP-2537, EIP-2935, EIP-6110, EIP-7685, and EIP-7002 require changes to Ethereum's execution layer. The EIPs fully specify those changes. + +### Activation + +| Network Name | Activation Epoch | Activation Timestamp | +|------------------|------------------|----------------------| +| Sepolia | | | +| Holešky | | | +| Mainnet | | | + +**Note**: rows in the table above will be filled as activation times are decided by client teams. + +## Rationale + +This Meta EIP provides a global view of all changes included in the Prague/Electra network upgrade, as well as links to full specification. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7607.md b/EIPS/eip-7607.md new file mode 100644 index 00000000000000..0bfc523f6ea136 --- /dev/null +++ b/EIPS/eip-7607.md @@ -0,0 +1,49 @@ +--- +eip: 7607 +title: Hardfork Meta - Osaka +description: EIPs included in the Osaka Ethereum network upgrade. +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-7607-osaka-meta-eip/18439 +status: Draft +type: Meta +created: 2024-02-01 +requires: 7600 +--- + +## Abstract + +This Meta EIP lists the EIPs formally considered for & included in the Osaka network upgrade. + +## Specification + +### Included EIPs + +### Considered for Inclusion + +* [EIP-4762](./eip-4762.md): Statelessness gas cost changes +* [EIP-6800](./eip-6800.md): Ethereum state using a unified verkle tree +* [EIP-6873](./eip-6873.md): Preimage retention +* [EIP-7545](./eip-7545.md): Verkle proof verification precompile +* [EIP-7667](./eip-7667.md): Raise gas costs of hash functions + +### Activation + +| Network Name | Activation Epoch | Activation Timestamp | +|------------------|------------------|----------------------| +| Sepolia | | | +| Holešky | | | +| Mainnet | | | + +**Note**: rows in the table above will be filled as activation times are decided by client teams. + +## Rationale + +This Meta EIP provides a global view of all changes included in the Osaka network upgrade, as well as links to full specification. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7609.md b/EIPS/eip-7609.md new file mode 100644 index 00000000000000..c5862a9615e1c8 --- /dev/null +++ b/EIPS/eip-7609.md @@ -0,0 +1,82 @@ +--- +eip: 7609 +title: Decrease base cost of TLOAD/TSTORE +description: Improve the efficiency of TLOAD/TSTORE by decreasing the base cost and introducing a superlinear pricing model. +author: Charles Cooper (@charles-cooper), James Prestwich (@prestwich), brockelmore (@brockelmore) +discussions-to: https://ethereum-magicians.org/t/eip-7609-reduce-transient-storage-pricing/18435 +status: Draft +type: Standards Track +category: Core +created: 2024-02-01 +requires: 1153 +--- + +## Abstract + +Decrease the base cost of TLOAD/TSTORE while introducing a superlinear pricing model. This increases the efficiency of TLOAD/TSTORE for common use cases, while providing a pricing model to prevent DoS vectors. + +## Motivation + +[EIP-1153](./eip-1153.md) introduces a new storage region, termed "transient storage". It behaves like storage (word-addressed and persists between call frames), but unlike storage it is wiped at the end of each transaction. During development of EIP-1153, the pricing was set to be the same as warm storage loads and stores. This was for two reasons: conceptual simplicity of the EIP, and it also addressed concerns about two related DoS vectors: being able to allocate too much transient storage, and the cost of rolling back state in the case of reverts. + +One of the most important use cases that EIP-1153 enables is cheap reentrancy protection. In fact, if transient storage is cheap enough for the first few slots, reentrancy protection can be enabled by default at the language level without too much burden to users, while simultaneously preventing the largest—and most expensive—class of smart contract vulnerabilities. + +Furthermore, it seems that transient storage is fundamentally overpriced. Its pricing does not interact with refunds, it only requires a new allocation on contract load (as opposed to memory, which requires a fresh allocation on every call), and has no interaction with the physical database. + +This EIP proposes a pricing model which charges additional gas per allocation, which is cheaper for common cases (fewer than ~95 slots are written per contract), while making DoS using transient storage prohibitively expensive. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +The gas cost for `TLOAD` is proposed to be 5 gas. The gas cost for `TSTORE` is proposed to be 8 gas + `expansion_cost`, where `expansion_cost` is calculated as `1 gas * len(transient storage mapping)` if the key is not yet in the transient storage mapping, and otherwise 0 gas. + +In pseudo-code: + +```python +G_LOW = 5 +G_MID = 8 + +SLOPE = 1 + +def gas_tload(_key): + return G_LOW + +def gas_tstore(key, transient_mapping): + cost = G_MID + if key not in transient_mapping: + cost += SLOPE * transient_mapping.size() + return cost +``` + +## Rationale + +### Gas + +In benchmarking, `TLOAD` was found to cost a similar amount of CPU time as `MUL`, while `TSTORE` was found to cost about 1.5x that. The values `G_low` and `G_mid` were therefore chosen for `TLOAD` and `TSTORE`, respectively. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +The maximum number of transient slots which can be allocated on a single contract given 30m gas is approximately 7,739 (solution to `x(x-1)/2*1 + 8*x = 30_000_000`), which totals 248KB. + +The maximum number of transient slots which can be allocated in a transaction if you use the strategy of calling new contracts (which each are designed to maximize transient storage allocation) once the cost of `TSTORE` is more than the cost of calling a cold contract (2600 gas), can be solved for as follows: + +``` +solve for SLOPE * == 2600, => num_slots == 2600 +gas_used_by_contract = 2600 + SLOPE * num_slots * (num_slots - 1) / 2 + G_MID * num_slots == 3402100 +block_gas_limit = 30_000_000 +num_calls_per_txn = block_gas_limit // gas_used_by_contract ~= 8.8 +max_transient_slots = num_calls_per_txn * num_slots == 22927 +``` + +Thus, the maximum number of transient slots which can be allocated in a single transaction with this method is roughly 23,000, which totals 736KB. Compared to the current gas schedule (which allows allocating approximately `30_000_000 / 100 * 32 == 9.6MB` worth of memory), this is a net *reduction* in the total memory which can be allocated on a client using transient storage, so this EIP presents a stronger bound on the resources which can be used by transient storage. As a comparison point, the total amount of memory which can be allocated on a client by `SSTORE`s in a given transaction is `30_000_000 / 20_000 * 32`, or 48KB. + +Note that this cap scales linearly with the gas limit, which is a useful property when considering future block gas limit increases. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7610.md b/EIPS/eip-7610.md new file mode 100644 index 00000000000000..80ef48d0bbb5a4 --- /dev/null +++ b/EIPS/eip-7610.md @@ -0,0 +1,47 @@ +--- +eip: 7610 +title: Revert creation in case of non-empty storage +description: Revert contract creation if address already has the non-empty storage +author: Gary Rong (@rjl493456442), Martin Holst Swende (@holiman) +discussions-to: https://ethereum-magicians.org/t/eip-revert-creation-in-case-of-non-empty-storage/18452 +status: Draft +type: Standards Track +category: Core +created: 2024-02-02 +--- + +## Abstract + +This EIP causes contract creation to throw an error when attempted at an address with pre-existing storage. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +If a contract creation is attempted due to a creation transaction, the `CREATE` opcode, the `CREATE2` opcode, or any other reason, and the destination address already has either a nonzero nonce, a nonzero code length, or non-empty storage, then the creation MUST throw as if the first byte in the init code were an invalid opcode. This change MUST apply retroactively for all existing blocks. + +This EIP amends [EIP-684](./eip-684.md) with one extra condition, requiring empty storage for contract deployment. + +## Rationale + +EIP-684 defines two conditions for contract deployment: the destination address must have zero nonce and zero code length. Unfortunately, this is not sufficient. Before [EIP-158](./eip-158.md) was applied, the nonce of a newly deployed contract remained set to zero. Therefore, it was entirely possible to create a contract with a zero nonce and zero code length but with non-empty storage, if slots were set in the constructor. There exists 28 such contracts on Ethereum mainnet at this time. + +As one of the core tenets of smart contracts is that its code will not change, even if the code is zero length. The contract creation must be rejected in such instanace. + +## Backwards Compatibility + +This is an execution layer upgrade, and so it requires a hard fork. + +## Test Cases + +There exists quite a number of tests in the ethereum tests repo as well as in the execution spec tests, which test the scenario of deployment to targets with non-empty storage. These tests have been considered problematic in the past; Reth and EELS both intentionally implement a version of the account reset solely to pass the tests. Py-evm declared the situation impossible and never implemented account reset. + +Refilling the existing tests will provide sufficient coverage for this EIP. + +## Security Considerations + +This EIP is a security upgrade: it enforces the imutability of deployed code. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7612.md b/EIPS/eip-7612.md new file mode 100644 index 00000000000000..5edc38c94270c8 --- /dev/null +++ b/EIPS/eip-7612.md @@ -0,0 +1,182 @@ +--- +eip: 7612 +title: Verkle state transition via an overlay tree +description: Describes the use of an overlay tree to use the verkle tree structure, while leaving the historical state untouched. +author: Guillaume Ballet (@gballet), Ansgar Dietrichs (@adietrichs), Ignacio Hagopian (@jsign), Gottfried Herold (@GottfriedHerold), Jamie Lokier (@jlokier), Tanishq Jasoria (@tanishqjasoria), Parithosh Jayanthi (@parithosh), Gabriel Rocheleau (@gabrocheleau), Karim Taam (@matkt) +discussions-to: https://ethereum-magicians.org/t/ethereum-state-trie-format-change-using-an-overlay/4165 +status: Draft +type: Standards Track +category: Core +created: 2024-01-25 +requires: 4762, 6800, 7545 +--- + +## Abstract + +This EIP proposes a method to switch the state tree tree format from hexary Merkle Patricia Tree (MPT) to a verkle tree: the MPT tree is frozen, and new writes to the state are stored in a verkle tree “laid over” the hexary MPT. The historical MPT state is left untouched and its eventual migration is handled at a later time. + +## Motivation + +The Ethereum state is growing, and verkle trees offer a good mitigation strategy to stem this growth and enable weak statelessness. Owing to the difficulty of translating contracts with large storage while they are being accessed, proposals for migrating the current MPT state are complex and will require client teams to undergo a long process of refactoring their code to handle this conversion. + +The bigger the state, the longer any conversion process will take. This has an impact both while the conversion is happening, as well as when full-syncing the chain if the conversion is part of consensus. Fullsync is used extensively by core dev teams to test the performance of new code. A conversion longer than a month will impact the release schedule of client teams who typically release at this rate. Nodes that cannot follow the conversion will need to wait longer to rejoin. The conversion will also make reorg slower, so reducing its duration is desirable. + +This current proposal suggests to stop the MPT state growth in its tracks by activating a new “overlay” verkle tree, that all new state updates are written to. The “base” MPT tree is frozen in place, until all execution clients are ready to perform the full transition. Data is read first from the overlay tree, and if not found there, from the MPT. + +Whenever the block that freeze the MPT is finalized, internal node data can be deleted, in order to free up disk space. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Constants + +|Parameter|value|Description| +|-|-|-| +|`FORK_TIME`|`TDB`|Time at which the verkle, overlay tree is activated.| + +### Helper functions + +```python3 +# Determine if `block` is the fork activation block +def is_fork_block(block): + return block.parent.timestamp < FORK_TIME && block.timestamp >= FORK_TIME + +# Write an account in the verkle tree +def verkle_set_account(tree: VerkleTree, key: Bytes32, account: Optional[Account]): + if account is not None: + versionkey = key + tree.set(versionkey, 0) + balancekey = key + balancekey[31] = BALANCE_LEAF_KEY + tree.set(balancekey, account.balance) + noncekey = key + noncekey[31] = NONCE_LEAF_KEY + tree.set(noncekey, account.nonce) + ckkey = key + ckkey[31] = CODE_KECCAK_LEAF_KEY + tree.set(ckkey, account.code_hash) + cskey = key + cskey[31] = CODE_SIZE_LEAF_KEY + tree.set(cskey, len(account.code)) + +# Reads an account from the verkle tree +def verkle_get_account(tree: VerkleTree, key: Bytes32) -> Optional[Account]: + version_leaf = tree.get(key) + if version_leaf is not None: + balancekey = key + balancekey[31] = BALANCE_LEAF_KEY + balance = tree.get(balancekey, account.balance) + noncekey = key + noncekey[31] = NONCE_LEAF_KEY + nonce = tree.get(noncekey) + ckkey = key + ckkey[31] = CODE_KECCAK_LEAF_KEY + ck = tree.get(ckkey) + cskey = key + cskey[31] = CODE_SIZE_LEAF_KEY + cs = tree.set(cskey) + account = Account(0, balance, nonce, ck, cs) + + return account +``` + +### Changes to the execution spec: + +In the execution spec, modify the `State` class as such: + +```python3 +@dataclass +class State: + """ + Contains all information that is preserved between transactions. + """ + + _main_trie: Trie[Address, Optional[Account]] = field( + default_factory=lambda: Trie(secured=True, default=None) + ) + _storage_tries: Dict[Address, Trie[Bytes, U256]] = field( + default_factory=dict + ) + _snapshots: List[ + Tuple[ + Trie[Address, Optional[Account]], Dict[Address, Trie[Bytes, U256]] + ] + ] = field(default_factory=list) + _created_accounts: Set[Address] = field(default_factory=set) + + # Added in this EIP + _overlay_tree: VerkleTree[Address, Bytes32] +``` + +And the state access functions are modified as such: + +```python3 +def get_account_optional(state: State, address: Address) -> Optional[Account]: + account = verkle_get_account(state._overlay_tree, get_tree_key_for_version(addr)) + if account is not None: + return account + + return trie_get(state._main_trie, address) + +def set_account(state: State, address: Address, account: Optional[Account]) -> None: + verkle_set_account(state._overlay_tree, get_tree_key_for_nonce(addr), account) + +def get_storage(state: State, address: Address, key: Bytes) -> U256: + value = state._overlay_tree.get(get_tree_key_for_storage_slot(addr, slot)) + if value is not None: + return value + + trie = state._storage_tries.get(address) + if trie is None: + return U256(0) + + value = trie_get(trie, key) + + assert isinstance(value, U256) + return value + +def set_storage( + state: State, address: Address, key: Bytes, value: U256 +) -> None: + state._overlay_tree.set(get_tree_key_for_storage_slot(addr, slot), value) +``` + +## Rationale + +This approach doesn't convert the state, which is left to a subsequent EIP. This is meant as a stopgap in case we decide to push the conversion itself to a later time. It has the advantage of simplicity, which means that the Verge fork could happen at the same time as other, simpler EIPs. It also requires no change at the consensus layer. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Test Cases + + + +## Reference Implementation + + * `transition-post-genesis` branch in `github.com/gballet/go-ethereum` implements this when setting `--override.overlay-stride=0` on the command line. + +## Security Considerations + + + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7620.md b/EIPS/eip-7620.md new file mode 100644 index 00000000000000..538afe2721cfaf --- /dev/null +++ b/EIPS/eip-7620.md @@ -0,0 +1,202 @@ +--- +eip: 7620 +title: EOF Contract Creation +description: Introduce `EOFCREATE` and `RETURNCONTRACT` instructions +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Andrei Maiboroda (@gumb0), Piotr Dobaczewski (@pdobacz) +discussions-to: https://ethereum-magicians.org/t/eip-7620-eof-contract-creation-instructions/18625 +status: Review +type: Standards Track +category: Core +created: 2024-02-12 +requires: 170, 3540, 3541, 3670 +--- + +## Abstract + +EVM Object Format (EOF) removes the possibility to create contracts using `CREATE` or `CREATE2` instructions. We introduce a new/replacement method in form of pair of instructions : `EOFCREATE` and `RETURNCONTRACT` to provide a way to create contracts using EOF containers. + +## Motivation + +This EIP uses terminology from the [EIP-3540](./eip-3540.md) which introduces the EOF format. + +EOF aims to remove code observability, which is a prerequisite to legacy EVM contract creation logic using legacy-style create transactions, `CREATE` or `CREATE2`, because both the initcode and code are available to the EVM and can be manipulated. On the same premise, EOF removes opcodes like `CODECOPY` and `EXTCODECOPY`, introducing EOF subcontainers as a replacement to cater for factory contracts creating other contracts. + +The new instructions introduced in this EIP operate on EOF containers enabling factory contract use case that legacy EVM has. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Parameters + +| Constant | Value | +| - | - | +| `GAS_KECCAK256_WORD` | Defined as `6` in the [Ethereum Execution Layer Specs](https://github.com/ethereum/execution-specs/blob/0f9e4345b60d36c23fffaa69f70cf9cdb975f4ba/src/ethereum/shanghai/vm/gas.py#L37C1-L37C19) | +| `TX_CREATE_COST` | Defined as `32000` in the [Ethereum Execution Layer Specs](https://github.com/ethereum/execution-specs/blob/0f9e4345b60d36c23fffaa69f70cf9cdb975f4ba/src/ethereum/shanghai/fork_types.py#L42) | +| `STACK_DEPTH_LIMIT` | Defined as `1024` in the [Ethereum Execution Layer Specs](https://github.com/ethereum/execution-specs/blob/0f9e4345b60d36c23fffaa69f70cf9cdb975f4ba/src/ethereum/shanghai/vm/interpreter.py#L60) | +| `GAS_CODE_DEPOSIT` | Defined as `200` in the [Ethereum Execution Layer Specs](https://github.com/ethereum/execution-specs/blob/0f9e4345b60d36c23fffaa69f70cf9cdb975f4ba/src/ethereum/shanghai/vm/gas.py#L44) | +| `MAX_CODE_SIZE` | Defined as `24576` in [EIP-170](./eip-170.md) | + +We introduce two new instructions on the same block number [EIP-3540](./eip-3540.md) is activated on: + +1. `EOFCREATE` (`0xec`) +2. `RETURNCONTRACT` (`0xee`) + +### Execution Semantics + +- The instructions `CREATE`, `CREATE2` are made obsolete and rejected by validation in EOF contracts. They are only available in legacy contracts. +- If instructions `CREATE` and `CREATE2` have EOF code as initcode (starting with `EF00` magic) + - deployment fails (returns 0 on the stack) + - caller's nonce is not updated and gas for initcode execution is not consumed + +#### Overview of the new contract creation flow + +In EOF EVM, new bytecode is delivered by means of creation transactions (with an empty `to`) in the form of an EOF container (`initcontainer`). Such a container may contain arbitrarily deeply nesting subcontainers. The `initcontainer` and its subcontainers are recursively validated according to all the validation rules applicable for the EOF version in question. Next, the 0th code section of the `initcontainer` is executed and may eventually call a `RETURNCONTRACT` instruction, which will refer to a subcontainer to be finally deployed to an address. + +EOF creation transactions (ones with an empty `to` and with `data` starting with `EF00` magic) are defined in detail in a separate EIP. + +`EOFCREATE` instruction is in turn a replacement of the `CREATE` and `CREATE2` legacy instructions allowing factory contracts to create other contracts. The main difference to the creation transaction is that the `initcontainer` is selected to be one of the subcontainers of the EOF container calling `EOFCREATE`. It is worth noting that no validation is performed at this point, as it has already been done when the factory contract containing `EOFCREATE` was deployed. + +Details on each instruction follow in the next sections. + +#### `EOFCREATE` + +- deduct `TX_CREATE_COST` gas +- read immediate operand `initcontainer_index`, encoded as 8-bit unsigned value +- pop `value`, `salt`, `input_offset`, `input_size` from the operand stack +- perform (and charge for) memory expansion using `[input_offset, input_size]` +- load initcode EOF subcontainer at `initcontainer_index` in the container from which `EOFCREATE` is executed + - let `initcontainer_size` be the declared size of that EOF subcontainer in its parent container header +- deduct `GAS_KECCAK256_WORD * ((initcontainer_size + 31) // 32)` gas (hashing charge) +- check that current call depth is below `STACK_DEPTH_LIMIT` and that caller balance is enough to transfer `value` + - in case of failure return 0 on the stack, caller's nonce is not updated and gas for initcode execution is not consumed. +- caller's memory slice [`input_offset`:`input_size`] is used as calldata +- execute the container and deduct gas for execution. The 63/64th rule from [EIP-150](./eip-150.md) applies. +- increment `sender` account's nonce +- calculate `new_address` as `keccak256(0xff || sender || salt || keccak256(initcontainer))[12:]` +- an unsuccessful execution of initcode results in pushing `0` onto the stack + - can populate returndata if execution `REVERT`ed +- a successful execution ends with initcode executing `RETURNCONTRACT{deploy_container_index}(aux_data_offset, aux_data_size)` instruction (see below). After that: + - load deploy EOF subcontainer at `deploy_container_index` in the container from which `RETURNCONTRACT` is executed + - concatenate data section with `(aux_data_offset, aux_data_offset + aux_data_size)` memory segment and update data size in the header + - if updated deploy container size exceeds `MAX_CODE_SIZE` instruction exceptionally aborts + - set `state[new_address].code` to the updated deploy container + - push `new_address` onto the stack +- deduct `GAS_CODE_DEPOSIT * deployed_code_size` gas + +#### `RETURNCONTRACT` + +- read immediate operand `deploy_container_index`, encoded as 8-bit unsigned value +- pop two values from the operand stack: `aux_data_offset`, `aux_data_size` referring to memory section that will be appended to deployed container's data +- cost 0 gas + possible memory expansion for aux data +- ends initcode frame execution and returns control to EOFCREATE/4 caller frame where `deploy_container_index` and `aux_data` are used to construct deployed contract (see above) +- instruction exceptionally aborts if after the appending, data section size would overflow the maximum data section size or underflow (i.e. be less than data section size declared in the header) + +### Code Validation + + +For terminology purposes, the following concepts are defined: + +- an "initcode" container is one which does not contain `RETURN` or `STOP` +- a "runtime" container is one which does not contain `RETURNCONTRACT` + +Note a container can be both "initcode" and "runtime" if it does not contain any of `RETURN`, `STOP` or `RETURNCONTRACT` (for instance, if its code sections terminate with `REVERT` or `INVALID`). + +We extend code section validation rules (as defined in [EIP-3670](./eip-3670.md)). + +1. `EOFCREATE` `initcontainer_index` must be less than `num_container_sections` +2. `EOFCREATE` the subcontainer pointed to by `initcontainer_index` must have its `len(data_section)` equal `data_size`, i.e. data section content is exactly as the size declared in the header (see [Data section lifecycle](#data-section-lifecycle)) +3. `EOFCREATE` the subcontainer pointed to by `initcontainer_index` must be an "initcode" subcontainer +4. `RETURNCONTRACT` `deploy_container_index` must be less than `num_container_sections` +5. `RETURNCONTRACT` the subcontainer pointed to `deploy_container_index` must be a "runtime" subcontainer +6. It is an error for a container to contain both `RETURNCONTRACT` and either of `RETURN` or `STOP` +7. It is an error for a subcontainer to never be referenced in code sections of its parent container +8. `RJUMP`, `RJUMPI` and `RJUMPV` immediate argument value (jump destination relative offset) validation: code section is invalid in case offset points to the byte directly following either `EOFCREATE` or `RETURNCONTRACT` instruction. + +### Data Section Lifecycle + +**For an EOF container which has not yet been deployed**, the `data_section` is only a portion of the final `data_section` after deployment. +Let's define it as `pre_deploy_data_section` and as `pre_deploy_data_size` the `data_size` declared in that container's header. +`pre_deploy_data_size >= len(pre_deploy_data_section)`, which anticipates more data to be appended to the `pre_deploy_data_section` during the process of deploying. + +``` +pre_deploy_data_section +| | +\___________pre_deploy_data_size______/ +``` + +**For a deployed EOF container**, the final `data_section` becomes: + +``` +pre_deploy_data_section | static_aux_data | dynamic_aux_data +| | | | +| \___________aux_data___________/ +| | | +\___________pre_deploy_data_size______/ | +| | +\________________________data_size_______________________/ +``` + +where: + +- `aux_data` is the data which is appended to `pre_deploy_data_section` on `RETURNCONTRACT` instruction. +- `static_aux_data` is a subrange of `aux_data`, which size is known before `RETURNCONTRACT` and equals `pre_deploy_data_size - len(pre_deploy_data_section)`. +- `dynamic_aux_data` is the remainder of `aux_data`. + +`data_size` in the deployed container header is updated to be equal `len(data_section)`. + +Summarizing, there are `pre_deploy_data_size` bytes in the final data section which are guaranteed to exist before the EOF container is deployed and `len(dynamic_aux_data)` bytes which are known to exist only after. +This impacts the validation and behavior of data-section-accessing instructions: `DATALOAD`, `DATALOADN`, and `DATACOPY`, see [EIP-7480](./eip-7480.md). + +## Rationale + +### Data section appending + +The data section is appended to during contract creation and also its size needs to be updated in the header. Alternative designs were considered, where: + +- additional section kinds for the data were introduced +- additional fields describing a subcontainer were introduced +- data section would be written over as opposed to being appended to, requiring it to be filled with 0 bytes prior to deployment + +All of these alternatives either complicated the otherwise simple data structures or took away useful features (like the dynamically sized portion of the data section). + +### EOF validation checking initcode-mode + +Extra EOF validation rules were considered: + +- Each EOF subcontainer must either be referenced by an `EOFCREATE` or a `RETURNCONTRACT` instruction, but never both +- Each EOF subcontainer may either contain `RETURNCONTRACT` or `RETURN` / `STOP` instructions, but never a mix of these two kinds +- A subcontainer referenced by an `EOFCREATE` must never contain a `RETURN` / `STOP` instruction, whereas a subcontainer referenced by a `RETURNCONTRACT` must never contain a `RETURNCONTRACT` + +These rules were not adopted to avoid the extra logic and complexity (esp. the last rule causes EOF validation of subcontainers to not be self-contained). + +## Backwards Compatibility + +This change poses no risk to backwards compatibility, as it is introduced at the same time EIP-3540 is. The new instructions are not introduced for legacy bytecode (code which is not EOF formatted), and the contract creation options do not change for legacy bytecode. + +`CREATE` and `CREATE2` calls with `EF00` initcode fail early without executing the initcode. Previously, in both cases the initcode execution would begin and fail on the first undefined instruction `EF`. + +## Test Cases + +Creation transaction, `CREATE` and `CREATE2` cannot have its *code* starting with `0xEF`, but such cases are covered already in [EIP-3541](./eip-3541.md). However, new cases must be added where `CREATE` or `CREATE2` have its *initcode* being (validly or invalidly) EOF formatted: + +| Initcode | Expected result | +| - | - | +| `0xEF` | initcode starts execution and fails | +| `0xEF01` | initcode starts execution and fails | +| `0xEF5f` | initcode starts execution and fails | +| `0xEF00` | `CREATE` / `CREATE2` fails early, returns 0 and keeps sender nonce intact | +| `0xEF0001` | as above | +| valid EOFv1 container | as above | + +## Security Considerations + +It is the EOF creation transaction (specified in a separate EIP) which needs a detailed review and discussion as that is where external unverified code enters the state. Among others: + +1. Is its complexity under control, ruling out any DoS attempts +2. Is it correctly priced and always charged for +3. Is the validation comprehensive and not allowing problematic code to be saved into the state + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7623.md b/EIPS/eip-7623.md new file mode 100644 index 00000000000000..987088182e418d --- /dev/null +++ b/EIPS/eip-7623.md @@ -0,0 +1,93 @@ +--- +eip: 7623 +title: Increase calldata cost +description: Increase calldata cost to decrease the maximum block size +author: Toni Wahrstätter (@nerolation), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7623-increase-calldata-cost/18647 +status: Review +type: Standards Track +category: Core +created: 2024-02-13 +--- + + + +## Abstract + +The current calldata pricing allows for significantly large blocks of up to 2.8 MB while the average block size is much smaller at 125 KB. +This EIP proposes an adjustment in the Ethereum calldata cost to reduce the maximum possible block size and its variance without impacting regular users. +This is achieved by increasing the calldata cost for transactions primarily using Ethereum for data availability. + + +## Motivation + +The block gas limit has not been increased since [EIP-1559](./eip-1559.md), while the average size of blocks has continuously increased due to the growing number of rollups posting data to Ethereum. Furthermore, the cost for calldata hasn't been adjusted since [EIP-2028](./eip-2028). +[EIP-4844](./eip-4844.md) introduces blobs as a preferred method for data availability (DA). +This transition demands a reevaluation of calldata pricing, especially with regards to mitigating the inefficiency between the average block size and the maximum one possible. +By introducing a floor cost dependent on calldata for transactions that are mainly using Ethereum for DA, this proposal aims to reduce the maximum block size to make room for adding more blobs. + + +## Specification + +| Parameter | Value | +| - | - | +| `STANDARD_TOKEN_COST` | `4` | +| `TOTAL_COST_FLOOR_PER_TOKEN` | `10` | + + +Let `tokens_in_calldata = zero_bytes_in_calldata + nonzero_bytes_in_calldata * 4`. + +Let `isContractCreation` be a boolean indicating the respective event. + +The current formula for determining the gas used per transaction, typically described as `nonzero_bytes_in_calldata * 16 + zero_bytes_in_calldata * 4`, is equivalent to: + +```python +tx.gasused = ( + 21000 \ + + isContractCreation * (32000 + InitCodeWordGas * words(calldata)) \ + + STANDARD_TOKEN_COST * tokens_in_calldata \ + + evm_gas_used +) +``` + +The formula for determining the gas used per transaction changes to: + +```python +tx.gasUsed = { + 21000 \ + + + max ( + STANDARD_TOKEN_COST * tokens_in_calldata \ + + evm_gas_used \ + + isContractCreation * (32000 + InitCodeWordGas * words(calldata)), + TOTAL_COST_FLOOR_PER_TOKEN * tokens_in_calldata + ) +``` + +For implementation this means that the `TOTAL_COST_FLOOR_PER_TOKEN` must be deducted before execution to avoid invalidation after execution. + +## Rationale + +The current maximum block size is approximately 1.79 MB (`30_000_000/16`). One can create blocks full of zero bytes that go up to 7.5 MB, but it is now standard to wrap blocks with snappy compression at the p2p layer and so such zero-byte-heavy blocks would end up smaller than 1.79 MB in practice. With the implementation of [EIP-4844](./eip-4844.md) this increased to ~2.54 MB. Furthermore, the cost for calldata bytes hasn't been adjusted since [EIP-2028](./eip-2028). + +This proposal aims to increase the cost of calldata to 10/40 gas for transactions that do not exceed a certain threshold of gas spent on EVM operations. This change will significantly reduce the maximum block size by limiting the number and size of pure-data transactions that can fit into a single block. Specifically, by adjusting the cost of calldata bytes to from 4/16 to 10/40 gas for DA transactions, the goal is to lower the maximum possible block size to roughly 0.72 MB without impacting the vast majority of users. + + +This reduction makes room for increasing the block gas limit or the number of blobs, while ensuring network security and efficiency. +Importantly, regular users (sending ETH/Tokens/NFTs, engaging in DeFi, social media, restaking, bridging, etc.) who do not use Ethereum almost exclusively for DA, may remain unaffected. +The calldata cost for transactions involving significant EVM computation remains at 4/16 gas per byte, ensuring those transactions experience no change. + + +## Backwards Compatibility + +This is a backwards incompatible gas repricing that requires a scheduled network upgrade. + +Users will be able to continue operating with no changes. + +## Security Considerations + +As the maximum possible block size is reduced, no security concerns were raised. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7636.md b/EIPS/eip-7636.md new file mode 100644 index 00000000000000..3520c973077c04 --- /dev/null +++ b/EIPS/eip-7636.md @@ -0,0 +1,78 @@ +--- +eip: 7636 +title: Extension of EIP-778 for "client" ENR Entry +description: Add additional ENR entry to specify client information such as name and version number. +author: James Kempton (@JKincorperated) +discussions-to: https://ethereum-magicians.org/t/eip7636-extension-of-eip-778-for-client-enr-entry/18935 +status: Review +type: Standards Track +category: Networking +created: 2024-02-25 +requires: 778 +--- + +## Abstract + +The Ethereum network consists of nodes running various client implementations. Each client has its own set of features, optimizations, and unique behaviors. Introducing a standardized way to identify client software and its version in the ENR allows for more effective network analysis, compatibility checks, and troubleshooting. This EIP proposes the addition of a "client" field to the ENR. + +## Motivation + +Understanding the landscape of client software in the Ethereum network is crucial for developers, nodes, and network health assessment. Currently, there is no standardized method for nodes to announce their software identity and version, which can lead to compatibility issues or difficulty in diagnosing network-wide problems. Adding this to the ENR allows clients to audit network health only using discv5, and additionally track discv5 adoption across different services. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +The "client" entry is proposed to be added to the ENR following the specifications in [EIP-778](./eip-778.md). This entry is OPTIONAL and can be omitted by clients that choose not to disclose such information. The key for this entry is `"client"`. + +All elements MUST be encoded as a string using the ASCII standard as described in [RFC 20](https://www.rfc-editor.org/rfc/rfc20). + +The value for this entry MUST be an RLP list: + +``` +[ClientName, Version, (BuildVersion)] +``` + +- `ClientName`: A string identifier for the client software. It SHOULD be concise, free of spaces, and representative of the client application. +- `Version`: A string representing the version of the client software in a human-readable format. It is RECOMMENDED to follow semantic versioning. +- `BuildVersion`: An OPTIONAL string representing the build or commit version of the client software. This can be used to identify specific builds or development versions. + +## Rationale + +One key was chosen over using many keys to make efficient use of space. The use of one string, however, does not align with other EIPs of similar purpose and as such the RLP list was decided as the best encoding. + +## Backwards Compatibility + +This EIP is fully backwards compatible as it extends the ENR specification by adding an optional entry. Existing implementations that do not recognize the "client" entry will ignore it without any adverse effects on ENR processing or network behavior. + +## Test Cases + +A node running Geth version 1.10.0 on the mainnet might have an ENR `client` entry like: + +``` +["Geth", "1.10.0"] +``` + +A node running an experimental build of Nethermind might include: + +``` +["Nethermind", "1.9.53", "7fcb567"] +``` + +and an ENR of + +``` +enr:-MO4QBn4OF-y-dqULg4WOIlc8gQAt-arldNFe0_YQ4HNX28jDtg41xjDyKfCXGfZaPN97I-MCfogeK91TyqmWTpb0_AChmNsaWVudNqKTmV0aGVybWluZIYxLjkuNTOHN2ZjYjU2N4JpZIJ2NIJpcIR_AAABg2lwNpAAAAAAAAAAAAAAAAAAAAABiXNlY3AyNTZrMaECn-TTdCwfZP4XgJyq8Lxoj-SgEoIFgDLVBEUqQk4HnAqDdWRwgiMshHVkcDaCIyw +``` + +which can be decoded to yield normal data such as `seq`, `siqnature`, `id` and `secp256k1`. Additionally, it would yield the client value of `["0x4e65746865726d696e64","0x312e392e3533","0x37666362353637"]` or `["Nethermind", "1.9.53", "7fcb567"]` + +## Security Considerations + +Introducing identifiable client information could potentially be used for targeted attacks against specific versions or builds known to have vulnerabilities. It is crucial for clients implementing this EIP to consider the implications of disclosing their identity and version. Users or operators should have the ability to opt-out or anonymize this information if desired. + +Additionally, as this information is self proclaimed, this data ***MUST NOT*** be used for anything that requires it to be reliable. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7639.md b/EIPS/eip-7639.md new file mode 100644 index 00000000000000..0cf333c0bc063b --- /dev/null +++ b/EIPS/eip-7639.md @@ -0,0 +1,55 @@ +--- +eip: 7639 +title: Cease serving history before PoS +description: Execution layer clients will no longer serve block data before Paris over p2p. +author: lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/cease-serving-history-before-pos/18991 +status: Draft +type: Standards Track +category: Networking +created: 2024-02-13 +--- + +## Abstract + +Execution layer clients will no longer request or respond to p2p queries about +block data before the Paris upgrade. + +## Motivation + +As of 2024, historical data in clients has grown to around 500 GB. Nearly 400 GB +of that is from block data before PoS was activated in the Paris upgrade. Long +term, Ethereum plans to bound the amount of data nodes must store. This EIP +proposes the first steps to achieve such goal. + +## Specification + +Clients must not make or respond to p2p queries about blocks before block 15537393. + +## Rationale + +### Only Pre-PoS data + +One might ask why the distinction between pre and post PoS data is made in this +EIP. The simple answer is that the at the moment of the merge, the block +structure changed substantially. Although execution layer client software today +continues on with block data on disk which remains similar to per-PoS data, the +beacon chain is now the canonical chain definition. Therefore, a beacon block +can be used to both record historical data for execution layer and beacon layer. + +Over the long term, the distinctions of "execution layer" and "consensus layer" +may matter less. This EIP tries to be agnostic to client architecture and +instead focuses on the shape of the data. + +## Backwards Compatibility + +After this EIP is activated, nodes will no longer be able to full sync from the +devp2p network. To continue doing so, they must retrieve the data out-of-band. + +## Security Considerations + +TODO + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7642.md b/EIPS/eip-7642.md new file mode 100644 index 00000000000000..265fce0e3ab8ab --- /dev/null +++ b/EIPS/eip-7642.md @@ -0,0 +1,104 @@ +--- +eip: 7642 +title: eth/69 - Drop pre-merge fields +description: Drop unnecessary fields after the merge +author: Marius van der Wijden (@MariusVanDerWijden) +discussions-to: https://ethereum-magicians.org/t/eth-70-drop-pre-merge-fields-from-eth-protocol/19005 +status: Draft +type: Standards Track +category: Networking +created: 2024-02-29 +requires: 5793 +--- + +## Abstract + +After the merge a few fields (`td`) and messages (`NewBlockHashes`, `NewBlock`) in the networking protocol became obsolete. +This EIP modifies the networking messages such that these fields are not sent anymore. +Additionally we propose to remove the `Bloom` field from the receipts networking messages. + +## Motivation + +We recently discovered that none of the clients store the `Bloom` field of the receipts as it can be recomputed on demand. +However the networking spec requires the `Bloom` field to be sent over the network. +Thus a syncing node will ask for the Bloom filters for all receipts. +The serving node will regenerate roughly 530GB of bloom filters (2.3B txs * 256 byte). +These 530GBs are send over the network to the syncing peer, the syncing peer will verify them and not store them either. +This adds an additional 530GB of unnecessary bandwidth to every sync. + +Additionally we propose to remove fields and messages that were deprecated by the merge, such as + +- Removing the `TD` field in the `Status` message. + +- Removing the `NewBlockHashes` message. + +- Removing the `NewBlock` message. + +## Specification + +Remove the `NewBlockHashes (0x01)` message. + +Remove the `NewBlock (0x07)` message. + +Modify the `Status (0x00)` message as follows: + +- (eth/68): `[version: P, networkid: P, td: P, blockhash: B_32, genesis: B_32, forkid]` + +- (eth/69): `[version: P, networkid: P, blockhash: B_32, genesis: B_32, forkid]` + +Modify the encoding for receipts in the `Receipts (0x10)` message as follows: + +- (eth/68): `receipt = {legacy-receipt, typed-receipt}` with `typed-receipt = tx-type || receipt-data` and + +``` +legacy-receipt = [ + post-state-or-status: {B_32, {0, 1}}, + cumulative-gas: P, + bloom: B_256, + logs: [log₁, log₂, ...] +] +``` + +- (eth/69): `receipt = {legacy-receipt, typed-receipt}` with `typed-receipt = tx-type || receipt-data` and + +``` +legacy-receipt = [ + post-state-or-status: {B_32, {0, 1}}, + cumulative-gas: P, + logs: [log₁, log₂, ...] +] +``` + +We omit the bloom filter from both the legacy and typed receipts. +Receiving nodes will be able to recompute the bloom filter based on the logs. + +## Rationale + +After the merge, the `TD` field of the `Status` message became meaningless since the difficulty of post-merge blocks are 0. +It could in theory be used to distinguish synced with unsynced nodes, +but the same thing can be accomplished with the forkid as well. +It is not used in the go-ethereum codebase in any way. + +After the merge, the `NewBlock` and `NewBlockHashes` messages have not been used for block propagation, +since block propagation post-merge happens solely on the consensus layer. +These message types error out in the go-ethereum implementation. +Getting rid of them would allow us to disconnect non-mainnet peers earlier. + +Removing the bloom filters from the `Receipt` message reduces the cpu load of serving nodes as well as the bandwidth significantly. The receiving nodes will need to recompute the bloom filter. The recomputation is not very CPU intensive. +The bandwidth gains amount to roughly 530GiB per syncing node or (at least) 95GiB snappy compressed. + +## Backwards Compatibility + +Since this EIP removes the `NewBlock` and `NewBlockHashes` messages, private networks or forks that use them to distribute blocks can not update to this version. All private networks or forks that use a mechanism similar to ethereum mainnet, where the consensus layer takes care of block distribution can update to `eth/69`. + +This EIP changes the eth protocol and requires rolling out a new version, `eth/69`. Supporting multiple versions of a wire protocol is possible. Rolling out a new version does not break older clients immediately, since they can keep using protocol version `eth/68`. + +This EIP does not change consensus rules of the EVM and does not require a hard fork. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7643.md b/EIPS/eip-7643.md new file mode 100644 index 00000000000000..8d7235c86573ba --- /dev/null +++ b/EIPS/eip-7643.md @@ -0,0 +1,1983 @@ +--- +eip: 7643 +title: History accumulator for pre-PoS data +description: Commit to a single root for all block data before the merge. +author: lightclient (@lightclient), kdeme (@kdeme) +discussions-to: https://ethereum-magicians.org/t/eip-7643-history-accumulator-for-pre-pos-data/19014 +status: Draft +type: Standards Track +category: Core +created: 2024-02-29 +--- + +## Abstract + +Defines an SSZ object for accumulating all pre-PoS data and commit to the +historical hashes accumulator's root +`0xec8e040fd6c557b41ca8ddd38f7e9d58a9281918dc92bdb72342a38fb085e701`. + +## Motivation + +There are two main uses we consider for the historical hashes accumulator: + +* for users who wish to download the pre-PoS data for the execution chain and + verify it without executing each block, they may simply compute each block + hash, accumulate the epoch records, and then compare the local accumulator + root with the expected value. +* additionally, the accumulator root allows for `O(log(n))` sized proofs to any + pre-PoS block, whereas today to achieve something similar, one must + recursively verify the header chain. + +## Specification + +### Historical Hashes Accumulator + +The historical hashes accumulator commits to the set of pre-merge headers and their +associated total difficulty. The format for this data is defined as: + +```python +EPOCH_SIZE = 8192 # blocks +MAX_HISTORICAL_EPOCHS = 2048 + +# An individual record for a historical header. +HeaderRecord = Container[block_hash: bytes32, total_difficulty: uint256] + +# The records of the headers from within a single epoch +EpochRecord = List[HeaderRecord, max_length=EPOCH_SIZE] + +HistoricalHashesAccumulator = Container[ + historical_epochs: List[bytes32, max_length=MAX_HISTORICAL_EPOCHS], + current_epoch: EpochRecord, +] +``` + +### Pre-PoS Root + +The hash tree root of `HistoricalHashesAccumulator` for data before block 15537394 is +`0xec8e040fd6c557b41ca8ddd38f7e9d58a9281918dc92bdb72342a38fb085e701`. + +## Rationale + +### Inclusion of total difficulty + +The total difficulty allowed so that clients may return the value for specific +JSON-RPC methods which support it. It is also useful for verifying the TTD of +the final proof-of-work block. + +## Backwards Compatibility + +n/a + +## Test Cases + +```csv +epoch,root +00000,0x5ec1ffb8c3b146f42606c74ced973dc16ec5a107c0345858c343fc94780b4218 +00001,0xa5364e9a9bc513c4601f0d62e6b46dbdedf3200bbfae54d6350f46f2c7a01938 +00002,0x98cbd8a95ae7dc9c1ed823156d0eab9aaffa869f6852cab18ff0083063f27d26 +00003,0xd8b8a40b8cf6818e1bac871d882e772be0b28d1baaf72374946506d9e6fa7d75 +00004,0x6e3baba7e324b99ed72d98f0255d25ce66832736550f8b971c12280eac2a0bb8 +00005,0x5cff5a4b7284b1a4a6cebfcc80d876ab0418f71254d03f91d46a9a1fab49fa09 +00006,0x678fb79306f84e9d0a4749323dc29934ca59b852fbc7c8d2890eabe8a0cde282 +00007,0xd9bc682bc5bc63b20a8344407ae12cb17e2085d448f438efa6aa5d522b913a20 +00008,0x12c9605f2d8d4738f9aa04fbecdbbbc8b77135ebfaa9db399135c14e1ef10bee +00009,0xf9e4e8905b214c97bb4ed1f69178d6ecc769e21352885147fce5b671215db2a8 +00010,0x5f5d4516b7a38929b47ea7334b62b53829b9665d37f752d96c33fad0f7f78583 +00011,0x30f04eb968efe4079356b873e37f1657984717e60af612ecca95c98226528d54 +00012,0x5ecb9bf9e193da08c7e7f22abcd50d1b4d3c2b909f980ac1315856cb48ca49cc +00013,0xd0175c1ed6e694180c4c161ac7f06a913784daba14dc1d2e926f72def4f7f65d +00014,0x4f92d78141b7fa8d6fcef45f9dbc611f858447629eeac2d63bb43d07e6bd1aca +00015,0xa47cb8eb7157d56f718a6896c2ee1843a44e3de81b9127e64b78fc38ee382310 +00016,0x9344d8b785c0e619d0b1b83e5d7b3849d667f1ec0d0d6390d26fa33dd4cb31af +00017,0x43963724de4a8917d16d8c6a663c38fcdcf3ce5b89a51bc766dcd0ffd1d5aa32 +00018,0xefce27b480c92a0e7fec472fe38e87ed9a1c91c3d07324cc2f262de3916a38f6 +00019,0xf5434352253a7f35d909fb2c383e7cdad65761c509eec24741197b869ebcc212 +00020,0x0c405203cb7b2e54b910e5d953b5378ff4f0c3bcebef92e7e3a1f240dd6703ee +00021,0x20d8f1af038c2777dea9f86fe9e33f14af9e4270ee20adb32e0dddedc4b85236 +00022,0xb694d8955851f744e44c68fba193f6bc41d1159036531c5f55fac9ce91883695 +00023,0x11beacba76e467dda23253f104d064b00ab75672ab33cff6097be1c3e8ce7053 +00024,0xf216a28afb2212269b634b9b44ff327a4a79f261640ff967f7e3283e3a184c70 +00025,0x987cb6206e5bae4b68ce0eeb6c05ae090d02b7331e47d1705a2a515ac88475aa +00026,0x3afd50ff0edf3cae577c42bfc39871f0f0ffe7bdd5ee0b96f7b2e879c9b29994 +00027,0x28083285c935c0c169ea1406f9830701ff20fde3d0b2a5b83efc1cd13139dccf +00028,0x362fc97cbcfa6ab609f1a3f8ca2f8a6e0ac6061c33e84a285a14713cfd73f203 +00029,0xa0cb99e26e896f5d115914910c4c66fc112ae240bc827acdd564785e738ff29c +00030,0x78fc5e8e58e6dd726499295eea1f7f52a31979c6a003d48d4e027d95285e851c +00031,0x52306cf9ed840bea9d8c3466bfbed5ffecdfd51107f33d013a487c3b653b3646 +00032,0xcb4d0c3a2384b890a8acd698da6b9ae6267c5365fcc516391829f7adbae838ee +00033,0x0c3781bbc07124e29ff67754bdcf556b20ac4f4ef19ddb004837ec50193ce0bc +00034,0xfac9315aa442073b647e71716a7acf1c170e5a0092b69edc2a5634813716592f +00035,0x737e07578f0dd5eeebd8313e58cdb59ac705c0ba07d842feace53fa2922c6508 +00036,0x84c7c1e7c4a8949247953858992012799d323ebcd0fc6cdecf8002f20f2ea7e1 +00037,0x34d067652cbea843a01e70ba75566b6f174218969dc453c285e59b4f309faee8 +00038,0x38aaf94c653d619b1a08e7cf9fac72ecc57715bc19ba236c942d400742bc3f16 +00039,0x4ad4940c51be350c9d8c69f424f01a9e87e42fe6b312afae3f8f7267c62512e5 +00040,0x4707f60dffab08b6837078ae91316ebe04a275aa19892462521cb6125913d3d7 +00041,0xa6a87a9e797af923887645fc57602d60f7cd684357ae837a6270936eb6e5ebd5 +00042,0x5c8dca3c7c7842995372aed15fae7b9bada264b56082bec19c870bd4c7562b97 +00043,0xcb513d912a6ee576a33cf3683d596354b57484cfb4d7e382f64326eef5bec32b +00044,0x1c72a3909e56831cea647e4c67faeb91db49b5be8c61832082041c16b2072e87 +00045,0xa87afdc1e1d225e6826d8f18c15c0415c7d13ba2a3933dc35816491bbc64501c +00046,0x22b3f78d1437187866a86fc05463d5afa558903def2357a05ffd32663d5b7896 +00047,0x92d8437253506251ea652d6242ced9f3941906d4ffaa78edcb396a6c5fcad7d7 +00048,0x78ae53ed63f208b18448b40e3c31476eb2cd6627d6c65ba7dbc96d3e1051dcca +00049,0x3934e9608386c1bab748cf80199b6b6341e581a163c64f6c0bfc55d36d41cc64 +00050,0x71698ebf74b826ce701bdda7c804c2b9d0aa3616bc1ccfbb62d4455cc2b0bec6 +00051,0x2c1c77788b22e42409b9e068fc98a28310af7cb451dbdc2601d29771bb117c47 +00052,0x3a047d9aba82db1eac26733dcc652c0aed663250b25781360ba9596db48ebe01 +00053,0x161ee1b5102e9c6300c04d4885dda180e50f3e5078ca8d2bc1f3d0af0a9d8287 +00054,0x14074ce7acc2ad4e4d60966d9717d8f2e6f7d28cffa1fccede05d4ab7269b772 +00055,0xae639ad86664191274136f85177a515b7524be9d089571f5e24c13bff9f91a38 +00056,0xd92c394c57df45119161e4ffecf8445e3af06c79c90987db86db649f2cbf7840 +00057,0x4bbe776e7229c9583ccc6da7d82451b56ef1fc015c802c27b2d364ffff7c6e7d +00058,0x9ac60ed891eb7490ae1a5fa1d9c14ef66b01bf5fdc6f31a419a28c2946e0c3bc +00059,0x246c1b33d8b91d3fad3c3b88d6aa04cd872bdf0608aafcd1f11a53c437418eec +00060,0x4533d0c5d211593355e4bf1e07564fc04bc158e75437f33eb97ec9066322b3dd +00061,0x122db1c231fee4e86b938a432ae95eae69a3ea733b82b15c2d784c70be3f9b89 +00062,0x65505079e3493c2fb572db2d1d9e455ef3e48be78c18f760fa6724fe1326f5ff +00063,0x39b219117b1d306e0e9ac0a8f969d47f1cc375d7593e2c8e0996fbb80822f293 +00064,0xdb26a83cc55bf6f8c6ff63525fafd2c8dca1a0cd99828afcdbc5d3146da18dde +00065,0x1df3a40f96ae6291f081fcf9dab9ebe03382d958cde909a4cb7cdc76201fe006 +00066,0x07bde22d34d4cd3a29214dd2bd1c35a49190a3df40505ddddde8e3622c6e7cab +00067,0x751bac833356761ab2a1794fed46b04afcbc60d23e608a707db5b897e5d042d2 +00068,0x546a10c136f0cb0c85bf58b69e04424ffcf1b00b4afffd3f33c5ee253899367b +00069,0x55c236ed7566681663e88a71b9597a48970297cbc0ee8b23b1d302dfe69f61f6 +00070,0x0ac3ebb18ec9ee6c921f36d5053d9343ad81218f797c39376d9e4f4352c768c7 +00071,0x2fb03713d78b7fba05408f872267c4877ed8db5e1bd1b9f1e57d872c5cc08adf +00072,0x2f9a4a75044a49046297e71c578329b8326352fd49bd01158f42c73ea6948454 +00073,0x32871a4303777114e0f17126567013d94bb2884ea22bf0a103d45fef47c4b005 +00074,0x8aacdeeec1021158c05056e5aa2ea4cc4994aa2372f5d37d22272ed065f7493d +00075,0x368ce2b13e74f99ef231825ba5df588d654ccaea62e0ff46d012b879608454d5 +00076,0x290a4131608502c9423b9ec4fdbb4cfdfa245ec92a571053702cb431d6d661ab +00077,0x5d736b0aecc493c6160872dbcc216816071483a4c4518a2284bbaad9a9c592c9 +00078,0x98ac3e9dfdd27556bf5d5e037d10de525ad1142c1e954de9cc3b7e2287dc9ca9 +00079,0x95e0734eb17b4182d2458e6f5268abbc75c44e743b5abeb775d99bfdb1d1f6a2 +00080,0xd778ae86ee6b3ed9f3f3dc83a5ece367faa9ea230daa21c07c54e073af83f2fe +00081,0x2089ffc8e635baaf3e1673f9ca3ed6d64b1dd02dd73aa5c2beb692af5363a1a1 +00082,0x382ac3bc7f5de4df286366863351ae1d3655fe5df7aa195e3f955e5cb4988bed +00083,0x5ab1cca211eb959107d5541a30d1b9f3e8a6fcf9935643acabd4f2dff8f3d212 +00084,0x9ec0497d2130e92ea521793e98774962fe83ebd994fcac4963cede93950efaaf +00085,0xf847bef9c0f4876906d74c0955d362175cc4d9bb83f134d60dad7bf3df6d0b3b +00086,0x0dd5eb92d78e345af8ac60db208207fe3f4621e5ea09f195da8c977418c358fb +00087,0xc0612d68f34fc28c18a095b0062d5762cf56d5c6554d94a0e97315ef262a4dd7 +00088,0x3f433e6334fa2b3d05edd615d92926aaec56b355f9375e3ea4b91ca0dd7c654d +00089,0x0432ee13cd0aab4c445219c8edcbf80bd502d11170a2724cabad19f55d8f2ad1 +00090,0xcf23b0c8c31f2368dc982efbf1220f64439b107d691450a3eb15dca1180f5854 +00091,0x9fbb0197fb4b50008c5feea2810b0336d38dba1958fafdb3482036e6ad269895 +00092,0xf88ab15fc925643c8adc5b3485f19240e4afc53dc777f0c9bf9ab5c6c6f3338b +00093,0xb7499b8c5bdb76c9a892b9e0d09cde7813ed0c38740d25743d02910f337c3c6a +00094,0x5c45bbb126771f6277dca461a28239b4efd388b55afe6ef1c6e595ea4ebd9509 +00095,0xa3dea11d2eef1db4c8855ae369918a0e12de5b99e0087e3af0105ceb1ed1e0a3 +00096,0x91ff33f7ed74652bdd22a154aeec0cf24542b29477122dc02704000ef15dd540 +00097,0x8e4ffd2bc8e767d8848b4d001c20a7dbf942fe73b20f6821a2abd586c8462334 +00098,0x4c5709afb1a85d25d9131fe5e441ad7f0d5d4608583c07836ff4cc2e3228a30d +00099,0xd55b92c14fec40d8ccf4fee501efecf9f71ced6d787eb3faaa4cd7050f3a3e08 +00100,0xbb39d00a031359e390914a91d9c26c1b8dff1b6d8ca4a44ebb64d5946a5451c0 +00101,0xe6df19425c17f10ef876e9964f7561bf3f7bc41fdca9151c26797f38e4a064e4 +00102,0x2aac9e21e2134958f6ebebe21acaa65142ccab41a0ca386aad4eb4c383b69145 +00103,0x3fe56c2aa4b33540147f05427b757a5ecfb57a4301a84022a0a26c57bd1f5b4b +00104,0xf3269b3047cc6b5dd1f38313ff3bcc717b44375148a8637e4ce41ec39a9adc57 +00105,0x6f2f86e801b6456e59b5f4c6d2587ca8e5cfd97fbf93dcbd11b7c3cf65b83170 +00106,0x621a252741c0cc84c5e7e3b01f90d30d86474348f44cc659ff48000093671bbd +00107,0xc3e8f7cdf2b7fd8a0ac98834d4ab1374e8aec4644fc722a04db5abd57329405c +00108,0xbe1a1635522e1529456595e0615c4d3c53905a0198ad65320c8ec1f7f3ec665b +00109,0x49424c3e48cdef7a00003a3ea76da66ce8f833df83f74580faacfa7cbff5dd28 +00110,0xaf29e604357c6c3d6f8a23c69ab648b8b19c0bac3e7e8ffcfe3d23f62c585490 +00111,0x1738246f2b0b1ba4a084cbe299233f487f3730d8ebcac38bc6cb43e503992248 +00112,0x0074a32e1420b57f8f7c142a61d5d945fa0df577c3007b375dc4412c46e774a0 +00113,0x56e191304d05e3370a821bf16ef43a7528b63105a03b425fb2c408ec21807233 +00114,0x10c2a569cfef2c20fbce1953dcabaa463cae1daf08e83a38322091fb1da59db0 +00115,0x26efb6b7b8a822fcfb126451c09491efa88a986bf3ee4f0bcbc7ff5610f051c1 +00116,0xbdf3bc6e520513ff3ca5382abbcfad7f2bc857db708233a07f17149d57d66648 +00117,0xe68e5334db9c4e799fdd67843038b909e231e8f5d248af1cb212907554ccc352 +00118,0x1c9a243765a53509f7ac091504edfdb27fe9e22f9766a7cfa02e0f87ba6774b5 +00119,0x5fc6b689c399c8151792427fa1e9b44c6453f520ea15ca643ec14cf1860b3397 +00120,0xcfefc65fab88cf757198c581e272c0e02d6488f4447b87dea8c908cbd8b3fdc6 +00121,0x0e29b6cdd3b4816acfbd104ca56b2ed140958c37fd4f7d9dbe5d62e1e7444e61 +00122,0xcddbda3fd6f764602c06803ff083dbfc73f2bb396df17a31e5457329b9a0f38d +00123,0x7717d3958ced7ec038af0b4d7daaaf2ab4da56290db865faaf96da59e9babf7b +00124,0x2e66a66a8ff5e15178ee8c9e500475b7badb71cc65d26dd6074e8faad109b427 +00125,0x82fdaab150f1a25c78a2a0253018fc5a83c420bfed8ec727f6c98e1571b39b6c +00126,0x427637ff154cc2036316442348c319c019515af54dd5a2c702527b87f6ea4611 +00127,0x65e302f1d26bca3ceb600bcc6c19190d2a5e9723a47a99e0710f4ea1fdf9a2f7 +00128,0x6fdc1fedc9d9454ed6b7f1067da89f57ee4c4e298767cebcf549b37c38b463e3 +00129,0xc8705b6e734dc09bff141a739eddafc9a3016ca7e7078a09439db7785fb4e688 +00130,0x650f1d51006a9afa156973b7080774340dbff7334f6d4941729ed1fd39f4bbd2 +00131,0x7b4435cab2538749da96316d2068854b40a8cc5eb4810155954acb70ab8eefec +00132,0x23bd760353974c8a41e410bb24b6aee32d19eb703692420d375da68ed5b8b4a9 +00133,0xc0faccfc19b41bb694cb86c86b88760dddc771125caff85b33ee5cf935f5106b +00134,0xec9cf3ec39f1bb33d363eda9d803fd63de89a5b4afeed17c9bb5185b784d4cc2 +00135,0x66f5486b3e5c79a9d9d10d4ac5581bf89b4068376bf05ced98455b7d50b08844 +00136,0xdc4ebb94b5007edaa6be31715620430cab85927af56ff7efcd8e5c4df5b2912d +00137,0x022982006526d25c7ee022373f4832c10fe42c7aa25b26044ee3f317b812c221 +00138,0x3d2314001a3de949f8cf44018b245fe6522bfe212ecae7b8e1676505d05c9905 +00139,0x5f31661180c2ee22f0f7209e38c1c2aea2fc03384aa0ea1f9d8b98cb0747ca5d +00140,0xf13c9fc08dd8e3fd03250091f66d0cebcad41cfb4330d6e68bf447863d2f8201 +00141,0x17dbb0e39329cd8b2bf6839de0722241211c8a602c233f48302e50d7e6aa6361 +00142,0xe42539c839845c3033143db80f7bd316ab323114554cca363c2f3ead3ed6a68d +00143,0x5594a813aaa2752040681086954b21e457ddc5a8f1d816b45925eb85ee7528ee +00144,0x5ac2296fd274fd53197c615a25b4fb6f4303b17a977954775f73e036981eb4f0 +00145,0x9244d418b8875cb5a463decd0f8cee235755222f2e72ad97810635975f6ffff8 +00146,0xaf9e7a53390b2fe7c833e937cdbf627a8ecb39da70260eda50ad0af37b4a2d1f +00147,0x1b6fa332dd5f6b04e3fb1a027b63f2513b4159035d3294b0212899649b61da2a +00148,0x39f0b0575eec3daa97f64b9bc538f841242003a72256fed04e015e78f72bb92d +00149,0x586c4a913ddb47e0cd4847637cccd2b458a09e35e10b29451febc5ce8f19f696 +00150,0x3ff89a4a288f9325e315b394c991680a5843acde1412d0539412363b08ee7c4d +00151,0xe322efe1b787fb583eed8d19ef06ac5660c014e566ba2541c160251273f8eaf5 +00152,0x4d9d0d1c39a4d03a8e4def8892d713c4c9c84df804bd2da90e20e596c99ff6f1 +00153,0x6b5702b39f5bde08d74649594e48ef49faf24a19c5d7ec75d8cf490157f4f201 +00154,0x13608c120fd377b160206bd5f9afe2ed660ecd8a121210faeaec26c9b6010975 +00155,0xd0bf6ce2d1f149196b41e2379831cd9e07d215a9da2be8a2b772be32a10b3f64 +00156,0xb8c3629c89fbf5c93a481688d05e108af37f4ca1152e2c1ce66de366db58e934 +00157,0x97351a9d18fe2307ffc128e294f580eb5c9c9f48fba6a5f4f25a0aa98d97fac8 +00158,0x5cee8f8c5f208a9d23dc367deb3c47e1b3e186bbdd94f2812ac27b40825de041 +00159,0xb92f84e91d955459a2de86bc28544a82ffaf23c6175f657f767303d63cf8b842 +00160,0x3e41d9f5b9538accaac888b49abc201aa3d71f5aa6c516a97e69314886989788 +00161,0x0736b99a2882a562bfd35db27b128a498711834107fd2c0356063b406ed8c804 +00162,0x0a1530daf01f3cddb2af69fc527b5f7635aab2d02adc46e5a21f8344eed9f7b3 +00163,0x43212d3b60bfcccb6b12bf765fd072f8785a7d41dca097e37ea14b7c8faf6d85 +00164,0x3744a01c5c7968e2230ec9d29de8a370db7f43763ef8f22f58cbbdf13f27eb1e +00165,0x3d14fc84c9f2dafa748275285205ae2b29df613c8f982d1f334d661b1511f8e2 +00166,0x97c2592527a83d1c2c514f447e8ae6fdb1481c0dc9c4a3f7212049c5eeae578d +00167,0x1148500252c17babbed0e2df0e3913dc380f7c0a06e680d4ba101748620660b4 +00168,0x88a365fabc60615ca56960314ae6006f61df6fe729a40341c12bb3c98045a4dc +00169,0xf18242e71a0c97722f01fbe9c462e0fe857d93a43f1d683fff9e36e4d3ad59df +00170,0xf03ea8ee5343e37601df81cc61173e6276516b1f69225a8c1a94fb079545957f +00171,0xbec8ccd9a6e13443a8e61a931138f3cf6218a2b477d11ef59a082f898796c439 +00172,0x34a4c5d21fc33c31b415829b9e46c63588db2327e3ee13682d52233108a2af25 +00173,0xe1ae6c812dc2ca1cb0613ab42e6c81721f96e771b13c79d284dacbb30c65e5aa +00174,0x727d10b81b790e7f5f608c35126fafc3523c7e991bfdb8ef018edbdd207b4c24 +00175,0x1bf21dcc47b8d4ed6511e49dfc4bc14c1f40f2c21464d52aba8b4a50c60e3b1f +00176,0xecc872aa4aa1c53bdc3c22687ed31f1373db111f1c1219286f857b157f6990b0 +00177,0x966bdbf23d2e86326afccf08377aac0067d485c6098d90c1c74a84b34b8eea3a +00178,0xb412f22cecb0219921846638c68908fbc2d73f3d2c7d32d7d86795e9f48c5145 +00179,0x09e40d3b668d4808509a521703734da066da50c303525314712713c5dbc6a2f2 +00180,0x8ce22357ac0066d519294b9ab476c222a2edf3cbcc4e06a2df0504ad11f5c1ca +00181,0xac1cf418529f5346213890d7f11ccf4a21e24023d40f2eaaa943606f8b7a1e6e +00182,0xf770e12a39d1ebfe34919a211fcedb2098ff562689be021bbfb8636f756c4b95 +00183,0x798224ae95fa5281f29cdd3ac9eb753ca8e9ee44b9cb2c5747f97c8d71917b58 +00184,0x876fdbe53a7831817a5e123f1b043700f1f3d47f685b772dded35c953d629e5a +00185,0x7b447a76548eb9c28145371f61831a2dc941acd907804808a7ab93f7c171d621 +00186,0xf1e11ac5a67e45142b1a1a13663c725f82a84d5e59ddf65f3b740dbd028b3d63 +00187,0xce8b009f996254d6df379dd2b3a5aba9dd1d3e0b64de28e5838b43f411f42e4b +00188,0xc7bd816d6d55b71c0f6784b2925ff9e1daf65bfb238fc1bb4980274130b500c9 +00189,0x144cc97d4bfc31469fec6de2cc4ab5556af13aa4b00b96081692ea64092c592d +00190,0xcbbcca518e96049a99aad9b53f2e579cf866d6c8fa3a69e407404a3508963394 +00191,0x3a7f648499e877f2451d3bb6f1e90e5e48ce653459849d52aef5b1f04bd7a9cb +00192,0x8a4639c3f8df41e06f4af80ecd6227823708c39128cd6a791e9ce390d9bcc7c9 +00193,0x52629553fb11ce8b1f53ad71c3ec8fa911ff6e0424b7c0a015922311888079d3 +00194,0xc4828a4b7616281c5e82ba47e691de8a9975512f0d9033b098082cf027e90236 +00195,0xf50a165e20e68aa37f97ead770fd9710ccb7b4fdc80581b5982f1d7a219feae8 +00196,0x5c31919b4d982bee212e5d30e35fc2998d946a0c124e54e3e2c27fbf8d129494 +00197,0x9e2a709b9953cd0e76df8b6f36d2cee961b24aa19ed11c6def3f5a1744c1755b +00198,0xc3e781bf3998d0fd70bdbdf8213e066bb31636039606d9763ab9449cf73ad5d1 +00199,0x20c05ee3e79b3ab76d806ae93d9cd01340ea68c007816dcedede0635df91850a +00200,0xdc265ad95ef9c500cecb8bf2a5da52b3f29d171aa981c8bd9ccbd6ccb7696e69 +00201,0x1356f2dabf963afe35b149a0de796d3e48f87bc41d9a516d4924854af52dd709 +00202,0x84e861144a0bfc933935e47097d963e8591a0f321cdb7ad1d75d899ca501df1e +00203,0xf2da7b50b32ed6bc786564ffc8e7b85ab250ec0eaa0096dea3faebfc9e07bdc7 +00204,0x7f42b43f0556b03846f18a12da581203682f8d2266fcd686b388970ea6229de5 +00205,0xafd08f8ec73d9a83ac8b099ba3202cda132e9e07e3dd18738dc4b5b1f0d98e93 +00206,0xcf4a2c657b1cf55f37167bf85a51ed104eac71967a98bd4c02a42dfc057c02a6 +00207,0x59a0e883c7a7087b9c330ae4703d0cf263eedd8d20466e313c894519235f5d44 +00208,0x3d0bbaf203bdf186daab82974347c617e1210a586751ec6c9818185d0a096e3f +00209,0xc1041285ee311030789717024ad66718f6184a03a0d31a1ce4ccb0948fa17dc5 +00210,0x1eb673abfb14d61c67d81d48dad2b7f72080a90fe090b6846779fb78046402ff +00211,0x01e5a4d0cf29ec996c00f168d445f55eb3552f213200a247c4efd60d4fceede4 +00212,0x83c3bb0ad1f3784c92a88909ab533c62dd5e7b3dcacbaf624ae95ee12022eb11 +00213,0x9a09fe68cd5dcdc15ea76f08eac7e2a679075e772064354c747b75e5ddca8d2f +00214,0x9e78dc12bf0023bdf0c8c1b8e7f7c6e5a92d66b56475594bfa334c129df58735 +00215,0xb02bf96a7443e246b6733270453b35a70ff1fcf49375cedc97338614ac65ac51 +00216,0x209c8b324d31fd9d8c8c4cf26f6506657608e6816471fe522adb1425b5ebd04d +00217,0x6c84f49aa1ae7943df31f340739b2b63df7476e87cf0ddf82862982456865c95 +00218,0xacb60f14bf4bdc96ce579f02f62f8bb35db16f03dde7329363bb50388c3c45b0 +00219,0x0a773645ba0627df6df44158e292f2f226ca74bbc90464ec4796ac2e9bf26578 +00220,0x76ed2324a565e51cf2a82bd0cdb025f255caf25d61396d4da19d708c40adcf92 +00221,0x76ddd2d829c12483b2ffec2c587557bc5972e08dc8866708a2d44a31575483d2 +00222,0x71e986b22213ce63d0e3df141581fca8fbfc41569f0bcd62c101c67cb00295b3 +00223,0xca2b5c289ff78be184a6cea0f072aa71cfe0977f18bbcca536b48938e5d64276 +00224,0xff571e13e54cdc9ca6facd7012051ee787bee1c52a555653fd969751bfaac7f2 +00225,0x1cfe32398c41e4ecdde6cff7b2df6f9f2651ee87aae1b52bc35e4d76f136c3a0 +00226,0xb0eb8f2f68728e48a4ded02891b9a682f7c925099e899c26143083850b3f2829 +00227,0x83556e9f3d0e05c0d4cd809cf1bcad1557bfeae027ac4de16e6956596e8309fc +00228,0x7651e7fbd8326e549f9af9122585f517c4f59ab6e735cd958888fb6f80f29db3 +00229,0x238ed7884113c0356cf4e5ef35e05434d3e076428884b93bbb873ac30afef54d +00230,0x3826affaf4ebf5817b453c54c937951770c19ddb7900c9a7742919c24242f6b0 +00231,0xb81f93c6179db089673e919d91660274e96f240a699a12a140185c69ac19b674 +00232,0x0cda2a75d5dd4059a2e5712ac7cb151f033b700995e93c0819f38cb01b7f005e +00233,0xb183167b3a03238701597a198475ccec1308e2c55babbe5d5acb92fcd694fa21 +00234,0x4a88300d556d8a8d66669f2d2b395263ded44d9a86bd45b3b426a55f7da8eb22 +00235,0x05ef61436ee159233c382043f0a9e99d34ed88a0bf3c12244f546b7b861b9f5f +00236,0x4164fdf451a7134e2faa3672aa40a0168e2a16895020c0cd5632322793fc96d1 +00237,0xd5c9eed4c1796793e8595d155187444376f4b5478ea5ff1804f1ba06bd328506 +00238,0xdb0d90c5045dec94b87c81a03fb985a6fb84e1debb372b56c2513f25d4a2d8f8 +00239,0xa0c972ed0270d34b19b803a74649470307f138ef0567df85ef53a862b383dbdd +00240,0x9cc1a86a28230bad01981b644067885e0333588976edef464aac674744c9eed9 +00241,0x8ab5ad435e4c9a37815b47344d282c90a3f364d516374b4b2158cf16148d79de +00242,0x491f232e15a8a44b1f045dc68552543672c6d3bff361a5fecd7c0a54c1f21d2f +00243,0xf66eb348a6b9dd916baf6bbab3299c57b9d95e5bfb585893f2953209c2c451e8 +00244,0x7b141f131b2878edbef5e71682051e3082490e755502c0372e5ace9cb5ea3d5b +00245,0xef5b96a583318ef2d24bde313396aa09dd5d102cbd270b95c036bc6db98349a5 +00246,0x32d63aa14065862ce43f33e578625a2892710dd11025a9299f8722421c625874 +00247,0x7b033a6c76470c8b7b953161d562fe30c90705672f950a176de70a6aa5f1b130 +00248,0x50916052436d167fa83998749a703038ddb08d7cc789c276099235f9af28a613 +00249,0x75e0db34d48e90e80705be01c100e3767aa3302d4269a00f4c944069ea451ccf +00250,0x4781ac7f896d2a547f2a973fdd352d5e9efb019939bd10ab31f0f84887968831 +00251,0xc0f8b33bf4828ab6578b5312d922b37139bf9c1d0eddd973f5ee84b39af48a28 +00252,0xafa72ca222af4feacee96c6a64a4b05a1fe464f9ed48e93e13cdb096d0147d25 +00253,0x96c6ccb34878fb040117b6933c7d7f1ca4f534dc63ab86d2cc4914b06786331a +00254,0x7b32050e8240cfbf7ab11e4b06647d363c83aafa32d78cf34460b335d0e55a3c +00255,0x16317cf915089e0c7cc1afb35540a004fa2c79e75f4410dbd89e6d9fdb2b89e1 +00256,0xb4ccb50be9c8f0759450e6dd9d05cb16778cc2852c0f8aaaeaa118a45267891b +00257,0x98808d165ea3e628d92a93cfb1081e68254c4e2a48eea8c1cb3771772ee0fa74 +00258,0x3cf61b1ca697e63092bcbaafad3cf25608f47a9b6563bf8dc1720eb2a7fbe384 +00259,0x051764d24d14c62f71e8df8e9eda01d4edba8a9a52cf50ed50dce0d06f33bbeb +00260,0x3b0545e8512ad0ef40623a237e1461577102fb2d6aa820dc0a9420d62f1a5942 +00261,0xa6f4bfcafda2d4cfc8bc900a5f844d60a50822aff332f7aadec3157b12a8d1ba +00262,0x1a75662f7da5af8abe9f73deddfdbc4fa23772f28a2968eb44dab1e413238841 +00263,0x21bf7eeeff2979facb0c0a59ebfe07e4f110c9f7417217a341039ae2deb4c6d7 +00264,0xd41eb83d2e64d9928f6c18e95060bca40c3226b4982f91dc97a518201aac8fb2 +00265,0xe7a1956113e4b4c440a7ca46855ad2d2705ee3c018770e3fa8f8a3b3a6b6d6a9 +00266,0x4f172aab43c6bec97adf68392b12e82b4512ebc52df0298ce3253672fe59135b +00267,0x7c0e1bcfc2aaa6ae002a1bc3fe0ed288598013b4c0dbce889d4b41cc8f1c792b +00268,0xc839e6d47fa99f7bab58ca9eea51d6306873f67fd286ddeca8348a09c773cc42 +00269,0x9ec52dfb6facec401f848cee38bd6eda4e3429291939754a4985eb8ae969787d +00270,0x4e8bc7277defdbc8c904f780c9b6f82c214816b5379e95490c7f0052a7295465 +00271,0x5294c75dc9cdf4c43f683b6c02c9078852607faf9dec990339b74476e0c0108b +00272,0x02a11db25d807b03efafe32a0ee0647b35d47506a7fac186bb51e3c3a77a5655 +00273,0xd81a2c4138adf6e8b1af325a9a0b08ce6a0b3b72a79b367118294bafb4b832e9 +00274,0x9c4bd87dc1b25b83302973a9c4223cda44c1200ea2a83106463adf6317bdc605 +00275,0x85b9c67dc6b5b7c0014824f8b1909633459cd0b8e1584753064f85e1a1243c8a +00276,0x38cc12366c2a7d559e4df0705bb822d8d0db59221de71477dfcab90e317b2e97 +00277,0x40c70f952d1ecfafbd064b1367045570b703fdbc7059cc7f9194ed34794d1db6 +00278,0xd9e0d7381580a9f3fa81e7a8f582967f09e1e87f0e4c5d08221edf0434053608 +00279,0xd20a7b7f9138afec7ab17bcc1fa4d77571d78f12bac193db64cbe046d0bcd1e6 +00280,0x54a85faaf00ddd99bf86faab4ddbd028b8d3f4e8f4492d1c7160aad9a03db638 +00281,0xf08b974956e8b7c14b335bf82add248bdf06a9626ecd6627ae0cc523359cad9f +00282,0xa5912776593b35ee8dbca404e0c36497dc410062c0e5f4c6b40923232b17a8ab +00283,0x8ee7ec35fab36575d9e5105303fa547ca8a03b6ecf731cbb64b9823250323d25 +00284,0x374996f2ff5de9c6262168bc93fe7548bc6cb94d45dd4dcce211a9be677ddcfd +00285,0x9494258571f7dda74ed018ffed536e412f5272028442ce932677668613278035 +00286,0x6d47a23492f0ec9831f3536b4b542b1addaa041ab9f9cb6d2f6821a5f9ed6646 +00287,0xf9804151a4dbbe0c86e08b2109fc328a287ea4ac10abfbe01a9bcc866e7422b5 +00288,0x3724a8c948c728a89eb03af19c3be5e7e26abde6713e6e9ab5559dd21f8e095e +00289,0x60d72bd902aef520fa3a0fd618cc230a50c8cd3951042f5a613b3d45f0b94c6d +00290,0x64cca80b0eb18b315b2213ad5e2b53dfcbb1141ffa422ad46e7cb3586a200aeb +00291,0x0dfa92f2d0ff334ed8306b33e6d3325720cc13aa0f046d53a2de144d89b9af92 +00292,0x9490598864a1e3ce2241136637de020cf275921f59545dbc4ecf4cf87f678b84 +00293,0x0d6c5812bd1b877d8715198580c66eab1ddaa78e1dc350e70eba0d59e633cf30 +00294,0xf6c5c94a2006aa624d007104ed8debbb32ec15423382e4759bc7a16a1357d5ed +00295,0x4efa78d05a58e9b1e633443b058c9f8d447728e0ad64a50332f848199f8a4253 +00296,0x81c1446a12d42c3ce40f4a99326cf8e5a306ab72c773ac26f63a63cbe0a58064 +00297,0x08d13a3189fb2e18636d6beadbc137a79d03d9278c60f80829443348b8c560a4 +00298,0x3d1d6d89bcfb495fccee7bb0bd8f04715d84abe14f94fb36f870e5606c2cdf18 +00299,0x23728d43eeafdcff8f761c5a53e3f9373d25d17efb28347a91938484e03d07cf +00300,0xde0332534e50154c9eac98068e56da4508d82ecf24ca3a275aeef3dee99b95e0 +00301,0x15a24df990de83affd9aa7cd9e67f4c558e1b3f306a6281385cc2e6409b9793a +00302,0xba653536adb3464fdd46fe741d7daa1514a84f7555bf7ed91cb4d3bddc0a6f1b +00303,0x35fde006dd9552f56250125ce80ad21476daf78f8727b432cdb370372c161a65 +00304,0x377bf395fc2a3ef98595766247a1c057a05d5fd3629bfd27d0bede0c6183a7f1 +00305,0x340a0b81056d5170e635ef43d952b8ec4ff7f3d5cf4ea1469750448d78f3e501 +00306,0x848e3d92711946156cd7c848947d2ba4ee4c0b39087ea30c90eb1e64f8aba773 +00307,0xa3ff791642f87c2bffb269a1da3d8e943a1828cafe10ea7a483a508f78ab54e6 +00308,0x48c7160cbf3a38ea7299edf971711e9d6875969dd38ce2086763389d9fac048c +00309,0xe7948131b78ed9f05c0e18ff0497a192aaf8c5d3c1a56e1096570b3b45117253 +00310,0xdb22eaaf717a1a827a085d3960e2a477a2e9a73584bc4a293377ac50a492350f +00311,0xf9e4fff98d04206dd4004f5ec146e676327dc8399dff7c7eb61d1d80f706d3ea +00312,0xd95903d02e93dc935ce569153d9c88680972dd5e9156dc0a7f4da9a3435ff004 +00313,0x73f91876f19025335210705149eac61825673f8698bcf5aae285c00051fd6f6c +00314,0x8e3397949f833d550ca3a268befa4c48c238f488572b2512f8cb5232d78dde24 +00315,0xe83123f07d6e146998f885c5c4f71988f472b9769e9c731d421327f3f4add351 +00316,0xe49c7af7a328992fb98e65057e28326f3684f84293a6b9825ef8297fb361a186 +00317,0xf3ae6a628ac464fc0f14f4654dedf31ab553c9750bbbc801e395ac858bbb619f +00318,0x4bf5c84ae3ef17b5fb6455380d4708dba2da9c9224c4a31a0cb14ed4e8eb17f0 +00319,0x391837c44adbebf55ee138d56c65353612b31c66f1cc02663b7f088b80dde22f +00320,0xbfd4677eb2bd0210ee172956700adfcf8b5164982b533a191907f62ac3f6ae1e +00321,0x7189f4963254c00f349ebdb7f507638472c13e083cc525be744de2ce8374e1e9 +00322,0x344663aa7240ee9c312f31e5111dcb672451ef971ec1375fb8a298c676738c7f +00323,0xe111bfc2e481e928c91b0d0a5868221c8699e22fbe87852b3bedb3124072659a +00324,0xbe2b4b22f7c8c897ba0731eb6342e075c338b8feb2791c31be1d20c6c47f167d +00325,0x441fdc4402e5b407058b634523f6318e2b6ac078414720bda9466129896e19c4 +00326,0x4297936031236c915aed0b391555294f1df7b346889ca02edd1313b8fbd73298 +00327,0x820afe74538d0b05b98e1d16604fb60bca79f04c56fa724e6d2af5532a5b45e1 +00328,0x08665862041221b6d297f4e7619b1044eadbdb92ec1415e916e9bc78558aafca +00329,0xcc85d0d955b9068c848b56435b53e7eef8d2a1266cfd92c46544594a1b7c06fc +00330,0x8ffabe96ffed7125caf2395331a37eeeaa016c1fbd0af6ddbaaeaa4ce3a75428 +00331,0x57c9aa448a060ee1cbe8a7b5236ef301c090d29baa0f644ccb23661b7933b4df +00332,0x3135b7344e51ce37b6f82ad0e1ab5dde01a7cbf154ec76ae394c6e99fa866e68 +00333,0xef368f009534af83848b1ad36c874d1cd28cbf792663db122dd8f7f123506966 +00334,0x1c3457cf9b7bde27ad51086fb1ea494d78e82217cf2477f79ac8fc4cfa610f25 +00335,0xb191a95efc41af23eaf794aea75d4b4c9308a85647f6793201533b30b3d9d368 +00336,0xb5318d5c8c6f173084a7d838110e3e3de8739123b4ec387658c0b579cb87fcec +00337,0xa84d51fe94498ad9c2f558ad6fe685d9aa73ef5ab52c794861277e690ff27d65 +00338,0xf0b5744f941d4eea8fa255edaa9f7af5028da4900c7fd0b2a1214b00c33f96fb +00339,0x5a637c4c3cebacbb0caf5c8bb9080288270e8f2ad3106e50ce82a65bc27386a5 +00340,0x6bd16b95991a8cfb3671511c673093106b4aa7d626edd4558bc58ca67f8054c1 +00341,0xe0d9d5cba01b6dc8c430de66d0503e58b9be6195e7a767fc26e15277af7a08fa +00342,0x203bc599777747671b50d1ddcc78edc4a180537d2e6fe14610426772d1caf926 +00343,0xa668f92ec27ced688ad1ce7eeb4f437996bdc213ab001f5d548f5e283f243754 +00344,0x9cfd6013d6c92d918e19c4b6118dcf5d73e9070af0c7300f8db0ccc7fef5e89a +00345,0x54595ee743dc095ed8c3a82f1c0ae34ab2ef7ebb494286a990be0f6b9e85e6a8 +00346,0x2297e35e02ef969b43a787aa88feb7e101a21fb5d73a81af1c4bc06c57a7c3bf +00347,0xdb8912b310472c79894387c19d79d84113709d05057c043380ec4ad8145991fc +00348,0x1dde5ab9d554e74a5635f8042ccee5454b215eb598cfbf696a74a459fc1ec87f +00349,0x7e25d7fe6b0e71c03d401537f46ea1628e91513cc3991171227d6ec165058e2e +00350,0x2bce5715759f8e6f9f17a735408e410f9965ac3cfd27e2c710060f3778d662b2 +00351,0x112b61e1ad4e349919eadac971bb9128d385eb3f51668b2895cb978f148a83f2 +00352,0x2ffd764d428f87651d62f1a1113874042f1c77dee8b999524e896663e1a0e000 +00353,0x8d5ed81a06d6bb19866099c16d80a7dfe3ebf9c642236410a5f3f491fabab7b8 +00354,0x78c57cc6fa8c8eaee7bef3b0573faacf9a42783f39c9a307a3cebd4a66a56e37 +00355,0x55973475ad5f1404bca12aec3688d80cb5881796a9d0a9a917245f8ed9bed47b +00356,0xc7493a6e7fcfb05ceb9f11b9af843556bea9f87883a2ee21ee76cbbb769204fb +00357,0xe5dd91711b000ce8cd41d02ec760a50625f924fcf7a095353f6965322881fb94 +00358,0x60ed8451fe763621afb94803cbec04b48e9ab83c8d05e2ec1524e623dbe0decb +00359,0xeeb9573da28cde717ede462163188da0c184c4aa61e166e9bc4ee047fa0c170b +00360,0x277ba2fed1fae84aa2b23a43872100f00b7699326a22df5679115b1dd88c5206 +00361,0xfc97c47f7bf57fce450809d63a32e255db170aa3fbc94c88d9b15a09f22e2f8f +00362,0x77f810e72a7d1aa4a164ba9f7bf0164b6f14842dda65d584508d7f403942c319 +00363,0x056ef66ff214f7a777abda23d7c32c1ed17e2d25f3e5e4299e11c22412bfb1df +00364,0x374faafad27fc139a45b9a73cb5957de978227d494de6cbe4d9bb4d48fc26197 +00365,0xa959566e36f4790873b779f74d0b31b5c08b4177e844e430fee9c33c190839c2 +00366,0x905c4a521e63de87fdd413379e245a1c8c2aafd1cf92e5ed6394892a635e62a9 +00367,0xed4e7dab8d5ac5eb9d4e3b711be5a5074eaceee1936455fc145362871d64faae +00368,0xb4a84335f5900e1df9ffd45af119abb6808b69960359257826702a0792dbb9c9 +00369,0x1f3be8331532a43391f286dce1908e750c2c1db4f40e04240df8a49b15077ffe +00370,0xccf6672e6da5a00cd8ce25a1dcd7ac9701d10e13db51b249cec8a168fbc1fad3 +00371,0x1aa762ac08985e6a081e59742827fdcaa0194f37db5a03574bea395a548c1ae8 +00372,0x05d7f23c6cb10f2e5ea143504193e0c18799879225cc7bb9f548c2a7bca406a5 +00373,0x9a8322055f128164d9b1ae8be520dabd5aa9a78e6b38887d2d0ef1c29f8fe5fb +00374,0xdab73b8e1681ad78f5948c11596f320dc9e37833a372a4bb75131ae27144789d +00375,0xe97d6f9f8cf09791cfa7d844116e30f30c0c25a010500db0721e1a0794a0f0bd +00376,0x6af73957e98a3366086abd58c1d750803706d7bc3ae2bbbab4eb6030d58cb244 +00377,0xfa0bd020aa5cff144e0c34ec5a67a63cd593c607905dfd7a8697796a7641385d +00378,0x85b101eb40a52a559a3bffc4667c2fa220ad9cacca9a34c62c684e87cafa5e56 +00379,0xfbe01c0b7b7e3e3434a5a4723c3619f544c6fc91324421172c74b3aceb816f39 +00380,0x3e90265a2de6ab0f66324c687364be3c3a4bf46b96fb5dedc4da99c2a59c66f2 +00381,0x0b316492b1f48b2a578bf289dbfdcfeccc756410f0260e2b14b8b2bf972ab173 +00382,0xa02e585dc76ee230753d64e6f49d31f6c785e03834bba8acc2fe3f97b2b0de67 +00383,0x2198573b3c6f4e37218236277eb87d39d60646c6a46b7f516de4ee75f7eb57cd +00384,0x0c367f630c9a45d6320139277a8d2f880118a31a856daea875c5a095986f50fa +00385,0x8893c8da5a5e2df4e794962fd80bf6d4b8785de5ec445115f1851f601d92afc0 +00386,0x30637c5e41cbd7671b1b2744d5abde33576904c2fb999de2262dde69d552b4e5 +00387,0x069b5e283383b315d1a151162386e05161a9ae0704c2b5d3162d18fe91445c14 +00388,0x82890633807a55f66db32bbfbc7eddec26666cf69d927c6ec17d3e52839f3d3e +00389,0xdef916eb755fd6d271775e79079003b9851e520c744dc2fc544599069a2f9a2b +00390,0x00f646779628de768f0a78b66f79310092a7eed1b1f42d871bc14945b31c4dab +00391,0x6055482350dcadf13a115468db04f05b533177f9cb92ce0d1174e80cf72ffe92 +00392,0x01eb08ec62a30cb0bc16493c077396adcf2921cf45e7fe07f8ad8a9eb3cb2486 +00393,0xa5b5b2ed61c5a22e51f28e7081d3c57657bfe1ee7ca90ba380e21b0c29bb871d +00394,0xc96f2c65a9b708e26fb06146840df2ba2fee86811fc64b8b03cb8da0e864cf21 +00395,0xc7c791690e0a24e565ad4325f0916eacd1472c5c67ed9d08007f519ab5ea4751 +00396,0x98f01c73bc56a14d597f9a2fc522c1f9ce473d5aebcf9f025bf85e10ab5e69b2 +00397,0xece428f5e482195f4fc650d8ba4535cdc50da4bbd6daff83dabf40f0fc1cb264 +00398,0x15d52476e016b06a31965a6f867703d8e72de4d75952ea588619e24d16946860 +00399,0x07f402789b0a04c5c653605ae4a4d9b538575eb278790ee1fca13e1f47aa85a4 +00400,0x837a78da3c31e197110da75373e9161ec3630eac20956d4976bfdfe5a3f76705 +00401,0xf319bb85477c7540c8296e257ae3e9887477cc5ce6615e79ff465e67447ef449 +00402,0x28918ded462955d7564a1cf7515dcde37e47a0bf649af47ce19c1bd2f42420f2 +00403,0x8d3e10d5ddb059e88145c8a640d6f435b50abf014464ef4112bb7153172e8712 +00404,0x729d063ef003bc0cd25960f423adc378a96f94bf330e2894980e229c7f792827 +00405,0x3857def7fbba5ea6f0330f98e7810ff7efec3dec752c7a72961925ebb55935ab +00406,0x7be7d5cd302192b0891e799f7fd3dc6214225bac396740ca00eab0987afa0e15 +00407,0x0a5da5b2bd5353f6dfccb3173ffc30d765f1abae1eb3fe1a2ba70a4c9e69144c +00408,0x4ef48eb40d14a101421b182a44e62e46058b24a968731f9672658c2998359339 +00409,0xe4148ff741b9ad3ceebc501e8db8796f923b39918bc4e003164b490a0b61d9a7 +00410,0xb195d1d07cd0b541bde741b4086345048fc40eba5c36958db1e84b72f813f9ce +00411,0xab2766df14efa74b0e28bb35708e39d6b1ca1d0bca5a94ef65b5aedfb53bb200 +00412,0x4fcf3d8ce7b02562b9f72decca131bda4095b44bff685e901c1a5b5d29ad1bdb +00413,0x371970b092f836d650467a8ce9b049da8e286f73b4ef1063380be6ec1c07622a +00414,0x7525f2eda283e525441c353da10bdc982c0b1ff04dea2c153b3543fdad000b73 +00415,0x4820498a2f344d87b28241909d366f5be00766e75b23645c45a09c75ec8dfdb4 +00416,0x55dcafa7fd60cb0110e64c6d5cc69db5f031a572e110368f9067151b0890a0f6 +00417,0x9a836ceab0f6c37b3523b9df29cd0434d420819221ef1063600765b3ca5f522f +00418,0xc524844779cb06e98494028130b971a762f7e249dd1d79e08acfc33d7927aae8 +00419,0xaa00e84454c9ec2852bedc300676f8d20bda558c13442ec8b9a148fbe5d37098 +00420,0x1a718263b17245356ffb42bb178e9590283ea2e0a82ff52dab5f904da8951895 +00421,0xb7a7719554eabde85fa9f5bac7580c6f352f60a460f9a07fbe87fff47ba7c19d +00422,0x05e01b82ba2d8b2fda2a7e149186ae56e933298b9251269a4e2eab1717f44fda +00423,0x0c5c203528a51dc0cc9a0852cea64ed0debab06b3ac95d012870589a5ae4c0a0 +00424,0x7d31cd1ad7743f0c08549c8aba82c3914de61f8637f768725812dae0be1c3cf5 +00425,0x737fc2002808f4c81dbad877b69160a9ebdc3f8382b5e1f2f08defce897857ab +00426,0xb042cd22b27a2d46775de19a0fe07ea0187139b69a8a5f9f8ad680b49a50e81c +00427,0xa5f8fadbaf1e1b1c025e9ca7646d214d84afa0d2575026bfd188492553ad2dc9 +00428,0x2247adf42e4fabead0c52c18fd8d9c3d378b6a82dc3941e9f2e7c03a3e6a5316 +00429,0x1cae28d5c467521d0a2986ae1ab697c0137fb88a2cd57b7b65e1087002f4ca8b +00430,0xab59cee6f8c573ce2e2abac2865d1590cdcc0e4289aa75144582810327d2bffd +00431,0xed24090f25bc8dca7749c25f4d6a81a6c0421251b40e9fefaaf7896a49e1cec8 +00432,0xecfb2f473b32475d203492960f9c706024ad7be82ced8dd0f9506c2cedf3b29f +00433,0xea10cb3faf85fe26801f5c5c6f963aa09936d48cc6070abdc86ef7c1ab93eb6b +00434,0xed8823c84177d8ffabf104566f313a2b2a43d05304ba6c74c2f5555bae0ef329 +00435,0x1acee0de8d8fa5a692ca7fe4e6e6b6070264bbce1d27bae29aa96794a92fffaf +00436,0xc3510bf4ec6f2561e65ef90ac5f69719835bd88ebc526470a11645a2c743696f +00437,0xf2dcc620fcc9352d6e87c27c30f9dcbc38e05c66d4cc315a6b04b3007234821b +00438,0x00f5e21daa244de11bbc15728bcda77c7c15fd858252459ad7c10c0ac877ae9c +00439,0x5149508dee482fd1927f619b3984641ee6a4cd545e763475d97a759cdd6b9ce4 +00440,0x9feb91891bf0aa0981ae9b6d8a71dbec00cc4a2ebf9a94a0aecc1815d621b2c1 +00441,0x3f1832caadae9d68b7056679e7e36db138a48754d0bd69f0f7c369ecfff7763c +00442,0x1d30de4aac58ef2504ba7fca3cdc0536a6129314efcf91c713578bebd2182e6f +00443,0xea71b6f9916c2fe3cee071ccbbf4105935e111b40d71ecc3b327ae5a992a6d49 +00444,0xc56da958661c206315768f8f855721cce15e24ff1f350b294a1331eb29db56e2 +00445,0x02cff3d78ac49a70b6466ab49a54dd2695b8ae3a423b9e52dae2351864ad4e4d +00446,0x2280f1cf6ebfeddf1211be1d8801bb188f0afb1626da2921ee603ede2bbcf926 +00447,0x3cff32e3d7dbda7c7efec80b3c9ceaf9c56b9d5d0c03b53cd12897c0ecb8a59a +00448,0x7dd2c4f161ae53d17ee1bce79c6dc3a848fabc81c2ed01d08d768e02c7ae8b19 +00449,0x6d1d274b948411de02b87258045266f96be9a450a363da2482a1219aecf586cf +00450,0x2b5e114981c6f32c8a3b78fa35ce6132d9ca9b597dd94ffd91b77657f5e51be2 +00451,0x4abe0e076ff522ec7b0eaf0d6751f9dfb7f164b42864e0255f1502a77315178c +00452,0x42606107511944b1c7dc61fd2d3467fc43128e69092df1eef47479dbca67f3e8 +00453,0x23cdebe00f8b0071fe04101936e236e3dcb4e58b94a8101a0f449ec38aaf53b2 +00454,0xb2b5e5f97f7552d912156e250165b87cf670d32260186a1a41c47bd53e4b7f51 +00455,0x54943c8b31b13a4f0cc4f3472967383de372b4ca8f89979f6043d44ae330888b +00456,0xcab079083dd2ddc43386c219d265ed110b97d315943e37e859764ddb5c380a2c +00457,0x82d06ed1ec9bfb436ed64caeb0a1c99efdc719d79167ec9600fed7802c5cb1ba +00458,0x2bff3cd79eed0180444dfcbfb8fb93579be52e5d0eb92fcd3ae6c70702a93254 +00459,0x29e03017ed0f32215c0705d87beff1ecde7afc804217ec41c250a0541e71dd67 +00460,0x6f2ddb12b11f17f35b123ca3692ac57b18043af935e33eb2f662fa0fe862a866 +00461,0x86535bae04792f1724aabb2201189ef0b12ca7624e1e9fd296d129d3ef1f74f7 +00462,0x3658342ed3dba9eedabc93cae0d6cc657bedef4d1dc6c631113af874dd65fb64 +00463,0x4f586d74db2e09c1ddb553421304a352ae8ca4dfcdd49cb9905c83184cd1050d +00464,0x2da57d6c84f0f2de638453005d496136fac3d1a4957f0e6a8aca32070522c965 +00465,0xafdd52d62167b3f4a6e0c88d5bd5fffd1f4fa06a528e52f2cf3a095cf5f84fea +00466,0x21cf05fbe816d55dc025ddc38f55aa7e66bcdb98ccff8abfd031c0832f69dd62 +00467,0x27685b9d5efe40fe088b50b9a1ea62e8dadeb0425171ad45e6bcc3c283af2acf +00468,0x610466b6f8c2771439da2e8a7343c8d961a040e3bbc73ca6c661e4a13f977132 +00469,0x8c5751e2b93bc6f0ddffd243332a890e3794bb3de71a80ca45c95b971be88167 +00470,0x2e445b03b86127fe3149c740429382afdd2d0bd2e1ff0b1f05ece2e23470017c +00471,0x7f37562302193a70baf1096ce39a616be3737721795d7a106ca321593f29af71 +00472,0x5f279db60b9c122ef92a239345b84ae0d9d6ab6399ef756e89078c9ded3df15c +00473,0x5ae48eaec56b9a49cbb966ec90af455eaa03ee66604e50195cc6ca4dc3f0e1b6 +00474,0x8b70d9c82bf64392306a74b2075f1218f3e25ff143962e2c63d0300437bd9794 +00475,0xa8e53747848b2eee9050ce20905f07d99282ae9a35ce825ea1b7faf09677a468 +00476,0xdd34a7c17094183961aa4c17d9cd6e2e73daeac22f27af1f0d948772d9727e11 +00477,0x488d852ffe678ca5d7fd3b4f04afeb893595b929c6a968c2b8e6ff7204be27bd +00478,0x232a4fc9a0cf3b37008375f24a562c44e25a0f54774e2384db37ea0acc0b599f +00479,0x4b082f2481b4819595dba7d5f02505e200b32e78c59100241de37b51720217e1 +00480,0xb54b802e1b7923c298d222ff23b5f0d1c8b76b886c764b517a1e29bd4801ebe0 +00481,0x213ae81b453ef36e78b560492832c28c71db8bbb5d12816cf0477c16155ab8d6 +00482,0x5d09d6eed5b020f1268016d5117587d519d1aaea97b575c6ab24a85135daab13 +00483,0xf3c11c6e063ba5b267f6616529b2495424a633e08f6a78bedaa660496914ca81 +00484,0xcdc41b84ddcf6530555d2fd03651ca3fcc29981f4b9df53944efe410442174c4 +00485,0xb26f2e53df52942461b1c54800e6eb25858b1d86f9bee68c40b8f13ca1fb44bd +00486,0x82b8c438d8704a976289eb09500c628a3c07ceaca62d081de94e345d14bf58af +00487,0xd834f157ce0cabf68f199cabbda6fe5a47256b25acbfaabd376ee9d28d2366c3 +00488,0xfa3989a5ba10e3c27731de69a30136ee3ea9e603cb27d12e2a5f32afa60ddada +00489,0x4db390c5cb4c32c03d7f9cd7b8823b700e9d64da825194b83e3df46ce5751864 +00490,0xb9ad2e4d9c6627f63d60befc8778777c829594a044f464f12956c904486f7691 +00491,0x6aa98f9f56f6ef66ad09f15071de716f61e203ab7a31a98737fd5c46649a14e2 +00492,0xebdcd70d9e477a11b4fc48d3258dd5bcf6c9222db25dfef74dff86487714b798 +00493,0x3079f6253e59035a7e4a039275e685c9017d7e1055252fcc7db8c4a5c9bac205 +00494,0x33f97b590b8f704670771f738f9df52e2037a876fb185f0cecb89fba754af618 +00495,0xee3904aea19ec5886c2f52956576a8e81fa4b2bacc4464257c1dc3190d6694bb +00496,0xcdf13c18466bff16c454c4548995f6d11eb639ebfe71dc793b648066cbb23cb7 +00497,0x27f7ad957db315648dae2007f3c0c8d7ee81a6c7c3cba09119091325e7ffbf9b +00498,0xfed48beb69c269ece25dd3b123aae953c66433728e03370df36a76624736b61f +00499,0xd9c9a7333aded4d0f68412484ca0032f348c55ce9ecf21c986d22855625b3ba3 +00500,0xb11653db38e95638077c58252fa5695f38b933a229decc1bf3d1dd124c0d5f00 +00501,0xb202cc73bfc03b7f9f584614f21533221cbd0acc95409239090ddc52b5f27d9a +00502,0x19ef7cc080401251d654b9529fe8018fb1bc1a58cc6b99e8a5a47a40872c5955 +00503,0x45f20620961362cc0f7f6e4f3fe15312150eb015de00fe77f6730383c79b9688 +00504,0x21e3a8f27e2686892a5cf54955dbf7509feb97114352d211efa8573dc344245d +00505,0x6dd1ba5667a00e35a95d075c187344e3dd341c0b96e9d7c686b1cf8768e2d4ad +00506,0xc0414076dded3d476fba3387ed8b0eb57402f1017dbd117dfaa64eebeb162f24 +00507,0xa7340f2eaab8704157b80028c86a7f0cb1fef4864da34554f08dfcb614cf4955 +00508,0xdde4c38d485ca458dcaf7dd54cbd451ee8c9eeae251d59b2f5fa6faa97280a14 +00509,0xfa5dc42a17a4f780caf728dfc049b9fd56455f05e2ea06202c763ec143b9fd6f +00510,0xea2b8d47198cfdc653a2136b98df5615aee70388df0c64eb5cfb90cacd50a931 +00511,0xd5d2416f6a00df2713ec8fa6cc13ef973d1eb9d900d852903fe1046633599565 +00512,0xe2918e5026ffd68825dd25cad6ed824a9ab0a4fa4b85a35c4ecf4ef8e0544d08 +00513,0xd39eefadcb758f4e3c4e4b34eef2e976c6a3959432abcebdfc78d06bcc3148d4 +00514,0x8bd8f6bdf0226ae2173194ea147c71af760a5c0c661ff1f5ad7cac137b1b6d83 +00515,0x66d4642ecbc838dc65765a4fcecd474b20b9ae0637244181a84bb373b13d5601 +00516,0xed3b11872cdaf7b8feb4ba80cc6635e2123473ceec8e939eb46471c70872bb97 +00517,0x5ef487b21fd4c9f018e1c42787966f14f32ed2e1581fd159ea1e4259a6d73cc8 +00518,0x710270293ed9c587e43e725361f93c98be4769eace47c2016e4189ef59c5b7e4 +00519,0x218c3b62dc99a297a595e41cca22f5f8535ff99908dc03940c9e4a855104b61f +00520,0x062e17197c2a5da9db37319b5a50917706cbb5b2f94436f231515944f5a533af +00521,0x5b55367f4c641c3f847e97b9507772f3defe8e7a7b7e7ba7485a5350838e1786 +00522,0xdbca1ed318fb0b730386df7aa1e3093735b7579852cfc869c4ef4bc80cdd6564 +00523,0x297cf9d5925da0389d57e13787de1938ca0efbc4fdf2683d957e86f076191df4 +00524,0xf389f3b6336ac065daf31616b7dad80bf6e725ffa95b57da3cea36466c04fa47 +00525,0xd851e82289f5aeca6786aab0281c156e6e75cce90fb8689cbbbc6cff69f034bd +00526,0xc69972a185d32c7419238da9577424406252b97d93001e401d8649fe6991809c +00527,0x2c103256a2b901f09cd43ae21da8743d4b7c8e5c925d98a67de5579de1d89630 +00528,0x32a674ae21d37007a12f57639d299bd71d378c127c3b5bf80d9b7b72f8a89800 +00529,0x1bf711d19f7b6ee55cebb887105666aa7f30c594081b4b9bacca5b42c935d68c +00530,0xaab9d4e3f1f4a07e2dc09ecd78ee8fdd50daf8ec5349ce42d33e93e73452e1c9 +00531,0x0f51dbcac068fc62805ec9b43a0b1b83c683b23f255eb63cd81ea3e2562953ca +00532,0xb4c6703d6f10db4d87cfd07d94c45cdf6176fc42656997210ed219af1320df18 +00533,0xbb2932ed5e95ea609fc5a252cc60087f857230da2797d62330595e0647430f1f +00534,0xc65d109d82fe28526fe4653452cf09db4db6a254c2c3054b8ce3d6cad489bc3e +00535,0xbb367122e14176555be535edd3085bbffe0cfa73f3754ca9eaa10dcae6f60e82 +00536,0xfaadd066133e49dcb1a5fa2c92f376f3d165c3b276ac75e5881fe7012b2734dc +00537,0x576b374c1d32e2db299b04073d838366c4525a766e1c10dd8fe0a79ac2ce45f4 +00538,0xd8eab6c1d289e8f853425d63e99768ba364012c21537e9be20e9b8999ed94eb8 +00539,0x2c32d06d103d4b1f9d31779131b008f404e149a5bd8a53f6805ad0331e592281 +00540,0xf3078a9b01c1741a63baca8c231bb4a482e62d835c4eb3ca3ef752154ef9454b +00541,0x3063ad60f10b704d724c082e97a0145796854d3ce3d1550347309657dd36b8f9 +00542,0x90a242f8e1785389d27726dab026c0e30677713f67c4bc2747673358990aa4d9 +00543,0xbe9dd353aa0b026bc9363961397d25bb46f26570ea7f90ed982373d6a7115c72 +00544,0x1c5c761520401a356ed867ac5172ffcf59b1a9b9c6fda3908a4c9474ea075592 +00545,0xe6369239027eb6239ee703f7e9e6dfdb32dd1a94b70094dfcadc9fbe0154e4cd +00546,0x2135141345bcdc69e19b4e3df1ce29a017c07fb80df9b27bc38287c2c5ccd628 +00547,0x0fd9e031326788cff66e44315940516bf926d51524e880548d90717d0da9d6c6 +00548,0xe318be79b341bdbc93f1900e82a5fff4f52df9b9a113edbe4bfaa512d1411189 +00549,0x2dde72e5e61c9eea6351d4ff14794a71685daefea6ed3cf9b62ca9aa99f9313f +00550,0xd89b717d47ffb827b1490a37ffd97547694c6ad3dbdee5cd56a3583717962751 +00551,0xa8dfd8606b55c4f54453ccf9e48838bca6accabcb629be668755b0a13867a77c +00552,0xd6a3521a5eaec4c47314a4b123701777fb7ab51af66093ad8c57bde9249bfe8a +00553,0xf702584d8c87da3ca916ab9caac71d0a0922884cb8db05cf513d5b4144bac3a6 +00554,0x700d58da768be40c844feeadc5f42385dab83a5b758aafc432172fc150403739 +00555,0x41db6d144ada4684a7a61e108131d5d78d250b3e47c8cccc85b447e5b1088a8c +00556,0x3503dd53c35d41dd5df98f30d4a4df5f7c4a456edb598cb5c2ecc91cc81198d3 +00557,0x02391085f2bdccf3e4774ffe1e0a7fdf318fdebd564f5015c64d6d1edefb34bb +00558,0xed670fa946019be6e96bd20ec27eb5c92bd6177ae0a32fc9cbe2c179cf7f536c +00559,0x63277435c400bbc4916dcf4d295ab0cb233d68834bcda11cc231e999996628cf +00560,0xe89160d7dc2b0d06408df356eb166aad39c73e6fd51e97f5a64d1f6d57fa1686 +00561,0xf95c755f337bd6df5127911e601a763a36070bda95ec63ab8adbd1fbf148a35d +00562,0x97a6fdba7ddb6462d9cae6ecaaf13c2ac670f7db6216547a5c20ef46a9a2af6b +00563,0x8aa6ac0e68888875b0afe306759d787609bd56cbad19a9cdbed484cba64b15b6 +00564,0xba8486b8d3fc13f529e72ac00fddca459b530ff9a9ec0948a7838089401efc60 +00565,0x7cba894eacdce587e611f2740c3de0d15e3754efe0331e976e1cf0150035fb2b +00566,0x54b3e34b615873aa7def6c73d8d45bab4e5f0ee5a9c8e503340ec9bf42e32cb3 +00567,0x40280a8567c1cab76c46ea7666b3f17b06a6b1d845922feb286020e7c3439091 +00568,0xad863b1e23e92bc3b1dfd81f66371f01eb200bb178d4c1659b39fecc1d5209e3 +00569,0xdcb283eaa11602480e3a38aec7563c48bd939a61149760408704f243062dffe0 +00570,0xfb9123623556bc897c2f316008fddb109a20ce6abbb666bf55d9f0e96aff0dc6 +00571,0xb65f3342d82ea682030d61222badd0d0032f03a44fb33454fd5965edfb57e9ab +00572,0xdc59179d2daa0417c7f7879eee3d53a08066ad558a36cee1535a9b515b0d0cef +00573,0x21aec308be98ab2777b0030e3b55220901ba3e4c2059a076086ef52e11e15e9c +00574,0x55e72fc99ac693fb34bb00d1ed8611d53d6414693acaaa52fdabfd3099dfc88b +00575,0xf6564eb58e1d7f625d3a634513ab089b913301c69a30faa1bb52730be7908721 +00576,0x923096d4ee10bb045085a46459592497f6314b580c75c62cda1e27c637f105df +00577,0x5914605dadf8851cf40c7591ff45b182fc6751a233e8ded429a92df0fca49c5d +00578,0x57d591a81cbbb89601aa972f81d25b61b88f534fa7fdbf207611ebb6aa1cc267 +00579,0x705b8e045b05fb96483e3356c8b0e0120cfef7a8e9649476bce35c26a8d25f95 +00580,0x5b210184902c591dc9dd3630edbe4d816137515009ff3447144360d49ee26317 +00581,0xd3dc3f99fc86600deabcc70f3bd7ef4fa9fe70da3a428b2b4ec622012b115d7e +00582,0xd6b2c7ef628b2a4e0be27bba141b8f45946d18ad5d17255d9230b21555a377cd +00583,0x434001606cc9da452057323ef3d56d1cf3505f9dd19aae59e918617e11e180e9 +00584,0x21b2682b8046bd14001c17d9a9feb7feda179d3a56f21a722df82042056dd1c9 +00585,0x02f0b1510358fee5dda91e345cfe38e0e0bdb0643d0165ebc51cd382fd0ed6fc +00586,0x60d868cb6169cbec6c74545f6cc362b6b44290d889527a728b1af1f846e9230a +00587,0x59cc91f73e2cb552ff57ac76eeb2de51c49f80f237e5e05302115e2d1500f668 +00588,0xefefa87ce3db08c5545fc2bb64021e8112434e06ec3760bed7b6440d852cd576 +00589,0x85c8dc20f625a20a8d969f1cd97a54a4c760817067763f9992be2e1e9d2d9e8b +00590,0x2bd79cac465f01ebb1eb59886d2b7d2d1c7b7c1debb19d5cea88470aa13fadd9 +00591,0xd9b21bd9fc16529e92da39239593c1021e195231affab0eed3475b79e01d8c65 +00592,0x9dd2dc6ad9373a8e5e80ec6ec9eba8b0f2242692bf27a93678270986620a743e +00593,0x0a9de411103269d9df322cc24c80bc49e30b0d0021f0a13c84e784a95c1412c6 +00594,0x54bb502669ff807c87513c7ac708c471efaf3782d0ff9b7dba577dbd5024a8d3 +00595,0x08fa26596e31b58ac3788844e300b057d53983911166d3848105b53c0b064993 +00596,0x5e2423f9905b980f953f2c35daf3385540333d41dddd46c710ab7dab864278f4 +00597,0x49b11d141d74f6eff4a99a858413e3ab5f3d3740c6ed5c705cd66070af051a63 +00598,0x050d0b97623cdfd0c8d202dc6bf4e0c3a73df861383ed307131163623422e0e0 +00599,0xa19b1a209ced8078ab2f240886f68b64cc67bd5806a08d472ba3cccefc5eb9e0 +00600,0xa81ae85fb6a0ebae94d8df6f34414ea890a7ec7621ac195c683a6d6c34a594a0 +00601,0x9e26205a26df3598d2ec6236069fb7a74c37fa84cf323c4fa09f4bf7412e687c +00602,0x287136148ea36dabb0693ef81fe921e25974d96a2724ff0d86b10e3e78302ffe +00603,0x9a115bef53f5237d03975ba6c2baf4377bf8e15ac54bf2093375681a38cbf19e +00604,0xba62e0022781cddf46d8da27f2c69b7c1dcd33fc184b2329fd59cb187e351d3b +00605,0x0d936f160c2fd830cfc16d6c17e87ca0cf6e6b28ec1f6b7d934100e82d61c59f +00606,0xae859b842f320c06c3899683b50a2d37a32e1b07786c761fa092e10e572793ce +00607,0x62d75fce6440773a1c0e6573ac37e429164c377aa00135c7e1c2e2f7b06a4759 +00608,0xd449c48d3ab67d1f1f15eaf0dcd5351f9c463f6aa103e6b4ce6a17a3b69bb523 +00609,0x7e60445e276f7e090b8ddc8a36a01bc4b66faa212588130c1175a5797a837bb6 +00610,0x2f230cba76af9df75862b04ecf554ad6bb46abd4be7a8e99dc468de6d5905408 +00611,0x290b8c2bbdea109cbf5209a39382993c21f9d520ff8fd07e85d273de90c5f587 +00612,0xb363f64740a275f7816130024de8ccfdbd67fae7526a015679bee407a5e5f485 +00613,0x80a4144c9bb6e7aba587a8a91a1362a5edf92e0fc4dbcd339a717a9200cf391a +00614,0x20913bde281d7f10d729b290f509ab76ed07603f32033cb73071f43cef734092 +00615,0x8b6e7a1e1535c08d0457aacae6cc68c0385a62a35282179c726707090c84985f +00616,0xbd35481ad334939158e73a3b0e8214993e9de1202e8a8ff567c5dbf88a3dccc1 +00617,0x624ad401fff7fe715ab546b1898e5f3e735f42c134d592d49b4615afd5b6d3e1 +00618,0xc70c6f7e13ccb5d9a1e56381ac39cabeb4c2e9f1693134d59599b7260bfd7954 +00619,0x1b807cedf382c87a6ee8cf00a7178eba5516948a0318aacb8176f3e577ce0a6a +00620,0x850650230838e76460e4ddca3edc33bd286c3f8d40ad3a1ff89b35280cc6510f +00621,0x385fbb21923e5bbca8952a90a3d861ba963d83ddd01c9730fe177341cdb25260 +00622,0x92fb5e57d123f079903c0f55481f913c45d490c7df412a721d38cbc528037875 +00623,0x642081dd761497e077b1aab32917656570396000b075f9c182ffeb34e905bf91 +00624,0x1d72d6273c3ce96a26a5442357d4bd58b84dad51a2eb39f25ec02929e55290dc +00625,0xf7ca7cb8ad47a85c6dad965e8c89bf7b33af62fc5dbfae0f5e141ae4ae1c280c +00626,0x4f92dd261b9f5a9ed03735dc46722963d949ad3038f66ce380e4a1aaec9997ce +00627,0x06e70723c3b912cfe421cb2126e812684742e304f2b8f6d6eb57b1fa959b19e7 +00628,0x313cbe432878645b4d887d961d6ff1dcd3c75b508b9263c05ed385754b7c7709 +00629,0xe939c15140cdf455b99492b6259ecf0c93ff858719948940f54dcc0d202988bd +00630,0x1fbd3e9af1082f0e99094876294f6a857d8162f32c1f583eba1618acd2099a17 +00631,0x333c0583cffee0f355a1e3ccb6aa6aa16c80ebdc789e698c5f0f17521fc75035 +00632,0xbd6027f363c5a6efaf7d6f483653d256c6038a628064927411e970280a7ada9e +00633,0x2fc5d74d149d6b265a5f6ef7b220738da67423b7aa176bd97d8b1c0df694ea47 +00634,0x5b3c9d594d6329d06de454698372063fe7c17da6f5dedb0ed68d7220e51af8d0 +00635,0x95e4dedec09d095e65d74638d433817b736659254cfbb46483ff449a9a1414b6 +00636,0xf8124b1e4bc3e7715dcff4eac8fdfd594f035a5c37ed7e041c85928cb0f32a93 +00637,0x12daf758eb702d488f8ae9c61e89b165f4b1e4090dba46713796dd49866585dc +00638,0x75957ec2b9f6cd5f4e74a8f9c7f87432ba90888af7eebd1cb621b4d8b002d113 +00639,0x7c4f218a868ac866144c6d3d76ce9418c7674546ed3dc36e8ef313dd58913d6a +00640,0x3cdc61329614d0f9f495f56c7be93a89783786ec23004628348b62819a5db04c +00641,0x471f9e808ae0a317cce604dd035331ef6409ba0c3b0b0bf36ed93946fcd0fe83 +00642,0x551764bd61137d2595500f29b441cf8588f4ed1f7e1023182ee72656ad70bae8 +00643,0x368d4f6f887c76cd7416b91139d0613952a137d983d7ade47602ea026edf5e04 +00644,0x81a7c3da06068fc345f11d7bc65b30d249f3bae56c476ef2c16a2d7a04e19112 +00645,0x2582b644739c464536ed4befe7d7bcf77bba70a416a74869934701eba0300a4e +00646,0x7fd3548a22eafe728cfee056c100c5ec3622ee0280a79be7b7fb5cd1af2499b5 +00647,0x07e93c81557232d569357182dc05bbbcf7ff3f5b3786163cfb5df756e601d9d9 +00648,0x01a981a6bc6a5c30e9e24acbd2610094f612785ee1da40150ef6adf7759418a3 +00649,0x05bf160d3f11c285bd8d159e9a675bf04b17615fcadb4390e8f582246d52a263 +00650,0x119bef0c67ab4480ee8952c208c75959a4a98db6b646410d4276c650e107354f +00651,0x4d3f0b82017c63839fe95826858a18ac4ae5376c004d04a23aba4d6d7a32b96f +00652,0x730975c7bcbee5e2bc9299e12abb46dfc7f5b94416c94b6b103ae22d4a189049 +00653,0x2eb89f05e222461e22e437518949767e25e432862909e07df410c6ca237cb567 +00654,0x51b0bde3cc9eaf4d7ababa77e2e06e65b262864cd9894a8f9edf4b3483ee1d28 +00655,0x06381406a98b16d278488bbba3f91c0ec10c1ace930d75833f15ba9c73500a2d +00656,0x0c07242390289d92c0deb8bf23da435720a753a07822a0bde0bfddc258c2ae90 +00657,0x4b0dfe65c189822fa4cd1648d3fbb1ecf75b8b5538383cde1b3f899caf1d1bb1 +00658,0xeafc91b6b61da1feb8af3c78fc9b7d01239962fdbfbd40c920a55f620ff74351 +00659,0x49e7399f27b5e26165b5603002b529ab4a974346259ba9aac2128387c0b6516a +00660,0x376add4f0e8ed9e97c43c5e439d90b5742c913908bbd5ff6da3ea59ac381da92 +00661,0xa8a70e6e484c3180d23874a903ba032a1377e3bd53fa9818d7c11dae93883fa5 +00662,0xdffecb3c77a67ecd4d71ef3d16a47cb27dfeeda34126567620ad4bc0e6ff5961 +00663,0x6c4ef261baa1dc41e4e3f559e686ce4e340cb14cebebc5ec6cd2d8d11b4bb550 +00664,0x3eb2993dbbfdd451bf6ee204a1aa8363bccdf05442fb2d37283d0e9743c9548f +00665,0x8f4067864f02001aa64082821d09b6fa8bd4f08eb10a97f2b3d725988dec18ef +00666,0x4ed7ee7ff95fba3f7e26f8ba3dedd661c29cc693e39ac180fb1cf51cf06be01e +00667,0xa6b898d4e160d6568325e5178aad53d3b1928eb26c0a6983e2e564787cb59169 +00668,0xc4a9d166c6bf0bf68df60ac3841b9dd7643261a1f680ebc4a3eb1e78a2bae263 +00669,0xd8d978428ae77afca8ea889e5e315b4840b2c03a2f9cf046e6809ab3cc2bb50b +00670,0xbe3afc5ce9e69625defb1cef154c5ed21bd685b3b444f0bf18eb578438483e84 +00671,0xbf138a264139a579902a52806444d5b72e5a7d700b441fb3e48007d1d96badb4 +00672,0xbf106779ccffef7ba05420f4d363f699759225b5c63c0570c644684ed02a1a82 +00673,0xdefe7756ebd4bbb46d00e6a9ec83e0b448ad30cd07e8140e8d198a762e17bc9d +00674,0xc6dc6388bc26f755dbc33c06ede33976846dc45cf406aaacc275f36bafbeb8a6 +00675,0x1e729aa1a7eba72fa1b394e8e02ac0b11ff5b52c45ade0e1dbe6cf94133d3d52 +00676,0xa5855d981860b945790cd878ab958c0c8f9d634e19eed4ffb6f2b6fb0bdac0b4 +00677,0xf3e17cb0fdfb1b6843f71e8371f3ec7943f3fe8c336f50eec94be6b3d7cc74c0 +00678,0x42e737249c54ec77b3e92f6e2ad6cefa998f950a04b6e86467096abe91018de1 +00679,0xf0fc97a52d48a5cd63c3a44569661bf5d52b37631aa5de0f9c43bf9fe2ac0e54 +00680,0xa6045d364b325ce7f818cda8750a79196c59419e2be015438e097fc8b52dfa0d +00681,0x247222f0af90a8ec543ba8c04c847b648fce30a323ffb4cec28f0c1571f878a4 +00682,0xa6b3aedbef826280e9fb8ac59718ab16e5369cd11be51532675fc454d89d533a +00683,0x19fcceed6516cae75fdec68f8d34a12c90b64c4d140c4576e724251e6ee6ebed +00684,0x388b0bdc52a25713bd30615e094a873e633092c199bbe247c96c32a61fc12263 +00685,0xa2bcc3ddd6f1ec7a0e90f3faf0eb8418a297538a351f16523bf767951cdf179b +00686,0xdf515337eccd495de4a93cfd27e7cd44bfdaaf7cad84ab831255b232d9c3dbad +00687,0x8977442562e00f0c2d71e621848a4ed4b54dc37900075e31d4e945cc1ff9cd5a +00688,0xa979df6fe13d81c5777eae13b0416a370a2c631c41446e51ffb060a8a6a71452 +00689,0x33e5fa30c4826bbd3448bbb05dd7273639f122e9c9cacaad987e1def1daa7c80 +00690,0x7c95061fb3cac78558039c1cebd4c7e70831f6f5a7906b9faa1a7554cbb43e28 +00691,0x062b4177522f6cbaebe9e708a4717d0f5218b21041f84b7eaa13293477135e10 +00692,0x945645ca1e3e1c23eade81c2c8e0a7cd428d3dc875b15fc9bbdbde163bc742a7 +00693,0x8c6754fdf4780c58461bb089f7d5cfce43a0c0b527b7044e27eda9852f34a7a0 +00694,0x222e02bcbbe7f319c293f0c4da042bf7cd9c3bf8c953f4319a14191e4f005966 +00695,0xcebc5a0e235e81bd4488436792b62e736be4cdbcc60f200326cc91b436808baa +00696,0xf73fca1b251055ccf2966f306db54c0201bea107de603c1aac0f7b2914386dd8 +00697,0xcc3b18315c91ff81f2f9c76c74c0aec6f4bb76fc6cee9512ee81026de4f687aa +00698,0x062461dfeaa7dc2a5a6e7149f2ba928b78aef2b9958605a31185bcd7f004522c +00699,0x7dcae2e8fbc54bedb91edeb0c02141574a70e0412b2045e311330119491c2129 +00700,0x64f029a915ad77e37247bb296e4e3eca49dac180d5b91d5b9e1366cb5d02df74 +00701,0xc0ae757bd5b3d4a2a87884cfe45bd3ee2f11239b51f9dd5cfc05401c5c66bb8d +00702,0xabe351f7c2bbfcbe08dc7bcdb0eeb08079046bb9f2c94a80ed7bf8e51bddeff4 +00703,0xddee734cacc8d4ef083d67efa4df54519a60e0101c0a43842eaf93af88ab3377 +00704,0x2ea464e978346b97200486d8994e77706f83622452eb3850a745b215b6351eab +00705,0x9f0bc9d6161d69f28e3f342553c62fe53e281dee8c05002bd562b964c7abc1a6 +00706,0x58568eed1ab113f2d3305f595ff6306f9bd4a20dbc168388afce22679b648ccd +00707,0x6aca18990b84a8ef483d70e93ef95a3fefd969b44162724e8d205b2e44a60e09 +00708,0x2478502ca3b5bd3787da2b2702e4ed470abc698594043bd7eefc6b0d200cfae9 +00709,0x07426af091dc9d0b455e6c0a6de13abd24f3eb3a8e7763538159bcd1bf141645 +00710,0xa70b753c132d447457a4a4c500a03afa9fc5a506cd08966303adf5439a183fd2 +00711,0x1146e2f9e5e7d485c0b97ed15f1f6a5d3ce2b829460d37cdb9ac49d7f6b2ee08 +00712,0x560a81199fb507f115ab5c06337c8c4dc0fe38d991a0057b88816849e2899ad0 +00713,0x54d9396ec97021ae660990c80c6a06075f9e7e2cb7520f242b8c4019f29fe4c3 +00714,0x8979cc56b72d0fa09ab853f0c94da9223e371e4e3a76d085a8d5e0ccfa812c9f +00715,0x1a583ca6146142cd35125be61ebecf376f08db4cb907d613d8877b383a961923 +00716,0x4850905c37251bdd1612b0948a06170a335831bd753be7c62d0d50a8f10bfb34 +00717,0xf510edaada3d10661180eb5af717d93b8c5e39971c0c7b82245958bdc47d4359 +00718,0x511c0a35f990cf41f851e42863956b7fa20eb133503b7f5e8b7dcfd42ff57d8e +00719,0x14409e14f0ae0f18d080c8f6bf0ae89e4817e214ac3b2c3e7625266375a502a1 +00720,0xcf91e8a7472e27a4172246ac5c5a761575f2f25650a2284ea607f8b607ece639 +00721,0xaa8695870b38dbd336c12ca05e61ae474fc3540e3780da64432d6cae23de1ed5 +00722,0x96e85fdbaab8e3e96a18a455b6f7c52dfc256146b15b4a17cd5349a1e05dd900 +00723,0x78bf01d3000e5bf37d29358748ec99c6e4eb1d6e3203dcb914b0b7009bb475b7 +00724,0xd7c27830b175b06d64f2c9e7f6533d396a6527aa8078030d35e2997805031dfe +00725,0x8859c97fca028d013b18ac01644d4070df18cb369a380207c646808ee242d99e +00726,0xa705da9bf450e3f38cbc0916a3430caf7b7c2e5b84b0eed30865c21417a787e9 +00727,0x58d8312647f7b4f93bb4e166ebefe27b4031924f7550d9ba1d2ab7fa58fbd547 +00728,0x2daec9311d82d342bf0a5f197beda1aa5bec47277d79baccc91d033c2151d583 +00729,0xfe141ac786b2e586770563dd5812bab7673e4939e29473e6c4a1a75d5217bf13 +00730,0x4ab51ad5fce5b07c3935e88c8a21e911e30fec10a5066b79e0d01df2737bd613 +00731,0x11b0f603bc13ce8a712ca6ef749c8c923097c455c6b86386f166b1e47daebfd9 +00732,0x3e648126f5543d814037eb55ff7d4079433fb586ec6b3a2bd0ed968f8fed9603 +00733,0x87195980bf623a55f7bb30e396648aecd839768429e6dc5ecd3417dc44c6521d +00734,0x1a924a1baf8970146ef21e1ae77cbececbadcb975f4f950314313381d50fa823 +00735,0x34d9d6a7333d35e1f16458eb9bcac884e81f93dc421c3ad47b7a46ea6f929c7a +00736,0x1569f88b5514b6f98302427c8ab4b4b6c020b517b290b2c7b1e8b6b9ee2b74f3 +00737,0x288181ee87c7c1f4c8052ae1692959d57f9f4b123014deebfeeb6df20dfaa424 +00738,0x28dbb0e5bd25ae20d92b68183f093bf002cb40e2d0e7b9597ea6e58478db184b +00739,0x4bd79b88bf29f2048cff7bb28f048b67312009bb49d5c33e0a8df28fb26de7b7 +00740,0xc84ee78099163d07ff47d4e2f864338e0fcbdaa1298b6fa71352e6896655b918 +00741,0x2aacc622a545af97bb40c4d5decffd5142427c482ca5bb8ef7f29951e1807e4d +00742,0x165aa7d2b8608774366225bc7252056104da64abd35ddbd1db832ae375bb6031 +00743,0x4505bedc2d45231f48b90817f82a686da0f8b362a79bb0d774cb396288491461 +00744,0x08785ac95582347c80d4321d003a4c31d343effc0cc8e8d4a32f8370996123c1 +00745,0x6ea3cb82c7125522aa5fe08d65c4edcd10e1823d312f13288c5ae9b69b2d2935 +00746,0x3ec58c854981ed2f44dd8516cf166b12232e5e32d2fbeddf070fa45a1d8cc638 +00747,0xaaaebe5b4f04d2085247c7c9855d1add2e8f0d7e545c532cde20b6145ea711fd +00748,0x5ab3b22293636bc4bb517aac1a3c22fd297cdf1c8da5cab2353c7b657208f1d0 +00749,0x27aebfb9c574b6b4a90161369be8e3361b887534f6031f35654424c9d50e3efc +00750,0xcc08abf8cae1d37837d395bfd9094e01b70dd66c8cfc9800fe8fecb4b2b09599 +00751,0x032ebacd972a00b4cd4fc81ee4e8499468ac379eabf1de2762e98aaa957e4cca +00752,0xf09c12bf003999d4e98769faca1a7c12352abd26bfb290a048b846c669bbfc89 +00753,0x876733dd576846ad12f5967b4c131194b19013232b270faa88f816795c403e6b +00754,0xf50f5eb285818911c3fc43b60174f25a9e5b9dcac9a5f3e6914d8b0af439234a +00755,0x4d52bb12e70194eb981ae85c08a02d16b7e899262dc34e7b028eda0a123421a2 +00756,0x0af4e42bc526ccc68e29d057456f30076323afdb70a6aaecef47cb316a689c88 +00757,0xd1988f793da01c8d63bbd508befde9fe8ccc1f2f5974d9bdf0b2d8afa0b9f997 +00758,0xc66fcb070ebb36a3ef93360bb74079d15f8c4cad6fada6a408dc33f982308279 +00759,0xa6242a1ccc07f0b240026340ccc6d91d99396732364858d8dab438965f90545d +00760,0x824af748696096e08232cea82a07f15a590908d73e4b72da6733ed3dce3ce648 +00761,0x76b41584de30eb80fd613f82c44d7fa70aff42a1760221e3852d8865923ce75f +00762,0xb3ed5869910b3b75a102644af13fb642991e19aa885848ea9099f31091cffe0e +00763,0x713aaaf6faa21e1ace76e89e35cb9cadc04e01a6808e264dc08075a0a4074e09 +00764,0x3a6de7d91da79fe7ceb3f9ab4634e88efb40832ef2e776624ffde6b3d37b6443 +00765,0x18b5d60216a44d195c8c533a95a82c1cf17184393db431accc269b8f759f6341 +00766,0x6b5ade6c06f8ba9ef42f64369a90145db95ee3f84c7ef2f4cc0bbd088d400287 +00767,0xa008476355318634f1f429e5921b41860e1f2b84a56f25bfc4d1bb3ad99e339d +00768,0x8dc563b6cdbec477ab54634e7dbe0a986ea6f745e81d1fbe2d9ee2036222f50b +00769,0xefd6696f77b898d126c7df1d9f481853086479c17279d5d138348e5202bce86d +00770,0xd9db47f4de8d5d1c4700ea620d918e8ad0877e06d40183790fe55bf6a334748a +00771,0x2aa70a70c541cd444fd2caf88968d737fa7df568af3e13526cb9efd7d0c340fb +00772,0x44dcb9abd03e34d90516dfcf01de57529d8e5efe899d526fb222840547e98dd8 +00773,0xe4dcc8e85df47ef9e3e5ca5d5fa8bf8597cde9c9234f6ee5020260e69e911b2e +00774,0x63f82331a80309f20bd3c9500671446c81923ce5023224f9502343c7db25d83b +00775,0xf24f282ea23a59a5c6451e66987eca682686d8b5df910676b2fcac68e675a3da +00776,0x382525f177efd6e19eb9949fdf8f31802f86c7754d43898dafc36eacdcf72db8 +00777,0x2d3a5e7ae6a0aa3498ff29bd9c01bb50be16608071cdc311690b08d54b81ceb4 +00778,0x9a24e96613beb77c7482edb95e3bd149f3a95df7fde1e01c23eff75a71f73dd7 +00779,0x0be7242c1c73f21c6912fe398bf625f142d4b00f260cd0169b82162c7b215da0 +00780,0x0b8c7a94e807b13c8053ee0c97d5f38f263e31d9fa703d9b11de00c7d4c7945d +00781,0x6e9ae0809cf9e38136a64b629b4b58f37bcbf54b6744ef3121403abb14b1582b +00782,0xe888e6c289f0734c57b9c61c1b6798e5d94139252173305a7764c8c4cc9da157 +00783,0x03027295eb991e1dd03d652ebc3ac786ee4c263504a78fe31398341844f235f4 +00784,0xb6efb516952e014d0e2197320e521f15d58f6eb8c88bae72fed90c570ec3bf85 +00785,0x79728b75e2cbcd3ec3a144ad474dd75eac9e1dd898fb3c97023c4edfe7d91890 +00786,0x0586eef4843820a247d8f8201c6b77e828096bc02c4c5bc3d2c3b83bf42ce549 +00787,0xa0d4c8c20e3a37f678959b563859677050107b0e63d043ca1930dd48a93c0311 +00788,0xa55feb48d4922a3189983989333d70c7fc6b18656446bce243eaf77fd21c54bb +00789,0x9b95d3aa1408771b1e1e743db3216bf9e512a1fdaf6035f7a9f40e3019e9134c +00790,0x4a62280eabc47623a8015bbbdb99a64521c554491b9ca4baee28def4c857cfa4 +00791,0x064776dafa35a56678a5574157b74c8e5f1433d823f8addfacd972e0d2dfa90b +00792,0xe9a295429a1b3fe4ae05e4444fa3e7939ee234416505e5bb12533e45204ccce8 +00793,0x93ac12baf1d3519d2d6db741537a098b5b97e00c7044e96eb2c49900a7d3c3f4 +00794,0xb199a3097a3b71bb74286673315795e98805a6951174ec6957b80bcadddffe1b +00795,0x284915ec1b0af683caaf90546c773bdb1e950f8923f9468192e160aa757a4869 +00796,0x80b8a59801157a40d10e17c3915a16f78eca8b03998466f59ce4c4f910ac0760 +00797,0x40e902aaa84d1fa5c8cfc7ec95846be5b541c785a9514f6886257431d7c7d5e7 +00798,0x25bb39c7596cf80eed1af44ca924abd9f738b386cc3604beb0cc0e139b570a5c +00799,0x565a1bf8ee5e84e7e9ff397ee36a656ffa670321bacd7533e77eaf91ea104561 +00800,0x6723d6d967dab127477429efceb7f975d2cec28aad8ddb603fef54cc69fdc6b0 +00801,0x2c9057ba31e7f3ddad8a3324a066efb9353cbdce8e399ba3061531737b118713 +00802,0x75e347ad895b4b6dadad02d048f988ec7298298756d55d924a6605e3ce2bc9e6 +00803,0xafb8c20ffd497fd6ed9ce26ae25f7a83c66e30bfbae612cf83dd83972a75d7f3 +00804,0x472b0432e2d130803fee6986e35c0decf8989cb0d0645cce4848848a30cc990d +00805,0xa00ad7738c5a78e98095ad2803f5f02736ddf5fc471940d4d01642317be7bafd +00806,0x4fabbfd520862fb8c2a3cef755e30fab50f8e235460924f43eb239e3276738da +00807,0xebadaa845247da44fad909d4bad16b43a5e63c6f48bc3eaffe2b98b27f9e1c3d +00808,0x71a5a039aa5425f801492260210074426cf5deb420cb2ddf9defb3601564f0d5 +00809,0x2a78afe865f39dadda88e3d3d493b6be19af8374a62f0b48c3cc8b41e28227aa +00810,0xddc911377e4dd2291f709e0243a6cc7331a49aa27aab1ef211470f4662c8e460 +00811,0x47305f69611d5c09e9f302c34c1a491b8166f950f14fa56ed0885c11257f0224 +00812,0x6492e81274651a77c064ac8a6cec00c509e58de9a951070770cab002658d662a +00813,0x9ccf4c433a7e66762068756cbde59d2c603e1dc1d64cd0e61bd39bd636ddd877 +00814,0x02f878d63294625f5b8e01973359df0621504feeb548141ee1fabd1747bb2f4e +00815,0xe97a4d00ec948995c670a9c30441ca9f510c6369f00ef2fb38624f14d8531eb8 +00816,0x13c60a90e71fbfa321264b1dfbcdf76d0b15f3adbed05f31b02848e4fddad79c +00817,0x6f8e5552d9e7982de12d6cca3368f02671fa6b071f0618876d4a1e9a4d79a3ea +00818,0x8143cae1101045cfd98b8202617280228a5b68c0d4f37180b79327d4fd555a61 +00819,0x3894e28cbfa568d39fa7db232e4954e9c14f36eccbcc4c1d35cb8562285fbcf2 +00820,0x97b69aecc1068e3d89e32195d6b0058b13a2b762cdfbecee7d54256e67bc4b81 +00821,0x22732c1861dceac8803885adf29e9c9b7758ee5c2de3660d175aec67e0deb2d8 +00822,0x6977fa0d3194c37772fb68df9929cc9974fd9441cd4881adf20e17408465d544 +00823,0x0d164934226bdbae6b1a9c2e284a02bfe3e7552ac901576e33aee614f8f4d9e1 +00824,0x0de9eb6ca895573dc439ff773e617cec54c9a3e83c8412ae6bed73594f51845c +00825,0x14eaae6399e76bb8c66fbf9cf4333701bfeda482cc347590402ba802332e5610 +00826,0xe0848f10dad16982805b6bc7f6151605db509bb228fc49dc647bb472c0fdd83d +00827,0x6846201d042855e80cd3e2a1b2f5f0a6360d499cd803900873c1900264e45448 +00828,0xe89c0e11010967dc5ceb97b9ef40a45f36ecd9390c82b58d95592deb04b6e746 +00829,0x3096af7600019e93e14000a119faa50fc3c60c4fedfab2b65ef7c5e76c40dd2c +00830,0x55e8b4c2d3dc809690f3276cd43ddb11b907c7a975de41041a1cf47e6fd535b7 +00831,0xc501837ee2c215da498b734153628de1acc5d433179078696ce82a4f2fda42c1 +00832,0xf7000808e45b53416da880d5a8a6face40cb10a55fd1a9f4c07bc125da165ea6 +00833,0x5d73b97ad48b73368898a1e39b0f725c43ca3757b9224dacd2f8db81b90d6807 +00834,0xf240decca5d9b9a21a75948716f83b68499f5f260fba9e535320d7ad2b8f654f +00835,0xfbd0a3686d9e771cbe2410e0eaaa2535d140a5b5628d2dc5b79afe2a54da0255 +00836,0xfbd2c4fe042a2c0c30942153fd2b2a148fd11275cda67d7e945ea50d8ce9588a +00837,0x8bdc330460491a8d07586f41f6c980500b273533b9a98d0d0d180230a35abe43 +00838,0x2a2047ce16869ba58f7aa520202bc2c2345fac6bfca50e06194361165cedc4ad +00839,0x84c88273e2546de530b060ff56c8c9fe3aef02cc968fbeac333fdc4de9c49cde +00840,0xb96ae20a3f7c6cb7890d5f72037ba8a1a8be4e4f758be430f089ba62c9886887 +00841,0x5cfe6abdb5b075a8fc721d49e76d0c136de22d165ff61d27a7acf7050d84a31d +00842,0xb7d8f3a61da1cf210b8d80336009634c26f97ec52375533406ac0f0f7e22f5fb +00843,0xc14d7f51eb905c4e662965caae40a537cb7a85d85458a5508e91a2498e479fd4 +00844,0xc5eea731a2a18fbbc08066a06515c8f05d8838912d961c32b31ac31736d8e5df +00845,0xaea57615f40fa35e4c73f273cee2b1f077838a18001e8ddb9e87d28286149014 +00846,0xbe228f4af7a96d9c1cbbd4e76864e68c332232ba5ce81de3e11c0d8b33bbf1ad +00847,0x5721c5a99dfa32e02559d43450e95be7f59d245160fce626eb8e5c81c271be87 +00848,0x4f17a7ba2d98477f2d2b3ade28f2107d35516e8f953b636ac1f6014f4d1c2204 +00849,0x81731fd5dd5f8ba504c4c3bd1080eddb3e400e8655bfb1e93da5450177923ce8 +00850,0xc8596aa574934f8d7b7a0c938ce736d7da8c63dc40bda9719b1469d1ef93ba0d +00851,0xd9d76d294b8224a90bd65300b2bb1c3c5e53441b3182c5b0d41011f626046a9f +00852,0x3db9cab96ffd143cf6bf1c330e6cef7467783d82443e5122006e5d2fa200f1c2 +00853,0x05eacb145ed3b25a1949999d28e34eaf4aaf8cc033cea6569f8b53a4d49199cf +00854,0x787444532a61379ba993a92688941b3fac90f64fcf9a32d022ef0cd78544f813 +00855,0xb042cdda0306e8678b89046603d24839002d4916d40849b5dc9e65f3124952f0 +00856,0xc3dd963be82c9bd8bd0a27cf846b0fc901d63b7a5de84844305385a2de4dcb57 +00857,0x1caf90ed8dc29fba89264af3ba07d0874e2f03c223cf387fec52bb0b7c4c5017 +00858,0x7d89c8e7e7bb553c60a7fff4c056575791ef965ece8adcbb8923c17c2ca42403 +00859,0xec9f0685cf4c7e59b45c2627b98afbf56f2d113415af631bd875962dabe376ba +00860,0x608f5138cd3fdba7adca86cca1623b02d967a4ddfdabc1626298aef841f06e98 +00861,0xbc7139248334659528164fddc3c05f6933494abdbee4e82b5c16960461fb6bb9 +00862,0xf5d2654fda6b2a14dfe9f390fe8464887263d7415ab839418c21db6d00b75e02 +00863,0x29f0d1bd4ed36f2a8fcddc968249af476e48f49eafa8c1cb3ddaef3c9f6fbb5d +00864,0xba09ed24136ed4ecce9e3aca125ba9cffdb949164e4ac0115a7e5636bae9ff81 +00865,0xef98f25e48fa78413bfcb8bc7d7bfede024ae12b74727667431d0b7b24c88197 +00866,0x62ec875a0d3529f36a0559e183518082de0a399e1b4840e3d5d23b4ea1e6adcc +00867,0x6e38f92d9e902c7c4e46d334d8f15126fd82a220c3529cecddde6b7892187ada +00868,0xada339e00fa18f5a7a48601c4d9db77332f4df313771b2a166bcdf02c07b5dad +00869,0x687f70ac1c22d04c591b239219d4cea3fc899e22a15656cdadbfffee43900445 +00870,0x69305b6644efa1ddeffdbb7c5fbd55450e67237a3bb38fb8f08e81c567952569 +00871,0xdfb483577885f06bf36bda6c0918ddbb8ff30612412e6b4a67cc4bc867f2c44c +00872,0x1fe0bd683f075a332f51a8d355282e02186aaa79a97f75c6a317dea751ed8b30 +00873,0x6754774ca2adf65caf7d126d0a1b7a3a9e9385968e96d8ed20389a3c3a96895b +00874,0x89ed1e981eaab47a9b1afe89f4d8fd3eb60d208cd9cc2cd3c94c2a5e784f3bf0 +00875,0x918e70e47775c40e4aa6674b40d2f502e26dea08e7fdcc95fc612f9411268617 +00876,0xb174fe364a001d733d0ea0de0724d33c30d59ead3ba2f7c318322935c17b9027 +00877,0x1ee06c6001f96af9abdc53c79801ed63bac846f1de194b8e31fb0e99e6cb2dee +00878,0xacf82dea7eff2b6749a07263ad51979a18d25e10191259c97531804deffe5f59 +00879,0x194ae19978f7ceff5b951ccc21ca69e4093db9f14b3dd735675b658614b50163 +00880,0x88dc77d7fb4be097712c34808ae6bb09f4adc13e82457e2bdb930cf79cbb08d3 +00881,0x291ee430fcbda963ea5ab68df639ea92ce325530844b6e5b43a306fbd3bf86e7 +00882,0xe0bd01b96a078f578b599838c06357e455d023c72381c0c9d96d2a57099f038a +00883,0x24ee5653b2b7060f64b723f52723897140c6a39d07a35da8b362335a12fdda1e +00884,0xf46491735b52306f745dc8a439441898c7a9dcfe6301ef0cb0f933c55d8b9432 +00885,0x18be58079d1320046e689e4fe43cc04d43cfa1794999974288fcf3625e6411a4 +00886,0x7b8e7f87674815b502a57c0797eca3288e0b5ade2a8ca7f78dd7ba632b127e25 +00887,0xebfbdc0207cea435c10b7052a0937c699721b2e7e41a2d925d0eab2ab81e9c8b +00888,0x2911ec4630e2dd25d76cb86d8ad8427de4fca247c5e641ff2ae16038edb9ff52 +00889,0x7bc66f0a17605a2e0a082da2f3f99d6d424efa091d15c856e0bab50875629e07 +00890,0xde4cc0f167df6278f89a5cd047e8079d7e9368fed79d2ecb3e8b31537f744260 +00891,0x1aa1a5b9610ffa5b41fac5bd68fcc7f767d3434baaeea70e20f738d369a44315 +00892,0xb5354846b7a3b0764849ba2c006bbd7ab19d10f2479bd99c822442214eb135aa +00893,0x75d76eeec8dd8ee7b5849b76e8e3c5b363adbf59fed68f0df8c89ced4106ff94 +00894,0x81aa556ec3ccd95dbb8e26a987f6e0434ca41766f68949258ce05f805f74a808 +00895,0x4704352715ff20066ba6150a55318d0e9066ae548b4375e4ce9b31e530598c61 +00896,0x1ab5749f22bdf79c27d6a073d93687b6e375b33f38cda1d8ea1b8aa794c0de76 +00897,0xb81f63bc9725916a88ddb5a5a6d7b7d558afb1d55bf29d57952da749e99ecbb2 +00898,0xac96c90242fbe989a37f1711dfed7051aaa38a13d8e8bc3ca5a518a90713cccd +00899,0x922b1cf4946990d76e6aa05024474ffce4b71c683db79dcd7d08fdafe537d04c +00900,0x0f8ce28573d070b2160ba328d9eaa3d81af5b60443acea676cee7cd234f0dc9a +00901,0xf6f06a90999d172458e44c324081d1ee668709a2e4273a35fbfcf1312b913999 +00902,0x65bd2e95f8d26b9e2b3360b40175eb62b0881772fc80085a3d872a533362f5db +00903,0x3b916edf62cfaa0bdca3d8b3f13b9654ace5f3a1c6c9a787dc07452b69cd985f +00904,0x2ebf7c0d8151e785e5eb6ffbda1269e7d9d7f36545711099119ec1d486642994 +00905,0x9e7868aa92b87527f63245914226d675e3d09172ef63e3191562d1869ccfd5f2 +00906,0x6fe8a5a96b514f6763167cd7925516af89e4014baae26d735fbfa65dc9ee1fd8 +00907,0xfc681d3f63c0705f771f6f7cf8fbae11076db7aea57e4aa4db082fc82324eaf4 +00908,0x65f7339775a6fcd357411605348f51cf908f2a6bda04b392ce76132c1fc5a40f +00909,0x38ce4f9f511d38303d855f92e28b6e096b749211b0861af2aee292fd34ab3af6 +00910,0xd44a929f41f40d97e7767775efbcf22213dd313c0bbbecbfe6130712b28b2fb2 +00911,0xfc91f464f9eae7f2fe1844bcd1c304c8467227c5df40b5518f2d262e14aeb011 +00912,0x9acf8a7ebab7d5ea23e59c7434b854b29d79a7d52153264f96886051df865c23 +00913,0x0790733786688f30e6d7d11388f7daf100afa105770f218e84321adc6427fd24 +00914,0x822dfb1aa7d617e0cdb16f997d992e643890aa048e9fbf89051e42349602ace9 +00915,0x62602cadc14d41fb1a9d1c682afdbdc3a535828fd89ab1474040dd571631207d +00916,0x8b6dd223bb5846cf7af3766332bb4a3c7d0075b350f82c907db76a2765be8dbc +00917,0xb309c46944a731132a289569e9cf52c57e9921b99cb00d02926f93fc83d6e86d +00918,0x8974583a7b7ae104b867fa6ea76b999ddc399498dc070cd622df9b2eaadcf4a6 +00919,0xd139d7b42b3dc5b0316ec6e718f6ed470c2b8063357ca6a5525eaedfd77fe93a +00920,0x5b83da490a1580b57e046be20c03b6f6b9378cfb8b8313a2d58cd10bac12884b +00921,0x7a62f3b8756e0b45061ad40d0d08a4f400abcc7f8f9d21c4eac35d5eb3c69032 +00922,0x30f2071bcc7e743301be529cce48170478cf733c09f76bc7a007486e907b8d42 +00923,0x9f05e1511533dd79377f64581191380f2a4414538f9812bc978575ade32e4747 +00924,0x8d0da5014bf3664e6f3ee37a221447169bc7ef4cc2a98fd8141462fd4e6eeb28 +00925,0x9de1930ee287c457d1d7e31f789e7d73dbd9b2ae0b1db00a74a8ce7dcf8b022e +00926,0xac17e41e8ebb278089444caf7fb6de4be8be17e0d2737713c19ee56e233b8052 +00927,0xad6865ca7acf691972f0906fa666ed8742cff9e41ccbf870f1c2e6c8566e1597 +00928,0x3feef311a950eb4f513f3f125bf4941b2664e7696c637c0998aaec146910944d +00929,0x6e2d1f4b1c5ebbb67159e8db1774180c58e50b633117fa630e99025a4b648b12 +00930,0x228684d7571e71ed0dc00adc98f4ed6242dadbc65bffe61c131c91e396206d0e +00931,0x2485471e5350c5da449bbd5b6cd731be0a47123f5b26becf1790b2a65e8ea608 +00932,0xf2f69e075dbae9462a935692b7dd566909e2d95734929376b0b7be14e0d42fd2 +00933,0x44eff5aecb4e111871225cc1b58c1c04786b1a4aba892784b7551b9e8ba90595 +00934,0xac8cf5be8f250e984277952c431a84b01c0ebd96e4d46cb1b456d0aabe2fa7e2 +00935,0xc052cdd4116d1987a3939c7cbfa2f266e8d181465561a8d0ade58075cce59ab0 +00936,0x0d1ce1ba874c0fe555d4c8d7a238c459d5cd3f93634abd7bf304eac7a225bd7d +00937,0x20d0836298d617aab81be691f33cd1dc61546b081a1e913b7cf34e5afcb8c8d3 +00938,0xfb915a9512d1e0bb47c535ab0cc6e7ddaa439a720c4acd6d591be03ff738a402 +00939,0x2d5f2cb94ecafe782fc87c9a65f35a98a38b249bfe8a6c6483070d22f485c752 +00940,0x31a360b2a347dc2d8ff1e2ee51c8d487fb02b3ba20ea86104e8c0010e6840674 +00941,0x6247e765c7acc0135a2a1c8359ed9280836e63aa78bea7e5d489d44cfceda482 +00942,0xc352aa92f9ed89ebfc84d9bf131e0e386a26b3e6264cf3ef6e0d3262fc55df2c +00943,0xb8b31db995add4b70a2637cc3e46d37b0f9bb608f63ed39b1676115569cc95e1 +00944,0x2a8be08321010d8fbc280fbe2ff0d9a9102738f588dccbb4401ec722067450fb +00945,0x80961bb9747aa130e7b0f37c81951fb8d28bd916ac200bf5cf0ff8b4b5bb2bd1 +00946,0xcaefe64b2e4fb5f87ec1027d5ce8c9c545e116b687657c5b3789d195c29377c0 +00947,0xccd88affa72df06596b5ea6d9429fb5c0d3ffb7fb2ae2be3746463c4572841c4 +00948,0x11d91c258be65dae198f1301b2b3bbefc22d80a62dc3c789577a9d9584441322 +00949,0x209f845f27a7cfc68440e96a9a05f0bf9ffdfe3fa2b77f0b66ce46de6ee6a1df +00950,0x4a9dede78effcd06746878f1ad7c1c255e7451ead558f94a610d64de9e84a569 +00951,0x6493fcf8ae0df3ba0344e3f3962cd9cedc50b435d278c680b1ad7fe580046213 +00952,0x611a2c464cb0aed5d1ff89013df62f77a4c66a4dbfbd1310b861e17c0821d850 +00953,0x81e7d01751bb41cf701d58e15e5e24af7cab732efa990fdfc807d04965a7949a +00954,0x19895bb27f335092570be78e1c9e4390bc3165c12f3b4801c3386502dc1c14fb +00955,0x443f9153e9d10aa291a75482f6ccb32b7f03e5ff28ffecbc218bfb0d17645c82 +00956,0x3dcb543b7fe04863694029ec36709cb2be65281eb77801ec7a43c47421b2f266 +00957,0xa2d2aa3950ccd9bd38664a108384da939a29e5bd3602b44f2e6d0f7e078f8181 +00958,0x24f3f044349785645a815ecae5ca634e5068415f3e47f83a4de78d1f5a0ae0a8 +00959,0x8fc647c479f7467e99986f5a67aeda9ffc96c49cc3b2d939adf2e02e6cb631f1 +00960,0x680241a45f3921d7038f95843ee7c15a97fac6acfffad14edd0b80cd52525b8d +00961,0x759690ad2ec0fd1d75ef612e00b72ba25bc5c2cafa795df819ac5410fe245a45 +00962,0x12b37dfb28e1b19692de0b9ff9e4564d3712ba1abf0085cce006e61354f9b7c5 +00963,0x2b4168b786abedf1fd231b205fd827ce376aa3dfad7df2e8ffa37559c8aaa489 +00964,0xa7136656c0ac8a32a5cacdb85d35f7b1cfbf46add043b65d63870b7be188e662 +00965,0x8a62b4050b97c853f8b86c1a27865c5e8550689c699c7ac2cf18d534b4bb523a +00966,0x73e45b2c1971c37f6bffd67467b444874a0168db85f916c4e1e1cc0d760a48e7 +00967,0x399424597ccba8d81b2fb6d2f5b16a310e43bbee1d546bc0a80450f7ab202a60 +00968,0xdce8aff6baa754aa1d9c385dfd56b5d0ff0c9644cb0756cdecf9c4b1dc75396b +00969,0x49be47569890def0996f17dea252bad3c05e4f90c23a6b441e05db55deef4df3 +00970,0x68c57c6ab509c836dd5c5c0ce07cb41070698639ea7ea4b9faa07dd05d9ae9b4 +00971,0xc4f6b046bf04ee48a7360f9271b8507f13e222b37deab56d84090d8ad7071e40 +00972,0x13a7fe3ff99f61c26ce53cfad439b83aa50af5659ca5095a1666106ae43b178e +00973,0x135d2ae11ee8c376d2ee5ca54ebe8ce915d133c5c9330f9669c3f870cdebe438 +00974,0x922bb3c21c999cafa708dbc7df398abd83cdb51aab98537adceb848b95b0531e +00975,0x27b6441bb01ad4bcc2254fbbaea88e69e4adc75d9305a086085602eb971306af +00976,0x63eafa02faf46070cc68eff888506aae7e0bb2a4ef9558fa2ab095bd30b95d4b +00977,0x05bdc732d86d690e9fd8fe7fa8ee4077e92535202176ee37b9a2f124e7bd4212 +00978,0x95d7750a07f5423f61cbdd6797537c1316d250854bd865639df437ca3c70cbb8 +00979,0x8cf0d6245c51d3d854eb5a77b46562c4416f5dd64386eb5254036e44e189c9e1 +00980,0xa8768f5c3b2f7d860b55b71d01ededf8c4925a13c4f6eba25d2f1e9eb5232965 +00981,0xc4e8ddcfb6cf6972583902cb5e2d10c8be3ba895b076f7ba8e29c09de1a5e512 +00982,0xd4ecd7c319b9e27e4929f7c0e3ee7baa94b58604b55a0684832524f816124f41 +00983,0xd39b640f89b8d62e6a58bdda604a6931e5a97494270b8c13639c9291152a856c +00984,0x22592d52da8f0eed167b072bd3f9d68708ac37af6884b76497f518e419efc4e3 +00985,0xe4e144f9d02c04d79c9d03a3141f6a90d3a9217d2f348a8b5f57ed50deba907f +00986,0xb5e7db59cf4b1329d19cd7dec561c3eb7353eaf71f3f5eb92f1cfa9525425fd1 +00987,0x9316c767971e58e2fcfd1bfa386d6d678f05194403a9371194b26e160614f57c +00988,0x871302efe9a899f706e248554a0a7834244e9b94db1aacad82a96f70d50ce3c8 +00989,0x1c3a761603d969947df6da3491d18a2f55dc67cad3d7ae813aca79089e8e4dee +00990,0xa666b3895ff153f24a671fb6588494111eecd4c4482379b6bd662361f955de46 +00991,0x3154c955d0dc8f9ed8f5e7ebd476b549d5778600afc737a213ed6156765af846 +00992,0xd078def25dcdd2df52d7e37bc2910e598ac00c921473f8d93137a07d3a403edc +00993,0x6b2615f1fe8043e3f4f06ff4f918c0b34bed01cf776b535a3a16530b81fc9d91 +00994,0x6ed3f90facb487fa49945d0ed5f987a03b8bf76b0377fe2980bfe9cac2a5b6dd +00995,0xd3223ce7a69afde216dd1c957c6116cb76bc2d70895921c2ccd6b9d4f79038f0 +00996,0x016c769b453ee0995a23b0b20bb83c3870ec7754867b8676da1c3e4849511160 +00997,0xe19a4c9d8889c46240475ea0e669e967b4ca09dd35085c327dcf75e127093d3b +00998,0x36c9ff39ced94ac5d4ce3c5d8ce14030ca154bcc2e99abdcbd71344e8b0fdfce +00999,0x83c72fa27934098dbf8aea00c2491a9dba82ed6ae6f116f12ef96404f63ea6f2 +01000,0xddcc603638d6f6aca751013a22d42f0b3dc9e55794978e37f46c38b622fe0ce5 +01001,0x2d0fc419efdaf8f46067013cf528064da86116db18b5382289afb4b6e1cf2b9c +01002,0xf69f7b396a816ec0b8a377e3e75ee054c47339cce83f24de1453561c04f24789 +01003,0x1763271040eea5424900aea6164448f842f699eb662f8409d95e5a5635cf20c2 +01004,0xfbfc02162b85f7c870dba66af17bdcbad0f5e6dbb8c7b0f2ef936a0858595077 +01005,0x584687a4b29aad825e7a6f106afe5f27a97ae104d3cdd7389fad0f44ad5cb101 +01006,0xdf8970e84c6c9134c98a890c83c4649fbae258db7cc5d3b1fc3c63cd6ab64708 +01007,0x2fbbff929c09f13110369d940831fde47cd6eef07d5449d4b3f9d353ca155dce +01008,0x235c9a91c69ce2ce21267dfa82b595caacd3f9ee09d9ad725e5913c317a05646 +01009,0xfa09b4f1cabfd5bf65704b38982b06a536e316ef4b533db69a73ce2bf88a571b +01010,0x3cacc95c0a0f16f81baca64b7331b81bb577b2ce6d451b9b3773f1770fb1a948 +01011,0xdbcb3c6423aa05a61c71ddbf3181af582e525b5a72a9ebb8e44913bb981acfb0 +01012,0x6ac002dda4b8f105f2bfcfe0be9f0dd8cd543abaf99e36340397026f68fb1210 +01013,0xdd1763be363eae6e854d82cf948ce79aa3903b24fb1bebf83efa5bb9ad8454c1 +01014,0xc4e0e059fb5489787f907324c81a46a400a87b3cc056601f8a9eb5fc88b1d32a +01015,0xd2d13e5ed7819f3841af3e911c3516211bac48169a52d6c0f0525b94af603d61 +01016,0xa93277ff5640373ca1446607c231f0bed5bd15a096142e7376580f3fc78841c8 +01017,0x019e6db033ebcb56d9d51ba309d4f010fe79a0df9f6f3114b052390e273ec750 +01018,0x763ea921a273d3b92099e451f36949767992111073117536583f5fab34dff71d +01019,0x45d2795144aa708f2aa6d5016635c887f97c9e609dd7eaa30fbdbe04ee2acfb9 +01020,0x37e8f37e7fe680451499d4cda814162837dd4e60b9dbcc1cb4a09d8aad95cb5d +01021,0x6654a92dac9365e122dfbf52b5d2134dadf1d638aafa879893e50ee2da2152ad +01022,0xb81a65c13cc3d54b281e9ad392e8792910ad09b39b8dcaf6ae8e3fbce06117a3 +01023,0xb72e8700d81b2d7c322dc74a3f37dfce6f3b08a487a92242fd0ec2b8bebe21fb +01024,0x75f6d852198927b79d8ad8bd5505983052e9ac80b80d5dacebd4687d60d549e8 +01025,0xcd13479c8725155feebfed83954d53ffcb6725683f43c866acffbc6e9b97ccfe +01026,0x1ff6a9b9fc585560ae6780a7c54170e8f501324a894f00f08828697d661ef0e2 +01027,0x6c76c020b3f3f95b9c50a8d6d7949cc9c9798522070f5e35e61c6521473e15e6 +01028,0x78f9905648fbb6eaaff40a458301f05a7bb753a6288eafc141c797ca01db044d +01029,0x3dcb5e2a8b6791f5141c8ff08ac59a36030c9436e6ec6de8274be01fb81112c0 +01030,0x373e75f1325d787a5f7e66c6b888083a7b1b2e6250d2764bbe1b4f1145dd9b72 +01031,0xf06e62b5bde482371af35d2b3eb05bc4e9f80da90c64f9a36c8405bd0779f123 +01032,0x3f19793eebeb6aabbbaa055ef131d73f1186be249bd8bbe2b11af0dbd783cf7f +01033,0xa9765c1c7bb916043bb42b1572cd96f905c3e2f5fdae49010a5102a9eb4a700c +01034,0x1dcfe01766b650af58d6becf6de168e7da980e7058c7b6424da1b0c470a7ebca +01035,0x946b550f1e19e68d272a10be6c0a1f9310da704cdbdf518c8a90b694748a8c29 +01036,0xb953b4b78c6b2446d60625b65ebdb25165d4c9a46916ee303b5daa16029257c6 +01037,0x8356dd445dc79c97a83819c8538aab5176664d436bfac3e9971b1c9cea78022f +01038,0x3cefbeb9ce2ed071c7abb2b55fa1f8ced72cf1f2f9bcc24955a17aaf1eb99c29 +01039,0x4765ee428148e60b0038ce5034cbaa7259b0d85403d37936cff1f1f220c09419 +01040,0xc559659c692f7eefd643fcfdebf8697a04634c839b6e1724382b3bcdfcb15170 +01041,0x1b1f9767d845eef02506d6a6c54fffcce5bd6bc59b41b00f17ef06e4c63edede +01042,0xed5a8fb5f2b0ab802832bb99d32a9ba463945ffbfce2f56f26e9c39fda1c3fe8 +01043,0xa396fcbd5b63936ec43b6bacaf2b0236783c638eacc72614daa29e792ffe1ac2 +01044,0x33bd34bdc9b4c51f344e476fb8c97fe80cfded7c90de437f100505b17823c66a +01045,0xe62bdcaa8531750ae8fc247c76445a76670077643060efc80323e864c2c2c480 +01046,0x37db60cdd4270773f870c9cb8eb3368d0e1443789dc44cd653b0f423addab3c9 +01047,0xd02ff344a0e66526266e7ac1ef9269ee132e793c2a3eb2c20c95212665880232 +01048,0x27c44206ef714c1ebdfa21cd959c074063432f3fdcd7a3b0b2ec4375e12ba53e +01049,0xd74dcd433ceba7a2a6702e807c68470b446772565b466b0878d4518983640500 +01050,0x583482c4b0a752dd12430176b663ff8ea5fd11f2eeebd8b956702d0eb473a748 +01051,0xb1375fb5970e469451f9e7b9a29f3b20ec0c583ec90b79fbbf38f9e981d9a9ea +01052,0xfc68a5dbc89395b13fec398a9ad78b00d813fbbb259f005e6fba1eb1bdc7f2cb +01053,0x038d0dc543117df0c46ca6cf4467721780eb951017373d51aa88ece1a380f56c +01054,0xfc630d10c00e0f843cadfac7d24f8ad02f7603bc7555efb4fe7e6a33d42d8fca +01055,0xdc564afcfef0c40d16d7fbfd90afc419bbc37fc750f790130acaffc32f985dad +01056,0x75fba5d5c98ffc1f67f8a1ea520808f94a547003fa4fafa34ba7f9b2dfab7383 +01057,0xf2a347f31fba049b5994122c3d6de4d37196ce8fed6c7c7b5c2c6926c28811c1 +01058,0x7e00f70a6b91f77cdd78c01ca54d506dcc25f226fbbd13d56b0c80e8c80c2694 +01059,0x7c557845f4abf757fef7dbbd11b44e44c92025733d16b57ebdec6ae10f381f38 +01060,0xd6b988695e3c2a57b1d3038de5262349766cea46600f70b8cda2998ae395894c +01061,0x7edcc464ec0b7bd04070e80a4795a4d59581d9d6d53756eef10ae5a38b40259b +01062,0x84fae3dfe3699b7ab0c58b47c604799d1fa7a0088138efd63cd4603e79cae112 +01063,0x97a50adfaebf0ad4f60329d82fc6fd897416be8c698e6a6d3b6e7da8934a2f97 +01064,0x25e68a390fda36ad8fee616a22d79cfc531127e6c8cbc11710e8f5743399d9bc +01065,0x88ea91bdc01e8bc0fdda51dd2abbf05a92a14c20052dcb563faef0bcaaf5d161 +01066,0x77a58ff5479dab194fa000221e98fa4e6dc77aec51aed889bcb852db57db3d03 +01067,0x95926dd93886d32de8692bda38da9e4ab10f9026ddc5b9ff69c30f55e0915ebd +01068,0x9e4b22f0088519c08bfd6cefbe125caeefa43b83b451fffba1a87223dfbcc62f +01069,0x5451d56c823a2e8d42ad39859e0758b8a4829a11daadd96ceb4ab2b29874c7b2 +01070,0xdd746cbf406b80fca7b25d95961640fb0ae5d411468001224c3770b2554b95ec +01071,0xe7162b854ae8194deb0bd3a34eb77be0bf539ce76c566ae2e05207968a908b95 +01072,0xa0266c3199c30bb4c8ec4b5797d112795c89dbfac6478dd5d3b772a14158fd69 +01073,0xfb390415ebb31243ff63e550cf27cad325550dfee0b421c1c1be75a845319585 +01074,0x7d668fd503ab1327817d49218ba493e6174918a03b3120133126c453ca345e20 +01075,0x38bef7ff6fd5999f6446ad8abfdf10a24045ae1b837b0ab70e1db500eaf4cead +01076,0x55f5a07a76490536966de1a99fee90d723ebae9e8d0806d9ed6f1580b2174db7 +01077,0x61a13d92beef22d97be7f3c1656cae6760fc08e36db7d381d5c96222fd50f864 +01078,0x227e71270b878bdc138b23386bb7b33cec9175875b461b04902f4af708c31580 +01079,0xf1a39e59434a97dce0d30cae7bd6feb571827cceb3ba57af6af183e953c24b6a +01080,0x1b7d09908d41e6463da4ef25bc4a7e2545528671a510352110cd382f5b300d8d +01081,0x679b43594ec30c0fde26f3a2e05561c7e110ebc15cce1ec5b6d7da2fc5a415c3 +01082,0x5e7dea252df625a366ac47bfcb1e8eb2df49d44d0be463f98ba95d256d6982d5 +01083,0xcdcb8e564e8695a687939ac1a0fd1a0cc5dbb352f9cd24427cde8360b2a9f200 +01084,0x5f2ca307599872cfc55256ad29009b53f3303d024b5b782a4abb591c8cbe5a57 +01085,0x12230dff9cefa72d522ebb791d84eee3ec55b5c4a4600209cab7c376171fa159 +01086,0x6eb5d461ec98068957cdab5b2028bbd8b1b2f7a221a8ea9c8011071da37d7b2d +01087,0x45541bfe08784bc6d1298d97e0308241efaf18a47bffe4894dcc26ef776b7b0d +01088,0x09f2f43ee828665d8d45859b5e36a8b9d31283550eccf4f73b1a87638e709803 +01089,0x4519917d2bb898a1810ede8b13275e678198aa773f7eef2b2c05c129942cb259 +01090,0x506362e6d66ca9341da4fb5706d690f94711b6673ab9b7d7ac22dbd39e0af8db +01091,0x408e7c249b773c396ee2a412fdd8ef7e43fcb5538e026aedfd34d7b9b721e60d +01092,0x4f1216d3d70323582c6544bf9c07bc6bf3582ddd01a52550b257b1e078dc12fa +01093,0xf7943fdae6b71a9c1a6d7320a61ebb908c32b91e8c9679808b09da9f28774225 +01094,0xa2458aba8fb9a34aa4b4a5ac20b23f843e8b12929bdbf793499c0187de963643 +01095,0xc3174a59e85dd195642088336274f531f551c50dbadf407323d0d1d5ef961bff +01096,0x5475a30e12c46b42b661a0932c94efe35bb76575dc0030255dae625933f32712 +01097,0xd2ce1e42bbb308bb9e0abb971cf5b4d9ab1cca8fbd73d11b3cfc19dd0b3b235e +01098,0x5fb12ec44e61e8a76d79d4646c09a67627cccf3576e52206f580364cc03080de +01099,0x1cd92052c419c186c329a14c7bab28a4496c23e243635d5a263a3ba34d0052c4 +01100,0x22b095d488d0fbd0f10e209b322ca59ad319975d6d3c90a81d1fd9b6d0243dc6 +01101,0x844b63b3997c0468086656f4733991f97ec42d5fb1b65c050113d515117bb756 +01102,0xbcce4dd3d6cd5b08a76bb8890eef30ad7df184972df8a271648de5269fe1ed26 +01103,0xc97117921c0dc002265d161013da1171084008fe5b51d046c695b5e626c9994b +01104,0x5035027c4b5ec5e2df56117a2e012b79c9aafea7bc89a3015e9061e226893245 +01105,0x9331be3bcf98379d8a0e2f65a70785c10fd620d3fad050315c2a1e2f6c8bd6a7 +01106,0x901078cb9b1d4516ecbda207acb6e6e2891a134b0c80b647240fd8ad50016063 +01107,0xf8edc0d4190782ba1a6bb98105a33cedd5d71c25b22e0138d5bc5d902f9f5a34 +01108,0x42362545904d6792bb88ae2a9f7d29b10623e58260d0ec47749781227123a2d9 +01109,0xbc521ceaa2bd28faf23c9f256b2b24c98bfdb90a020d25216026f95d065eb0f7 +01110,0x199eeafe5585e55674bfa0a341988e470b65ef78061b3f20eade8d1e271ef3a6 +01111,0xd34462829eff8702ce5561c6b1b715e63c8a89b7f5eb274e8c5588cd15678ba1 +01112,0x1c93ba5b0b9c65421fb9cef8cd24cae654c4ba7d386a53b6036e4019eb517c55 +01113,0xbeafcef83fc5e6769d82b3c304c0cbd5a1add1277e1ac300f0bc5c7e2822f2df +01114,0x71ec790b6d9c1f8e40159317162256dcd6f52a700215fc61d329587c64b248d9 +01115,0x6f6094bffde8d3ae31ac86b2ffa489481cb8b4b440d4613edb06f5e40f0effc7 +01116,0x053afb71d72d02a534cf646231ef23fbcb10a93ffbb85b43bf6364a1b6cc2015 +01117,0x98396ff4fbee74940a9a03c33032d84f7285608a0a3ee7c58e016ca8c42157cb +01118,0x5747971200ae6086c2054eb6a3d0a5307b84a2c2e7ce4dd0b99fcf278b5b066a +01119,0x1554c47385b828df19e22779047108210de2c8a34fd0346f77b9a80c630637a1 +01120,0x5db300fa117451b25a6f7a59a55e33947378c5216687ed6ba23f38a721cbc21e +01121,0xb9aeb88a7f2c33e5ef7b0eb9e4001ce50b96bd4576f174ff5fbaf2aaa0ca3cff +01122,0xa8849157cde19e3801e69291365f8fc095855ea313f1a6cf5b39d1f117ff166a +01123,0x0b7bcf33f4e42502cf5f0c981f1103bbb8f9c98a0a4a02f3ac10baa8328906ea +01124,0x224f4405f110ce6825bab6f6c209a4b5518894bf489795e92195a87013406ff6 +01125,0x0b6064b3c367b296c0a422c00bf4606867164d315c7ab16d89f1ad2957a4734c +01126,0xc7344cf278e4f244a49689243aae7f3fe30e1ce07e5aba04ceac1cc40fa922cb +01127,0xad12ba3851456ed8b37c7f21c8825c885a767cff2bb776be648cb8356946cb0b +01128,0x3a386e6dc1d155d89af575c544cd88581c7d178bac55cc44f63b2ee888223764 +01129,0xc77dcea67936565fa9d9eb078ce575698500dd17988daf0a7a8f246ff5508833 +01130,0xa25a8fc183706411fa20ed4f3b2a68d96e0b161fc09468f33beb434c48f58bba +01131,0x0225209e1b7c3463f869898432742732f32fd1e7c5f64e5ed74adaae2eace9e1 +01132,0x1ba9f77cea8694123218706715d4224221fdd5af2b022d015071d6443aa3a1aa +01133,0x8e1c1d63b865ae597bfb51c82899e0aa4107a88dcc6ab180ebb568c6de993700 +01134,0x3197a1d6c72f1891609283366e120a1f4c61412f83835684f28901d35249a04a +01135,0xd28f2c9f79253b151384e63f867a55278831d92575d63ea0a6b14f39f373161c +01136,0x6cf8d26d850172c2e2bb9629792fa93afec55de913957c778fe0895734ae70d4 +01137,0x62215680c0a6143f5f66137de7a13356a0d1837fa842aca997aa6d4eeb1bd7d7 +01138,0x44e4142c95e4d04f4b598a4146c0fa04fde6db6afd78ddcc8be9fd16018ce72b +01139,0x1a70666e7cc7d475d738b07cb5e2984097e0e30df160b1d9b0698f33a9048c83 +01140,0x9bef85d30bd7319c6ac73e9195d2fb5a87900b61f09eff71ff9aaf6dd39d6c8e +01141,0x48066cf2b5c1a5a553ecd2ca62a466bd7e462a9836e3108fa9b9c50084109d71 +01142,0x112745d12d9f1ffe670ec1b1b1526ce0b586f0348788742af013d8b5ae8f1e50 +01143,0xc07f562554568dd0a8d7d83f4151cfa979abf944c364f627daacfe42d6c8e75f +01144,0xff3489f3959c367261b35a4a8cd106e9b8e504da8f95c752126874757a68d8a6 +01145,0xaa9a507ed68dfe695d15723f7f31e32977b1aa74bb8a948c2edc27a55c6b377b +01146,0xae05fa5d0e96ad9e6fdda36bcc44637b1a4b9822c275dd6b0fbb7471715fbc57 +01147,0x0dca795f11fbe372384ddae72721019ac51bb29767f1de14c808ca5278015b6b +01148,0xb970027bb776fd436f03d55bfc77b43836eebe0391f2f2673a794e5d9648ab7c +01149,0xb2f6f5174d78083b50511b907c2e86378294179e05d89fbd98baf0996055f8ba +01150,0xae9dea31e94ecadfec8694ff8db30c1527a1b4deaabc042794cbf0f7ba068fc2 +01151,0x1cb2b8d45a6d2a7a1b43aacd57d78702ff161f96b9141d8489ada32fe1c8a705 +01152,0x28b41e3872cd3343b0901208ef472e26d98ee3facb64d2787e6f1196cda87d09 +01153,0x9cc1f6f0ae4b10e85063dbcd30cc2077a2eff89daadb9ee3391e9c460e39d1cc +01154,0x1d470ae11e0f409328f29e315a1881c3eae67123d48019c748a01f4e4f381aee +01155,0xb516307f14425bd9ee0434ccedb692092eff147562ee7805e0c6e0df0a475d7b +01156,0x8c4c11190ca958c76cad26d8514fb383ee51183c49eb56ab2aa41704249b6ddb +01157,0xd7bb8fbd3048f3b139a3c64191ecf38bf1a218dd9544903b8ef3d0e546cd8af1 +01158,0x12ec0becbbf83afd68392f4d9b67d5a8da89979557cce60530735a1465c0fc6c +01159,0x4fafaf52d0c069b6f587ee7a519e715604f4de04fca1a19e726671ac56596b38 +01160,0xd0e1b363591af53d56c1c6a146bb78ecdfec21f12b34759aa832501c89c26a40 +01161,0xcaff530399938686e3364b6b228b3ac59e3b22f21b1c2b3450118170fb281836 +01162,0x070dea605d09f3096df0b0f76948df8a38831c90c4581ffcf6fed7bde0cc268a +01163,0xd285b66ebcd5852a1911fe5599702a89a0dadda1405cf84dcf6d55bcfe0f9578 +01164,0x2eb4c50feff7659cdd8f3ef48b6f9175a2a4b891d09af13bd0b414bff9b0bcfc +01165,0xff4e71c2c49d497341e7386bdca329ab892c94197d5fbbd18166cd48843de333 +01166,0x4116850a1bd36ed591c1e95e3cb1aace3675a61d1c86e1660da988d5faec71dd +01167,0x5b6986455f3550b4faaa88fdccbffaf90f897971254d9b8f3ddec649b5260b5d +01168,0xa23912b4a361e10bdd6093479763b042c8d09f8fc8a5909170b57b6aebd98339 +01169,0x0737b4e5ab8f9071f44e61b66da61df228dc0414f3ba5dde12b7a8fb10b2e618 +01170,0xdf35982e9c74b401291f2ae70a09ea99766219008b0e01880cf6302e9d62b60c +01171,0xcc7466dda5723a0c33c326d1596717848dfd0256867df4d68deaa8adc3f61db9 +01172,0x9abdb4aeec79e7dfe79fdb6711da93c071c9099542344da75fe1d968009f98e1 +01173,0xcdbdfbc64a23515c0dcf517dfd71825cbe5d9fc98566f9c6b02f733e8a1ba3ef +01174,0xd79c75b859479066f9caa316c37f67fb7728dfc01a0d94f6a27ef126ac0692cf +01175,0x0d2dbfd717f62ea857069cde24b45df8fd214ef044057175265d747411304051 +01176,0x94adbb4c520dffca694df807f479af7b035da83f3de81f014e28ea2d34e70adc +01177,0xd5e0dc5aa1b4441e615373ed2c8782ce41b20b2a7816e81ee4311c243d3b7be0 +01178,0x5c34962d525fd40d9c8bc44f522af67fd89111d332eb9ba5cc9b0f138a4059e6 +01179,0x1de75523ed57212207b3227983ba8bbed7607c3574300abdf11cd1a372136e40 +01180,0xaac82868aa7edb8173d1d41c6b0745b7eee734182d4fdfd54e6043350afc116d +01181,0x5899663553cb5e7842e72b43a64d86113a4b76aaec2b0774021361171aeaee29 +01182,0x74b8aa4405d31335e0f8eb310028c7d05972831702b931b5f28d5afb3d52d854 +01183,0x38d8567174aadf1166952a632dcc85d4a4b8c20c946f2399878183141a10b561 +01184,0x2a82d902f0d2aedb663fe6998f7abaf0cd666aa3d6bea64e81d8d83c92b0351b +01185,0x528d123a4c8b57d0b25864c5b3f673c21fbee2a1826dab6cd6ae9ee0024e85f5 +01186,0xdcefe6dde10acc340d071c61813392ec065800ade9040e5b721fb20fb8239a7e +01187,0x25b5519cbb7efa28ff1b23d0f46e38f7b3b2c3fd96d493c5285991894e371f40 +01188,0xa8eec3288b23734dd343db2bf518380753dd2f602d80584c1a8247f2e2e3466f +01189,0x0912534018135146db16c094d6a7a067062a455ba846f44be4d79e2c47094417 +01190,0x13085b0bb2b86b44d0fd7ea1476bee11b641b11dba8005afbf167cd3526855eb +01191,0xe8d4138f22d8fb0fcb988bbded449ceb966203228554022e6e0564b9ed6ea1e4 +01192,0x7a4ee2172c8081d3f6dddf4bb6c561c8ce3f1af703ac6b591e448c762b8f1d9b +01193,0x7c6dae3a659f3b4fad0b797c457a546ef174569dd60a71b6a4fc1e66d1e1f268 +01194,0x7d063ead7a3d4d51dc59256b72738faf2171d7844da6d5be42af7023f690d979 +01195,0x68a0b792e3b448d4c36f26611d9b7652585f23f216785bb73d5c27c0c0aed493 +01196,0x94c969763e706d0e7fba95c4c357b0e855c68be2dbed2e9a7cf7b5daaac5a08b +01197,0xa6c39440cf6d60b35b0ebc651ab80a101b0f57d9163379474ccbeac8827d5fd2 +01198,0xf7a5ab53c462dba797a3b06ab177ba42b11a370240ce077b03fc1fa2b107f4ea +01199,0x84b9e12ab6e9c0e7f41dcd01aae0ae2357ed252b3ebd78c0b2d95fff5e032724 +01200,0xa6b6a963488c4633e7f3af99047954e1c15fab24793fe43a4c9ec2c933031f01 +01201,0x4a0c7f03de3cfd31752d5100b70f028c31856efa2fd1a3b5a8cec4a342500d34 +01202,0x5486c645e895bc1bdc91291f74d5ce702e1c2c4d37f005c6c1968c96c4798a0c +01203,0x08a5313b986a0428d49ab7b7f6cda4ede434efa3f6a69c5140ee7c46c977c30f +01204,0x975103710d4d4cc0c9b337decbad38e6dd42449ad533b3c464801bf10a0f7f8d +01205,0x7bbd5580e1faf3394083ed3a12ecc3efeec75b71b52f3c5d2527306d47d46c9c +01206,0x61e11a8ca3db52b16ec4c025165e73542fea9eaed696dc528b1fc7d08bab6871 +01207,0x3745949046134c86ab95f8da5fac1e0b96e9146b8dfe976b95ea8adfdeb10fb0 +01208,0x4d0cc348ca8825a306f854475c04b618a82336c06150b936407f793bb132e1d9 +01209,0x2008dcc12d9eee29e24645e17c3a32c8b0fa82423b230b1bca74982ff32499ca +01210,0x842d419500195cf77644f8d7f656e9e0c7044c7c0227eef116f0b54bd52b8456 +01211,0xa9c1369756e021602515ee071013086b92c4050c767db4f6952a5e875dc74415 +01212,0xa6435d49ee936444ea5411227769e4e92c9bdc5e353fb90feda369d0b357ca32 +01213,0x71e5659c8984140dac3efdb27964e2e36dabdf863d34d9a44509ab28ff76d3bf +01214,0x1791e683cadd2556b588f262ed01f10dec8a17d0fac17264cde17dc821d61444 +01215,0xb250520d667d2585a11f8515bbc942dde5271dee48bb2079e94fdefb4cd12db7 +01216,0xa13eb7c2b5320556bec64b033af8d17d73880423b1aeefd6befe0a80516cfff9 +01217,0x5c83a392daf6735cbd58715ddad8b5ee5ffab29f0d90e9529cca55f1e5a9bf65 +01218,0xc13220ead135c3a3c44eb1f623db0231af2a830eba39328d3b0eeddba6590b32 +01219,0x5f56b030ea9674db988e0e19b92ca4f4d0172eddb66b88d1421b761f43f430fb +01220,0x512900cbb649da6361f264485c211c79688543284d48129d978f50ee9110ed54 +01221,0x90c06f460cbaed5f47e45d4761dc4860400fcefcf38a4adc8dac265798ea82d6 +01222,0x096acd8679ab399726890ee06192292f292205150e75a75d8dbc24fb5b5c4e95 +01223,0x1a1baa666116d37631224699f89e17da92ae1d5df34857e3429b0eca71f473c2 +01224,0x34f529a2f72e1e83cd12adeb4dea7f2bdf3d7c96ff50249b27a0c6a65cadca90 +01225,0xad7198e0def6e143734a5dc947221958a8e506274daa782383fbe833e664d60c +01226,0x2d858029db92532563a3dd2e05e63de9600abd032bc3402b598df65b03b96f45 +01227,0xbb9ed6f343eb8d8aac3a7190c4327752c136b8d2d7a9cc4cd58ce619f2541c50 +01228,0x024d8b0934652fece1c1009e992ffcd5a39c0bfaf4b9e464b492368fcae0b44e +01229,0x4fbd23d89d82ef4034f1bdd888e2b20cd2338e5430326039cc82a8ee32242e3f +01230,0xb70e3603aa922716ba38abca5dc445639eff218cbc2ace3e2352be344588676c +01231,0x76e468cbc19d282a6075b218eafd19f63234beae51e46b0c2b81bb0b707b0632 +01232,0x7cd7b651d63b2e5a4f6684ae77ab9d3d913449a92eef5a716ecc947ba553b724 +01233,0xd077ca788a7927c7d2f8ca57710139fccb6e387c563fdc34aa9c8ca05ae0bf35 +01234,0xccf5a0f7216ad6bb2ddc6f59917c9d33ef237a7813b09052ce349a26bb21fb10 +01235,0xd7666847f3b02e9a581f7bbd41e906b894136b4f98503c2e2458718f08d319b3 +01236,0x3d10b1757feee8ce9ee56ab7d3e36b34895674fa7c6c90b2636e85f0a9e16368 +01237,0xcfc709d64aefa7fcd84780a576f8d229f3f093993a38b6271826efaba6b55b46 +01238,0xf6f1e083e51e96a0b399e5878186085e9ca7d12512822558c2ed1e156a72404b +01239,0xcbeef9b07ca5099aa5f6bf79fb7d58a0e8418af292e992b4c1f1d9bf43f12aec +01240,0x02688fe8520ef9c0a4bc424936bc9b710a973517598bf394274c2a44cc848289 +01241,0x20ebd6528acd0d0e507af27f82db0aef20556c9dd36f482dd78e12a39cf5855f +01242,0xceb89cc1fff1a05d00b8cb8049f5ba68b4e0fc338a5b7593e1bbbbbf4fe7c3b1 +01243,0x6ca6a14a6edb58aa90fc386305b46048d24dd9b525e204b503970cad8c8864e3 +01244,0x40769f6cedf1218dd656126546473cdb24657724170f0bd71c0ccdac1edb3e97 +01245,0xf2f56ea6ddf8226f222ae389816836c60e8fe9bc55e630c93e8d6634a2babbe2 +01246,0xc0e897c05df5e53027934987158c81a2dab1a62638db704cbacc8a2eb0c3931f +01247,0x58d2fe58f1fc86b6ed0e2f210e13723c8ed644dc8d32ffa4e55cc176b7bcbc3a +01248,0xe2cdcc7c61fe867dcef5ed3854538fecccc3ee1501b6e66f3132596c79c41a93 +01249,0x379da93b0902e34eca8296446820ad2e24d3e4feebf1f0faa061e099bcca3366 +01250,0xafede008f90c6812f90e9cb5a5462e3dad70fe5f0d0fb383f833845659bf25e4 +01251,0xeeede50f94cb63b7e19cfddbcc3f25e3c06dc4c3a83b001804ca440540d37d43 +01252,0xc5b81847b51e4e59f89d6cf2361c42f64dc760fce9f0bbd332653de1f7474ef7 +01253,0x96748f6773bb94d740ab82734c26ffc9daeb4c87606403add65897512864e693 +01254,0x5c3badc9304a265385eba2afff786a1f9464737b71d9301035b758820354da66 +01255,0x2599ae05afdf5e1b2be57990d21f985c0133406a8141639dbf33d46e632bf6e7 +01256,0x2b44aee4e83d46ed4a02abb9ca11c1630073fc6b233c5aac3730f8d28e695859 +01257,0x4952c5127010c24a46460214617a2cd34a5430ec398ba635392762668b21a64f +01258,0x713aba14cadeaaf4ac33853d6a33ae19c0ec40e02821d467577b61e371a53ce1 +01259,0x1ae7b5ef37e8a2151263bd517645f1336e0907ef1c840b41e8732369ef1d3cff +01260,0x6f90c321b6915a06965c7804e6e28aed175cd6d62162eff3fea564fda50fced4 +01261,0x61d416a84d212bea9580d2eba99ca6cdb0a45ea809d540b49ae52e6a2d9c5f84 +01262,0xaee21385dd0720113fea63062d20dc69e979bfcb5f295131694752dbfff3dc97 +01263,0x9fa06b72e89a042853139708961c7114d3197bd3c98c1cef71ca0b34c01652bc +01264,0x53a8cc3b6aac658c3b80f92e99521056c4035fc053b6abbd4068e5339dca35dc +01265,0x1366aabf8693566d39e974a595eb7e681f57170fa8d98c68e1f7a4397a6f4cf7 +01266,0x2631621efb6f486a6c82b58c7cba7c37dda933bee528d982b1c25570a45df03e +01267,0x3dd94158da7fecd20d03095ac40774de44befb72fcedb2f94ca801619b5aaef6 +01268,0xed99cb91c4babc2b4eefa48bfc1ab03f710aa2bd4c6e12c60e0bfe78e6a774e4 +01269,0x3e65584f39c73ae662991d6d27dcfe9563830c5210ea07a12bae36dfeec36436 +01270,0x69ccf142f770f0bc36ec796d3893b895d9b602100a30528dafa20e5a2c28da1d +01271,0x66fbd4f182ada36bac2d86fbdb791807f55f3c2c010c79d8fab7abaa404fb002 +01272,0x7f448c5eace75539049635435d61193beca590922f7255ef040ebe6da1f29306 +01273,0x3db6b5ee4daeb3747abef5998ae0ec1def30f96ff98043bc40dfce86966fde81 +01274,0x63adf378c2182a75a6bbec3cba265ead7a1d31cfc37324a5cfbd44e70d3e2392 +01275,0x0c89bb3e1a35dd2748bec8ed667b9345d50726cff25f170637c86382abd82135 +01276,0x399bff6479203b0d07b9409e2adbe174c602acc5f4c2368b4fb399dae9227b5f +01277,0x1b14df373ee827661a2c07e3796b21ae8879dbb62ee89588bb43e2843c70b624 +01278,0x7bb5b29535784cb002cef2e3e34d518d7baa14aa2242dd3cdfd9e6e2801faadb +01279,0x4ba003f31b565407c69e13af897dd4acc225a71ca04599415f68ee839e34d799 +01280,0x2ab6865f17d91c52d0fe177d6b465575f83380ecd7d8c7f9bf31b2377ca0a1f2 +01281,0xa55982471099400711214ced393e9909d0e04c35e862b6319ada8e63fe9c5457 +01282,0x8357bfd95a67b8e01b0530b10daa926d6368de1f37ebb787a24893a1813d61b3 +01283,0xb502eea2d534a1d9646b8cdf01a0021a2fac7b298ae298adfcb18a8adb51bf09 +01284,0xf9cc24977a6a162a4f21fea4c588d8586d5cb96298a95364e3cb1b50f1878fd0 +01285,0x5ad4fdc89fbf4b2817a64648f37a14ec2908b58b24a621a12f941d7e3d4e6a66 +01286,0x4de64a70d6df12d28fcaa8d4fed874f5aab3f070552189ce5e24582539c9f875 +01287,0x1cd8e301efbf3554bee4a3699272b01033f3a1087a8ea789132a07e1d08bd20f +01288,0x461721aa1fba0486391f01c6b60ec368e021573fcef4c62a0d91204470a732b5 +01289,0xd776cb85c9b392f75696d6bb5733b4aac5f1e83a73719620efaf40a385468200 +01290,0x873eb969707feb65aa18bb94c3bd32f40fd891708a0977ede54d80ebab7e17a6 +01291,0x3466a3703a10207162520e73c9350cc646eec8158a0f5913345e0232ec37fd44 +01292,0xf7c7ef3af85eb27ace55a2b8174ed8d5616f3d6d8457c51678f8c5ce5ff6df2b +01293,0xeab36fbdb3f08b469d02903085a59c455c1f8693e76b7005832a872fc19bfc3d +01294,0xd38b96b71d18f88b5eee096a8affaeae086170fa9636dbd6d81b7f0bf03d34da +01295,0x9a8e547ac87505373cd0a850b2dbcf87fd17a958e86b91f431dfacf8faa1cf9c +01296,0x044263f35cee7bbd103e6537a34ef16fa8075121c6b2ac6cb9ccc932de47261d +01297,0x2a6fa8404ebef74fb534dd65a52008d9c451c8e133a111118c38b238963d8c60 +01298,0x25e8cecf4a4009a8a3dfcb6e414a52939dd8f0fec0cdfa43fbb88f6d93e84d90 +01299,0x4783a5b474945636c48b35187b5236790a932a6688eb9d57663cedbfcc35e96b +01300,0x05128f5669874610a201918ac659f325cadd39c596246a946c95c17899f4525c +01301,0xf8ad3107c0c201f6c9c855fa7fe31ace8ea37cf483e4466de7ee0cd8d4a1961e +01302,0x564f335c0b20dae960b81c7fa6715da2a7a1f32186ee0d0fe6fc162f36a3630d +01303,0x0dd93fff7d2ebb6031ca921ae529ff7f0fa881b0b64d0fde89b532250afcb3ff +01304,0x20eaa74f7d74b90dd75bf7750d80ce428e75745d60b92500549b4039163e674f +01305,0xd00fc022fe14cd175a8a593bd0fc6cf8076872c16fc3672313415760c659de09 +01306,0x1f67a41c83d8ba9d5206bd10389cc97b98c2b2b50d46c845728f67421c9a8b7d +01307,0x2f77e7c868bfd36ad2e2b0864b665ab2ecd6671d8be22c1738d3c01376d0b34a +01308,0x8eaf029a66086147ba2206ecdbea385029fa3ea27ae9d93be466ef702f9ef909 +01309,0x0e9134c94db5ca1f3f8df20c06242afcbc7c099282c1b5662b7528344fd49f83 +01310,0x36d0712a3ad4551da02c8fbcf6ffb7fc9105d8b651095af88f9168884fec0ae8 +01311,0xb196f52df231958730a92a4cf0468e2648750cb5665142e160d881bc14e37bfe +01312,0x052a3539fc9f8bc4d117b49c1e06b3c2f6ff129297b39d25174c8f0b8144001a +01313,0xed3d98e8ee4b3ac94e1bf4f158c783a8415ba5f497f9e33a32f1800d60cc524c +01314,0x6711d975c455a06ffe37404f2c044b0212d05580535f0b696e01c40a38ed2e15 +01315,0xc90257ccd4b09a7a0b1cfafa86eae19b648f0f9ff4d5f9d935b45179c45679d2 +01316,0xd23ae50b11a0b68e4233b0743b3ba73f087d2e8d9e73f74c100faec8838bf4b4 +01317,0xb2c5b1b5c44801e3d93702395326af0a9e333f6faa72ec9836bc0c6da90af82c +01318,0x803d224bcaa3b2d5d0ba2de2837b8b808215de356282c671fd92e94b4970bd37 +01319,0xf7082c225833a231427c3a2809a4f77fd79ddf88a94991e251336feba0eeeb89 +01320,0x66c7f0046df871f8a674e08f13d66ace77969519f44ad0eedf44bee0a543036f +01321,0x04af06fa9d5d1b4d162b96a9e979d61028b349d2c474a34d16d0c62761252504 +01322,0x44c4c046785d0a1596bfa34133b74b47e16a4eea6607b7633d84e90ed816d4b4 +01323,0x570d0caa96bbae3e4b2afc7f01b62f3d90fe232cb3797cfe54b52c3840bba0be +01324,0xd4cb7a0d9740bace6d20e145e01f654c3388393fbc655b41d8693de6bb960506 +01325,0xb10b22ec3ae6d7252bd04d9bd6f2aeb5759cd1c33df99d43230b5dc2812fb5cf +01326,0xea52129a4b82c6183fc1713117ed5d1803135642c2544612dbdaa6fd06be1b25 +01327,0x4f88b08507b8fb608565635faa36f8b09902017b2dfefd8091b05cc698e072a5 +01328,0x83f1204e20b3770edb57289e7f64401d79365d0c0e02a84c9c2c33ffdc496693 +01329,0x572dcecfe36d6a5159f90810209186d900bd940b27e56a8d1150aa4760e5b99b +01330,0x45db98fb860512b9cbfce82e225581bc15103e772c385102f63aecc98b3053ce +01331,0x79ac113e80705dc36acef32fd3d844dcda82fde0962d92da38a07e585edfaf40 +01332,0x2e02ff938a46434155167db8bc7aab30bb1380b9e3e7a61605bb4b98312305be +01333,0x1c8da535daab62298766c9eedb38110eeafe1d6c2fc0a6fe344486e50d23d57e +01334,0x9983596d69c4ca9358001d6e1569a17f8c35a885ba9dc1629aca595c0475af7a +01335,0x4143f16c56cdd171e39f8a54a3bb2d2dea69490672df9fa7e30378def8867730 +01336,0x2c80acab236f71b43e253b5268c172dc3f413cf145e0216d7f6c13065422a2bc +01337,0x70afebf06271380039afba9d7b5157f905d89598d03042f4bf4cc827f1d7b200 +01338,0x0d957f43c8483a069456ccdf1c44cfbb355796198e5b35eb365d66189c934b07 +01339,0xa954d4bbfb037a0e8f081be2b609544df79fc5f84f346fe687c83055e86b785f +01340,0xd259e3dbd24e5d08dbc1cf127159be9095f93cb2e035fc12cd4dd9df06ce4d91 +01341,0xa393c46b554c380371d5f395f99c878959168fb83b010ee586dd627ea5ac81f3 +01342,0xfebdbdcdc98e1286f41f504e2457d4b9ad17d1747bfd60a3b16fba723620efda +01343,0xc205cffc694cd333edf5deb8023b04a96ae6563e1de4acb4d93f34ce095a50aa +01344,0xe55d1bc51b81c62134e654fd69d9c13dc329454cef1328f1579d034178625187 +01345,0x18129517d6e589a3e497f93dbad3e63b013dae40ec88ef3e1f3910b655442848 +01346,0x62600923c76a890ebe7b693e545c5f316a329cc622325ff9159159322ba772f7 +01347,0xb7bc048ba653fbc6fa6590215174988a56bd0615952242f026700ae0ed9e44d0 +01348,0x63f08fbe35edc8666cd54f8b313029ccc744b622842266a11085320771a781f5 +01349,0xd8f90a763e74c5cbcc2f745cd41dfc34742eb9d91665d71b201e8f8d4cdde52a +01350,0x3b7ca4efb889b761f25df46f30cb916074f5f80e5bfb4a500896747da243b54a +01351,0xa5aeba3be9d1c93c5d8cf0ec419893fc0d2fd193cc9d60b52d2fd7abe6cf4820 +01352,0x75faba094a42b7e78000daf1ed774e8ed6ecf34bd142470238d1d16741003ae4 +01353,0x53743d70a74f3b85815f71200d6c3c044df0ffc75fe8dc56a8f9a3ad106d880c +01354,0xdcc29cd5c2804269d16f68f212fa4318cd10f686761ba1e012a2bea667d8ed2b +01355,0x73301488b070bb8268c358f07b89b07cb19d2ec612edbd30c10c7c83349f0439 +01356,0xc5358154fa2c30230dcb62a3ae16f03ddd07e3fb9ecb53b0813ba432aeaa6743 +01357,0x6ae35c6d816695c2e73892ddb5fa55282a108796ddfc1059a60d14ee87ed06ba +01358,0x40401985fc52c0c38cc1951a0079728513e34711517fb89e8c8893f889f834a7 +01359,0x4f6b265815c3a8d1595aeb9e2039c9c73e06a69e746d06d3e4adbd09ade7ddfa +01360,0xd0b1559c6907e19eec7b32ccf02f63bfe932f3ec95d28de33250f0e2929b18dc +01361,0xef5b459d7ac7c2743f4c0fe6adee0d06a89971dcfb7d959f087b7b57f12c5d1e +01362,0x08dfe9e3cf1e444d51c5a61d42a03d90f974513c237d2f9684995f399ce35d56 +01363,0x80f7dfd0b5347cde3ebd66b78dcb3cf55cfcdbbc019c75e2f69bf9f97e393263 +01364,0x4b47710e8532de589c562f34bfa75a8333a26937ba10f86d7327afcbf0514cfb +01365,0xcc79e6c613537fdc17caef5f69d705741d3ea81e4bb6d277304d243aaae7f3c4 +01366,0xd76553f60e2e468719e30bd8cbfb967a00cf6841fc520c86d0aaf400db5defc5 +01367,0xd7efc68f4fdd73317255edf40a2be339ce739e5f0911f447511c763a494160b8 +01368,0x17ea70afa701eca1af56e1a15f3d1604a3fa7f9f32e8a60b52d41708d15d8020 +01369,0xf4a498dff013a59d243cfc41a176d2e7584d686d4ae44f6dfdde575d88529fe3 +01370,0x027e2a2d5bbcb6fd1867eebf440e44ac1f7ded4acd265d97ab1db0e5a1169cfb +01371,0xb90ef17e2d9981a11ef0cd0a735c7116d9a233a825903096e2cb07ea8597ef0b +01372,0xb47194832a5dc01344496c495b28e1d202ee22841c8ffa1857d05ce0944424cb +01373,0xb999269e83d06f6df620c6f5f94964f5a643fbb64dd2c4d7f58eed88798cbd6c +01374,0x662f1591b37f2982f426f3003ed9147f96014bb12963e49e63ad1b55e2cd78dc +01375,0x108ccbefa9906c080c5115f77f9ecd63381b9ffb0930227cb2630f4b08d8a090 +01376,0x54d2962953fce8d8a641bb8cd1c9eaafe89f9ac9546b8b277d9b535fb35a0097 +01377,0x6d7bcae503db8d3f3771cf9e8038a1fdf3987beb6212755704560a0404118063 +01378,0xfd477f0bf18d87a2bd3ae3c329e468a7bb16a363ec3fbf658f55ecb98fc16d17 +01379,0x57b72b9a11da9b25c2bb52b648db7870e039a64439fd271fa320bd2fe789775b +01380,0xbeacd779ff788ab12f79382ea205b1b180c7e43302e902c32fa577c0925144ce +01381,0x4b6c00275a131aa994d1e86e9246196299930ad5fc218d09d0b66265234e32c6 +01382,0x485b0ed3728e693a618ca77659c55114a8f602ccd71fa6138e87e11b49814289 +01383,0x402cc664b8b4b8dcac9aeba636f3c902a713874d9fc6bd6c7dc338817c1eac76 +01384,0x547da0f4446ebbba63eba970ec761c7a08451eb11251c91cd6427cdf475bf00c +01385,0x058c55b0a6a077ed8882d135e4cb364b250d392eba6ad4e578fe910c8c9f340d +01386,0x951ddf6cc9c8cae358c63a8a8b5037a970cc5a3e9ad55fca7e4c85bf86c935a9 +01387,0x85a7797dd4dae08cae7218cc8c2497b580ad037427bf7e351f20f1edfd695d57 +01388,0x64376e672282c2691f4dd0a88ccdb12d561cd88612d689f2802744490e275e10 +01389,0x58445b6bcd79648c107c45ccfa2c2246b0bffbfc0c9c8750b934894144105f87 +01390,0x6a2d6ce478b520818b85e08d1beb56fb4d6d656aef8f26020cc9a1781a4cd96d +01391,0x330e88ac3fd46d3b66946b2bd2e342e0906769ba42be06f01ed224dc7ae90640 +01392,0x3bf42cf0cd0e8199fffa9b453dea46a65409ec5430638e189e8f60132fbd19b0 +01393,0x239fa3d0c11c26d29efac03c04735050e83c55686975a8753bbbc83349316a48 +01394,0x76707dbf2c1a10e6f1aaa37be9374185d3eaa2253594e5ff3482e436841e6b50 +01395,0x4bcaea6c1d0723bab48d33acf6e6bcbb6016c405f710f19e8542290568510ec4 +01396,0xcc5b5c9a71d2e0b16153477cdb827aaf6feb3f0758218dccddebcf0e0f0bfb1b +01397,0xce3fa54e8a5338bf4a395b0d522e35d60b473c9f8507d6def5dd7da739aa5317 +01398,0xd06c9a048e07da77ad07dfd45f48cdcab8eac2cd6ab44fe9db7778498d1200ac +01399,0xe131599e0fa8cb136a8425b02becb4d42888bde686d9d88b6248216a583dbc87 +01400,0x1a628757bb1610b0c239ae56df58324c7cf5b5f3f18bbccea4dd67b1ff9be9a7 +01401,0xe7d4a88015acd605be12a616c899590059d306c69aff9a1876d47c276ea96231 +01402,0x85d3f3038ba81ba3c5c5a86cec0e55ecd3865f4bcb2e7bd9fb8390e06278ea2d +01403,0xe1e41aa6c6d1cc5313c8f2a0ba5c50098c30f49b4a8ba5ea8d89e334be0ffd96 +01404,0xeba27a233d1a0b76360d1ec6793544482a197f01a47d29474b64982d043c9807 +01405,0xb0ddf49dcc80359d5bbbd56b5a1e53a8fa78fbb3563c806f1a8a91b51cc8d082 +01406,0x651ac24a55b66ed30dc6b260af6a9b6aff2c1e0e8433534a353d2b9463d650ee +01407,0xa76ac2e092a5e5db97ef6af6656dff4aa47fbf036bfb5ca2dea8fe0dea9635e1 +01408,0x209624ba6ce8936b8a37223a76d35394b8a3e1c55f0e23dadd60da82e867fc81 +01409,0xaf729a25d80ddd3c0688e76207ff9ee0ef4960a696061fc1e32c39e69b40289a +01410,0xa53b25ca9678e87be1fcef929c93d97ac456308f8405be0910fc8e917f264042 +01411,0x00cba9ae4ebb3a6e3876f16c22db9914e07a4a175b582fdeefbb60001dae465d +01412,0xda3d50bfc90ee547701ab1777f4cc626aae0183fe5d1f42df31048ea85c2a626 +01413,0xfe77f727e1f01d1287955db0e75a11f8f1077ebe78a7c96ecaf808e22009fa9e +01414,0x1053d23c71dc7e09a2250926009b353ea3f44a599953e347de0fd8347d677762 +01415,0x1f9ee40833afefffc10bd0f240252f1fc70ebd6bd9fe7894816a369f78f40940 +01416,0x162769df545470c247d848320910bb169a9c95859e676d531bcae4ff4eaac292 +01417,0x6904f50508e80bc3f8fd40550fb06c98df9da1f1fce47c95e81e47a030917002 +01418,0x668379548128b70fe1b31b174c6daa8a0915557d1769beb2bcfab9f95884baaa +01419,0x55bb8c9a8b55e224e139cd6f93893700ac261f27a2eab8f2d493d734366d1749 +01420,0x37cb2c92be70871a49bcea2f3d90a6215a72609ef728c8e46922cbd6737c2c86 +01421,0x05b6cf1bb6f912a9a46dd729ba1ea392e517ad277bb69b758dc88ffb08313288 +01422,0xcf2496163a204528e56831eb7cad31b71b85aee9c8d584270c9728154e6a0bd1 +01423,0x8500cec01a3af6600559bd3f68e2607eeacf62fc773fe4ea467c0592c9cf650f +01424,0xf9b23ca9378f773d6ce3ab66eee7f70e84b52cb82be13876d2cb7073dfc765c6 +01425,0x2e9e77d2e086db1a3b04a73d17cc79247012b93c4aead1462d688857c983b16c +01426,0x8c07100577d5a565f3962df52798a8e7c74eded7237c57b6287308e30693fc31 +01427,0x53b8caf6ce7524bd3161dabdee75a7948cb6813045b9422f0243b91d1a8046d5 +01428,0x68be6c9f0b492c78b2598baf1e5a8d8c45a7738d41afd795fc57a6b9e5acf34c +01429,0x12a34f393f9f0f3e7630b128ba992bcb8bd211f817a4e14869d78cf465aebfcc +01430,0xff0a7be97f4019b220ec1afd81839cc10dc9c9d897a7131fc805393f82f998e8 +01431,0x64d4fc5bc06327b48928cfcfa93581a8f840c950551365ab35029583fed9b421 +01432,0x2205cdfc0fa6fd60df16cad0281d1321bb0727e0d9dda4e5695a415f8b0d25bc +01433,0xe4ccf7437255286798c6e3c8181f1d4981ea17ba6560bd9e25a86a4a558ec60c +01434,0x7720205861646892f7d4f654cbfb82e1efed9fa75fa779614a2d7f71a6a3546d +01435,0x467addf009150a231cbf58b439c8ee6859807d2cc444b5391288e84b73437e78 +01436,0x8bd916a854e374573059266dd6eccc83a260c544a246cd8df022c12864d00a4a +01437,0x332b343d821178fd9f67670662e7d60926135fbc724ac83e15f76ac77fada151 +01438,0x595d9cbeefcaf6ef0d0ca2e5b5e221777f7fb99a07f07f398759960a16ffedc4 +01439,0xaed3cc6afce54a6dd6c0b6a68532d860d99ad64abb3550594166f2a5d1086b58 +01440,0x41f0520f9167d87677b563d4652b1929a1cc45d49f59803bf30d288a1be2b06d +01441,0xe2a38fbc4c762ce28ad95fcd0b38b461fc43cf005e1c0efaa1a95e8b08496fd1 +01442,0xef37dd9b1d91abce595f8e07f4b8200ff75af7d59811d7c222ddd0dcd5657b8b +01443,0x145a661e91fd5f7e7004a06124642067355ac94d3812c17dd7e28ab63e2b3bef +01444,0x9821beb8f5dcea100a98816920637fc5644bb4aae4d43e14056546177db2d2ff +01445,0x728597bdf315ebb1b2ab95a2cc6bf7b4b4740e6e6cb73be78c0827c9791d614b +01446,0x5ad80991f59ab3c3f5d9e4b0a64a0d1622a6f7201e6b4c9ab17425ef0e9c6328 +01447,0x6b884caccbb53424351a0707fd38ec1780332432704f637261d061ce81669fb0 +01448,0x869cb3c70c4fbab00ea39f9b8954bd0efc32ff9386d347d7731b482ea2fa1035 +01449,0x5cac1bcb33f6344780d0ae7effa537b4597e788655c7f0ca76f6427ee6951593 +01450,0xb92784114f94f68de5bc7ea7ff301e8123ad1ae21211d9fb843a809198f34732 +01451,0x32f5e0e5826dcafa56e2102e122b65f91f47edbe4fd164774c5db7b3163d749f +01452,0xb43138d20c9f3a4ad12f1c6a14975528e934c45e0821fbbf924bd0e97c7ce091 +01453,0x34bcded8fb20b97fb638a8f0b0b88da53ee9e9ab8e31c2ffcecd7cd172532e20 +01454,0x11f80fd32648f792ece5e55a241f473f2733f6b2801df8be9679896d18947871 +01455,0x18ea77d047b2a9fb5aabac87543ec56952c28aac11ecee3af95a4aa559bfed49 +01456,0xf1aadb7cf016bd145d3abaaf1a285545e331a9878f8291692df22fa7ceb34ec6 +01457,0xd00e9e6ffbb61a46cb574900034b3ee2e8ab614b1182d29fb228603016385094 +01458,0x7ffab11d609947e556ac0f0aa0e92c8d1b7daae7c691e159e31bc2de3090e2d0 +01459,0x6039b280fddd6ba4e398335bf0fabb83cd421c12d6a18f18b9f60249e3456e65 +01460,0x8e889e14bc66328b31238cec0e5ca5de362bf8d995519de91c4c14a4f6dfd6db +01461,0x773c0e114f7bb0a7cdca0a604b930a3c77b35d4033a7eebaa8d380121a2441f9 +01462,0xdf1babfea1ab0a8d9ae94988ffd97916576340ee9f76a697b4d783074a15cba8 +01463,0x6d328022fe6152777777c85775f267864398abdd880baa956659469fee4c22ec +01464,0x1c7eb43c12aa64d6dbebe5f9946254cb7d4960e919112034b25cd78ba4c7fbf4 +01465,0x10ffef9e33b607326adbb5aabb35e832952a99fca4662af142510332b9033a16 +01466,0x7785bbd4cc92a53101de632d4335e09d7e3a7f8b8a2e5263d884c2e02f3541df +01467,0xb09a9b8e7e62a4ec64bef12e9b6467b0f7276db516b270cfee9b8f30b59e9349 +01468,0x1919baf88fb35ea864c6e86c74db4a93ba81d8c573d53716fe6cb56804bb4c8d +01469,0x6338bf7f5a36a7559ab4b7abf0b3882c81aa369425bcf4718ac690d237d6e53d +01470,0x46fb7a9b26b5de93dfe8027aef0949cc8f81c523fcf3e578e6ac296acd396296 +01471,0x18fb7c8f934ec0bd79726a6dbcf9b1949eae47eb8e8a59fc60821d374e5cad5b +01472,0x47a32b9d02c3f8fe8780885803d922d76e5ba346335f99c8b46bff9d33530a57 +01473,0x333b7e8665b4aa205cc4136efce2add43fb3803b43a7f33e9386790b0846dab2 +01474,0xfe24e3c1483ac948bb8e3ec3ace550f72726f2025abaf97dbee5997a2d7798f0 +01475,0x81c78370e6f8e1054f5492a086f354fdbbdee13fc5eb433d5b70f6bde808feea +01476,0x857187a16d206dcf5ab6d0f375defe4689f638952e7be7e214a18ef95f612588 +01477,0xad00e0b4f49ca226ba794de114b83f21049c9678d956ecd0a9456509a4d33b65 +01478,0x8994eaa1d20c7865333115069f8f9b5d500b0ac5b77759a7938c4a9817e8a864 +01479,0xcf4abf0e245ee8096e0a34974636acedc772135d2f99a493e78e84171c30d4fe +01480,0xae5f5367ea0f5fcae4b0cb50813b16611d4348211979e922c039849237dc7e0b +01481,0xa121c10e9e5b9ebfd54ddf768c22b1f9a0d99b1d002f0c14133b9069271a577d +01482,0x2110d171195a2de44d08df4b38a9ec39242e74e177a9a330137d2cfad24f0e6e +01483,0x56ec2844150d5baf181784999e0f12eedab61b6d106be33e2e5f4ae7cd9923c7 +01484,0xba8ad4f1b96b86c81781dcd63aea4d8c817762f8950ad31b7b516ec86dbf9c56 +01485,0xc56c3ef61383b31fe0426d4e7e6101b3ee93e36f8743513d6f2827f6dc7443e2 +01486,0x57bc41042e73f44a9ffe5ad0ef0ed6a750b254d6174182d31210ec154bd5a6a2 +01487,0x122d8e0fb38045e75447d5d4b098ded50d3519ab133f407f16ce80b7811f59f9 +01488,0x42b25fd38e95b67a02cf2d2420f3baf74baf05cd3daa21c7d8422dd4ef082073 +01489,0xb1acea4e751f8ab84a1701a3810b7425d7bd25b9a11191b8439d9ef021a0ae99 +01490,0x34280f11add3d4fbc26f35a2bc3163e20bd68b0b2c5f5c977b3c5515f7f89c78 +01491,0x503bfdfdf60af3f68c00940ce18790b5a4b27708860b9397c247b65ea306f9ac +01492,0x1b74997d1c74b3925d68bfb59f89532c82f8d40442462a20b8f8a247223217ee +01493,0xedfb26fba9e0f118447e4f1a2f427cbfe9b42bf74c74c8c347718c2bb25de638 +01494,0xda405d1305cbe42530cf2a03f23706e2c2f0d5c4a8e3fe402026ac7cb9e00c7f +01495,0x3efe0cdadae9231c400665a65dee22fccf36020f991fbc5fc80a692a15e04100 +01496,0x809b00b05e0da5745ec980caa06cd88004cd61873bee830f9da8d9cee061c0ce +01497,0xc6923521f989fdf033fef5f95561230bf2bc872c3be7088a3a0986f40417cbc2 +01498,0x2ef9dbc94aeec86917f3545afcf139cb1092ae35566cb03667d71fa7b4a413e6 +01499,0x23a65ef9fa71a5631cb9be2f1108a6ae5a52fd9123102d43b167267c5c0b6d86 +01500,0x17e97c499981088f01ee7fd4110bc4e39552c70c535b2c01bfb825288c652cd1 +01501,0x38815f395760557cb4ceaf43f9bd59d7f3ae3438d98e2e8e89a1a985d77def48 +01502,0xc31ef6bf0361e3147b5cfa201a4296245cb801a4933e6e3c7c4040789fe39ebc +01503,0xc5393ba2406bc0b84edc863f36c63116e6f3ce5b3af9063cda7516ed664feddf +01504,0xb478f53b462aecc80018fc12f270409c9c21616d076a98f26dbb6bc76171fc03 +01505,0xb8013f87cc39daaafdcd88f6338920b22c471bf7d7b589963a6ada06bfaea470 +01506,0xf23ee99501bb670f523caf0761c956324dc590fed811bc4f6471b6c458805e5f +01507,0x21b534cf9c9af1ea839aad996558e17bf8698d1c0b6d1ccdb858fb19bf78fdc9 +01508,0x9fbff7e7dce3188b5c5503deaa65b47c43c304c52f3f1f4fa5e8221759c75330 +01509,0xe5141a21f39698a7b78ffce400c185d65fc6145c08b97e5630b16fef5cfea317 +01510,0x87aec91b6b6a9b92dba7163b403a463f001693df580b79d1b630413de7c62540 +01511,0xb041bb19cce32e94aba5ab72f8b325fe14088e933331cb81c090dd64628e3276 +01512,0xe41b5ac2f66221e3e7486d2513c67051afc5530af04715e37c144c198240eb5e +01513,0x56a669268cf40b4111afe73a823da07e8a09f6304f8ab890b4645d2dfd7cbb24 +01514,0x898d4f37bcd23ab1762aec11fd937e9b9843e74b3aa9c0b4ed5645b03fcbaf98 +01515,0x935b5d7aeec407a6cd83f7d0dc160edc53cc8b7f5f2e019c05fe619226a5b67a +01516,0x4ad5c3e371e953f644173a234e019d8e14993f21100068a439bc901b164b0713 +01517,0xbe94d5d09346e617ac54ff3494a7923b43d7ea91d61fdfa4a1185af83e73fee0 +01518,0x40fa62d3a1d198625a85eb1afaea58c9644194914293db1246869aa4b7fcf547 +01519,0x110e8af3acb590972a4f633434221317d3ac98b9fba73452c02e9a88e9de32f2 +01520,0x6e412e20bae396e80928f28ec0179a1be7765947bd7e4765fe3b20524f60f2ca +01521,0x8ffe28ad29fdd6e42ccae7faf81b1715fd4df21451ddeb305a3eead7a514a17c +01522,0xe93cd0a078a29332cbd05e1570a988ad748db4a2b2f2dbc2c6bbab0bd3c8302b +01523,0x77f19add028523159fac380f499a2193f29ffde2ae2eb043719b798e272d2b3b +01524,0xf583c72783c0c5b90ab3a01c84eaf9ef04620259b4c1ccf074c9e74a22c98460 +01525,0x326bed4654c8a2f1bf96d345ef7ac8eb3868861e561603b5dc50c8f623cf6333 +01526,0x558f5bae98e6ad2e383096f2c381c126bdccfaa0c90cbbffb7480426f5803396 +01527,0x17af0f4e322b322401ff5f1c360a93aa4c14babc71203e78a3f9df4cf56f8f02 +01528,0xb3d28e9ba92278e4be3110b7813b95e05243fb026f3442e6961e686576399e5f +01529,0x6ce3df5c684e6d291db88d672af9848f1c597d58ad4aeb154d7d812d69878e22 +01530,0x70b295e43e231b6edfb2ba45b14964ca609d06e596f65438c816a8919a141d38 +01531,0x5694754d0ac3a99b57cfa34aa9a6f37d7749675127deb9dd45d920a767104724 +01532,0xb7d62fb8035796a876d44ec6b484ecafb225782c12885d4cbd8768bfcc8648c5 +01533,0x1c4ea22b6b5b40c697b2048c59cec06701c032ef4fc245402d68ab614ef4749f +01534,0x3f50bd7f0574c667cf8d6e4d96e8375e845f1bb58b5458a96fa4f13400978139 +01535,0x56e96bf3a208e13326e3ae64501a9f8aa2a2306551a22729f4cdc632a316dc37 +01536,0x4c0b5a25c4a9f692cb2d1d97cc2ed3a9c6be0263543702df9cfa818e67792ad1 +01537,0xb84376f6b504ac6eee8eb390c9431dce6d21ba91bf66860488b267e140503df9 +01538,0xa859e797a3880fcd290e20193e80d4cd6aac09cbe285520972863a0496ba9e5e +01539,0xb8f7332814753428b30912ab8eca0e635d4060a7ef66fecc91b9963f0d2a9b5b +01540,0x5075b4c47e8e56e7f17022c6c00170a30cdd7cf257d893dd917b6ae8725ef044 +01541,0xd9a68897ad38b7a6b7948e66b75312956c32f2d8e2b27fdf3df27bb1e523587c +01542,0x4c44c323f56a00e42c55f8e08134019f4cfa635e945aab057be327146e41b193 +01543,0xba0d8406b4b7bdb1f2a3c8bf6cc79c49d1a1ecb99e9a289ac2febb3f062a31db +01544,0xb730d9fb4712957266c8134e8ad45e064e9dde91be74a4bdba289dd2c1cd3b7f +01545,0x2a36dd0adc9b0a8ed517b92ef73ee18072f2ad87d992eac9b163ed13701c2d40 +01546,0xcb6390d20de04adf9ca127b68f73fbbdde1ae451d3d5dd2e9deebed712c49122 +01547,0x7be294479d6f126c3da2e73d6ae008ba912d377135e43eefcc6ca65e4e2d9770 +01548,0xd42b2e596c43feb99b1a292cb65108e4d159699ce5399331ceedd101b37e8aa3 +01549,0x3259acc6ebca1ee7695b4748c89145bfb0962571f616b5e2da44ac571746369f +01550,0x15c4efe66e352107540d4c8ce5d800c117a599da83ad34388cd17510682942bf +01551,0x2d99a1dc1815eff9f0d697fb3c79a078645b573ad228ebe569384ec8f747fc98 +01552,0xccd34c1ecb8f3444c21ad2f645b5909fe2c44e9f282706205f45c102d68bd3b8 +01553,0x0f3371da1271d47e61ed8a04772fd68751b8c7ef16c316b8f4b1491449354a47 +01554,0x6acbe79cf6301c23a1202198de9abad6c1cf67718f48928176459a2e195839a3 +01555,0x975db585f0f663c6e62d41199c823b48e1be2f596effa9c56222d3b7fdd48d40 +01556,0xf8d968d981abe306802686c870f2d6071547604228bc7c8a9e26600cc13fc18f +01557,0x5250d82f1f9476a10e99a6b6c8d4664c52d206286eb62e544c4d93b6c8141608 +01558,0x8817dc1dc6343f42591204b1036b8e8b9ac90aa6be40647b3c13fc48256b865f +01559,0x16cbfdacbf89ab417c81734171a541d1ebf55b17e4d62474a9883f9aa3b9d992 +01560,0xcbaf55ad5cf0f88bfa5be589394b6a7ae0907116fdee9b447b4110ad76356049 +01561,0xa12fc593dbc327d7a61fa0e695f2e6bbd10b70ae3dd87d32802487380d67334e +01562,0x310c6496b06f98c1553f27b9ef878db3e6b540a4008fb4de7d65cbb7b431f324 +01563,0x5345e3d4fb9fb5cfc1e3ab07b7963c5185b3758583fce54826b59c8f59fc2bb9 +01564,0x2280e4c1f8c9444f8a85a63a744b4d9cdaaaeec6c27a100b704c36ba1b27607a +01565,0x893942f1ae02af922386a011d94aea458b000e6ae58ac5105469f15ef5ccb00b +01566,0x237ef759964133b24b7d50fb860d3ef49f5b5473a5dfbb4deb12a9ee75e9d3c4 +01567,0x1aec3b6ed606a370df07ff07933d708e4b30892c5b34eb27a3c179089ff70c24 +01568,0xfc92fcf640f5c001fe4c37de77755ff442f5753d9500aba5636cad6cef432cba +01569,0xeacd9d2bc6090407814082b59e363afa47cb9148ffa584c065136e11c62413e9 +01570,0xa22bf28892d91ec239139c3c7bb07a32887d7d42f9a097ee919e8f1333abe8be +01571,0x1a439d0701e901619bf55f220dd81ad945b75883f0832eb9d1ffad360225825f +01572,0x947ddced110265caee947bc7d343bafd17bafff910a68db5bcc0f46f0aee6fc7 +01573,0x3a831bed82ec33cfb63e2489ca28d1dabcab3326a310e117ed3ff4d91893ad5e +01574,0x9028d18bb6a6f17c7d25c2c76c6faf7a9df0913107ee429b1cfa9e865cf3118a +01575,0x598f030e236f72cf6eff6d43fb7f974f911b9fc603980b37f15614ec3cd779c5 +01576,0xf904329742dc4ffc14c96a9917c54d18a6fde0cb98c47d211e7f7ffb83956ae4 +01577,0x8a587dfcf7eaa992e28ff6c3504df916cd4e01fe66fd293129ae957fb4426425 +01578,0x43c1dcc3d038599b653d4863c7c9bb7cad97e7b7961695e8956e9bd42f2dc0b2 +01579,0x92a983f23849ce276e11172312cf40a7aee0e9bd34c92f66f95a2b55ea9f3cba +01580,0x1c243107c6f0b4ef1b64cb91a8d1abe0dff736faf40a28e01448477799d7223b +01581,0x1f943824eeb9f6e597dd06662f22d72c259fe15ca30f79f85108fce6f9465c80 +01582,0xde1cad895c807ccbc04c98614864decb0b4f438b79772508210e542de31a80d6 +01583,0x2d72b6e45e90548bead586dbbe36d30832196b923fc15981b7a75b4635835cad +01584,0x393498cdb070387b507967acb20ca81ac651fc0112e6f8bf4275a998e87be113 +01585,0xfa098e6dd3f968cc805e7e32e67beb12ee8d5791c9ad3f4c4f97d8090c5d7532 +01586,0x379cb7fe8047796010944629cbaa6009c131882ada4df80b344f674a209a02ee +01587,0x62641130ea31f0236a9a003332e891538e45fa7190e93f9af17f15fdaa0f73e5 +01588,0x63224c34401bb9cfd504b6527d4005cbe3d274af04571902b23f4623b177a276 +01589,0xa972b2e4d5472258ad38813f7ab77a0daac4a0796875b562a65a989c1cb57dfb +01590,0x1370376c417b6f988efc6de15723eb81354087bb24b5be9affdd536f7eb5e878 +01591,0x3c5940a5c4b1ced8cfba620ef392e3bcaea154dd3ec56371ebb50f7d3955488b +01592,0xfdcf0f058fd21fd4db98eec51153f4bc489fb41e08c1a8dbf8f1d7f3ffe01a0e +01593,0x7779354bd2845311c515a0f22e8f032d09e69f3d10a14a013152ae46000edfd5 +01594,0xfc12f95bb18ce0bce9db6efa93b555b6108fc6f3241d56a25a2c07d8e18d4e6d +01595,0x2118c3d09fa86752bd92dd89053b9afb26337edcf84098361d149f3d9a8eb9d2 +01596,0xf94bdd17711158be2e5aba2f31d933bca8e1d608a0aaee8d611255e5822072bb +01597,0xaeb7c436d1407307f9daa397e49a35bb39d2b7612dcf4a40639643fdd06185cd +01598,0xf56b793b792ea72e3e3f8c92ac085de3c0b6e2a04a11486599b92a86c6abd4f2 +01599,0x6cf982a28fdaf8ff3086f2ab622848b9a1cc92e347202b0c3b5bc8da8669ad9a +01600,0xc6a9ee35cb2a1e7ace08025884a30c605db736d1b026cbca495b623cef531c78 +01601,0x0497bfd92c28ce3e12442ae4bafb6b8bb950448933fbfa5faf307a908385990b +01602,0x9a50fff5ebacea0ef3d7d163034333d6c0c133718fae765896cc19513d0e3ed1 +01603,0xa1d88a2633e02e2c4e08d94c97fd1b76d7003800f78dc3323f9bcc5af6d00bb2 +01604,0x00e0c17d808088777af62a97fe1e63d0a1ea1433c5368c5e7427bde3e7677589 +01605,0x8fec155e0c69236d83d2c7039e0e904d800eba28c739bad9bfc5b4c3e616b1a5 +01606,0x7642a7d34a91eb38072e60a0b44d304de3f84d42928c44891b8768a2255696de +01607,0x0a337fdbd42c275522b604f3cf7eebe86a7876ba0e93ad89fc725fa37bffa4b1 +01608,0x2b8f0227d5c0605529146c4b66cefdef9fded753b2f496b5d2232de3f0f0ff0d +01609,0xceafb20105e86dad0aea7a8cd971d4960c6e675d677a4ff5b467c57072e1c324 +01610,0x99fdde4b6905f88a904c45a0fae519384c35cbf770ac691cc2f972bc91c9e92a +01611,0x0d642ed657bd7c7bad338118f728552422e9d918fc5a6d45b276be73ee489fb6 +01612,0x01a109f9c1765421c41b740a0beeada7ec1527a116e075768051a865688abc4a +01613,0x409c216ecee281bfa9d2292d1483c07a83af57ede1d306c3ef1357e6207bbc38 +01614,0x608abfc5fdaed326966359b7494e26fad1a0897d36404404cdd1e9d760a2cc63 +01615,0x546296f9bdd48f7a10748c5685047652d24ee0f5d9d5d39d00c138b5b72963a3 +01616,0x210f4a03fc1ad41169c1a2110e9881cb518e3a91920784a93790ec49b14ca899 +01617,0xf300016daf617180a864891d6e395a1d693586922d87b42012be8d01f21a08c6 +01618,0xd126355b8481e0ce290bcd7d8e59ea88d84464af126c0711c4aace2295d81ec6 +01619,0xfccf39eec398431f05ecebc058d0f7451b0601e47c8a32403f430fee1fa91b4b +01620,0x62719ac2f5906f11574a39f6235b3d12052d2df36855880901e99ab7dc7671da +01621,0xd410e2d782f4489c884bfca0410d81ec6376b2558e2fdaa4329d57739155b4e2 +01622,0x3a2643d146858acc75041baf09f47c0f2d25d4f102c12fc7d3db22f670be350f +01623,0xb86b68f188d4f0d56f35bd8df010b9154c282c78ea9604ef6e94084e9c851b8d +01624,0x79abcea66a1e7adfb03c8c047ccc1823881335a68f7221a13f057b9b812fa6eb +01625,0x9d2445ad11ecdc91945bf0507eb97181e1a8d7373c3f68b0760959a45a32fd05 +01626,0xa0719f0293eda9efab5b6cd4fbe9be45f707761d77e089ab27c965058eed2737 +01627,0x3825eb62719002200fd1b8ece3f1fdcf80705657d68e418366eeae57b14acfbd +01628,0x49d1a71da4a7a27348aefd008cc5227b28544ee604eb242e1c2b037f67c3abdb +01629,0x1ec93093a36a54010ad1302caf7c5c24188c3d668ccfe895972a57ff6587850d +01630,0xd52d9f3e99b17ef53cb1045db3488f149feb348547eaaa57f54bf7aaf6d18957 +01631,0x438a5c23f506d979268a2884664886c208526d050df78870f68c331625ee95d0 +01632,0xb811a1ab572962105e233bc72569ef1ef980ffaec0c58c62c0e08744fdb23a7d +01633,0x2dba253d07386a24dac2fc5c78c557e25f4e521c2c5c37ebf514b9bbabd9f4f2 +01634,0xc0975217f67c73ea0f22c7475233b64524f228a7da61e6c531cfd932cee27109 +01635,0x926f0429fd3f751c428e5501e7ffbb006ad7048930e1820455b6fe404b7d8a17 +01636,0x88bc22af6003d122e5ac2b7981aefe48cc5e787777a77364dc12530b35d33397 +01637,0xd10229ae7c392518d3bcaa15f43ed0c2cca4f235cbe009e1aa711b109cded52c +01638,0xf60a479f9ebd1a81e807ddaa404c8cc9b855eb08efa4481810529674214b8c84 +01639,0x45574d293ed9b0ade09f8b041efd0f9be629979743111520a7c0224e41c36213 +01640,0xf4d925c6aaeb0d96944b66a46324fd09815af73338fe9c58c332f77869473fff +01641,0x055616453b16d6ff8caa12ea67e2543aa0fe47cb5c610699d5aded16ccdb72d2 +01642,0xbffe5d04ec76b2d00ec35af8ed488116f1d3d454b1476db9c68bc62590b91b62 +01643,0xdb04ce690ea5b0472a5f3d630336a0977e19517bb6c8443876e76d49f5876c98 +01644,0x836dd3c2e51dd27fdfc1aca4839218e9a40390bb8966c257d470c5e13d610d09 +01645,0xccdd4d3758c1b860176290f80a588cf9f8f257ee6a094019968b645969039e52 +01646,0xdf78d1aa527997f2f34dcc3df048e8273d4c2147867b13f009fff3fabe1227e6 +01647,0xbc1a2596d167f86f145df1c74a4ce5cdeb09e21c4f9077a7b7a75a026a9cd7e0 +01648,0xba4445506249f1cd7510b1159ba679867a8a721810502db35b871131a52f6e9b +01649,0xc772985ee13356a7519f619cba370e0d30b2b17faac8e8779b34e77f319c2f21 +01650,0x0cd44f84d292e1d1a88b51fb885b084cb2e3e4e9ab284c6174e1277fdc808c12 +01651,0x108b81392c28178c4f4fb98ed3e03860ebad588e089fbf85a87ba9988e27c055 +01652,0x92dc53a4408de761c673c56bf0c52c88cd2cd65777b47f65ba27265dcf5a4b2e +01653,0xac1c8ccb958d598d2591f82adcbce06cd05c5bc8c7714195f2808a42602cbd55 +01654,0x2f466ff62e6b2eb3193683dca7c0af52da1825c22cae69cfda8b187d2d719bfd +01655,0x4dc5edd2150d175af8dd28927a1529a52080d0e0d2075d0c6f703ec2a527ef03 +01656,0x72d321b5204000c80fd39ccf2fe72a17cac0eea2195133632b987461a4939c1d +01657,0xd0684723c2fcb39b6536736b92d24f7ca1bbb6b64c51c69ed69eae1ab22c83c7 +01658,0x651f1c70b5bd5638c095aeaee6313f1d4d2e28471ce7ce98aed045cec480d016 +01659,0x0013c08b64bf7e3afab80ad4f8ea9423f1a7d8b31a149fc3b832d7980719c60c +01660,0x7825d5b222a31cadf8cc345ae34eff92e4d617659c3f630037821d5acf6a5cfa +01661,0x84e21383079e4674dd0c63cb29cd89f0726ed8895aa83aa99febd249dc9620a4 +01662,0xa5681587c34c7e8d143b6332a98804a6940655b08c9764ee13f8362b929f15eb +01663,0xc84283fad5c6405f6c9d51c0597b9908406ff09772233255fe61a1494e09cb2c +01664,0xab3af7a0e7c174b428f865f4fbe6d49aab50b91a0cb5555687f2769c6c874836 +01665,0xd0adeec06347b843d108e4d349b50156dcaa131bc27c7752a1cc3c3035b230d2 +01666,0x827de27e4fa09f2ddd98223a7393881100fd9c533b55416b3839ad8f3b6835ec +01667,0x558e21250bc559d5e9cbf0b5c9787f4607cd769a3d96d4c174b769907b8032f2 +01668,0x8d75bc100e6afde488e081895914ea1c5658115a0e028b439e2cb2d52c02a29c +01669,0x84ccda7e5a2f253fee50e47559bdd8db96026897cec18ac128409ec405979de1 +01670,0x3490d679757169a0132ca44b3c408b53e9dbb23dfde34a6c8ad34ddd0f88ce78 +01671,0x4533f7b3dc71406ffa10a0af1fbb9b2d5cf61f7ae1d7a58c57734680984ef875 +01672,0xabf106295d76c72cbcc2b778712a1b954319d1b4a1365e19cbbf9ed0c39d7445 +01673,0xd67018bd3f840799601c348f8d2a55eb0d46ece00688a3ae5d7a699de71817a0 +01674,0x16b9e8771fd65164ad5b4344b67bbc519da70ca263c562c0088a9c30dde29cb9 +01675,0x35b0af7b1dfac60196dec285536cee1ff48d20579fe0df117be9566c78fd9404 +01676,0x2753d9cd14ed65494895baf136feef1f4c0096ac569e856a0b858c43046dbaf5 +01677,0xe40b2ea438c3da468e62d736f576e9c6bf89e7b2079569b11b7b63ab6b859e53 +01678,0xfcbdf0e3790abaa1ed31b64333b348ecdc15a15a213488f46d753ea77659d1b9 +01679,0xe5f342e28cd6a85862e29a8bc6ededb8ce9e5252f02db387ca6b27f234a1c8c4 +01680,0xaf511202a03e86af88d1a53657068bad1682ed4d3c3d446e4e553313c4183f91 +01681,0xd0e6d3d3842257da332754ff2e0ee2f28b630041e206da98093d60fd29cb2494 +01682,0x66ddcfa8295f3681fe0dc6fa254f4a86cd25127f247cde63ea7b310f8934f163 +01683,0x8887a5b6add7aad0916907bf209931a98364a7c2a74162ccbea586d2c95fc4fb +01684,0xbb0ab38ced9c5de37409997ef703c79d0d0273d0599436d79c86fb19710f0580 +01685,0x64bf045d836bd1a99dd127859286752a1c09c20fb5b8a70d2c238c86d6565640 +01686,0x7a8fba5b00f60ce646da4ffa64981c334b927fbbbfa037890aab81f2ae5c65fc +01687,0x26481dad4204488c03b357ab61f70c3e214800bd461be5b14a758caacbac5a94 +01688,0x05f0a17478f22868e8c1442a512807f1ba0f0ba7d2452c2ada4b0626b23b6019 +01689,0xac53e2ecad8e9ff6a20cd863627056469d0fe53c1e5ec3b590dffc853f36576e +01690,0x9dbcd976d813101a23ea057a561d714c26264f42fec6b5f3dd2f06708423867a +01691,0xbb315f50f96b903776ae3f1e1cac5b683d34104953c62bae500aa4b2a29d8a4e +01692,0xb877548bc73b777200804316b2cf7081152f0fa8923908b8ce8715126fbb3963 +01693,0x3d2c2aad64a353e2400dd1141f9bd7bab23dfa8aec7c2e5c42a1c52c58fd7cd5 +01694,0xd42cdf89f6ddbc2f8a8bcd4f6786cf73b985399c41328fd76c08821dcb2cb39a +01695,0x8d97b21795f44f7c853891c4f8007e2b9eeb7999c16ff0d81e744742f758dc7c +01696,0x49e0b594a63361d8cb35b386558238731b5b206702a2b68050290948b97a2b90 +01697,0x01b23d087a4adf659d9a5f4c65eaf4a3164b46a7398dc516a52efd4f2f8ca77c +01698,0x9c316b67ce5ae45a6ba25c46c1720b77741ce1bd7631e5da01fb509ca50ace2f +01699,0xcea5c210e2ef00d919631ccb5e68b178fb9b480062d13cc8604ce3845d950362 +01700,0x3d9833e9df7243daa3904d9a41d3808841ba7ea07998eb140d63ad0b82f49d5f +01701,0x073ad3dcaef6a4e5c3deec4d10a9795592dca55108e7fd3cf274ada351c290ae +01702,0x9c454cbcd610aa388489e7db1f4849677840ce1f0a3679e88d9e102e2b646aa7 +01703,0x0d424bdb826419a44bbe1435dbf09f15e33b105a97d0c11741401fb5e151f306 +01704,0xc842662446daaba43a5dbc82bb9bc5735a21aba5fa7c6a0642a2a645d2fb06a9 +01705,0x850425a72ebd6cac965b15c5411581bb261a58e2e9f304fbbcc1f6ec56a3689a +01706,0x5f7468d23fbeed676fe8188c346cc24453860c8e265373880ee3ca128e9f98b9 +01707,0x68199dcdf8d631885b4e264ef8160a64551e500f2f49aaac4e2966d6b42143fb +01708,0x1bc39088aff2c8759c5f61190c8af3aeb48cc644a57ec061b6547c97395754a4 +01709,0xac6bdf4cbd7c785c68ed288da6c280a6d1b7340e882e1a71688e56b31d237970 +01710,0x616a421395c539814d92259f0dbdccc436b6be78d1ad264305abc632fae12c63 +01711,0x675a2efc56ef5c385bc82bd826482cd8247801e0556f38182d2d396d7af13474 +01712,0xb3466ce1c9c6c1f1c5c8681c13442c053bd73443ebd60b0443cccf95717fb756 +01713,0xefe87a15350ae4b7ea6136f27efba4c610f7d260cad4188771530e46a85d96ca +01714,0x8a93b06d9b9e80fc6e21443ec976bbd3de80fa2ca50768e728598d44c6fce197 +01715,0xc53f6fe8560e2c1f79a629b335139dff42a166dba3a3f3cdd8b9f3c45c482cef +01716,0xbeebbc85402356009b2eecfc3e808aa7d6b671ce58430bada153e2678890476a +01717,0x2daba19a743ea4ca797c5c20fffea6f79979ebd83d0606fa86a38c02709d0425 +01718,0x69ddf701e288b58796af67a303745d123486204a9a7e0ac18b2afb25c4c9b61d +01719,0xac2ebcf440ba3a2ef280e8004918a9b6d849e19b321823a57132d7799c21a147 +01720,0xc428eb527615d3acc4dbd68d2052fe6db27152c73bb2b22edfe4d9f13fd67ecf +01721,0x940116cedc675ccdecfc2ace0d21817c7e13d57154dfbabd0ac759cb68fc7aed +01722,0x1aff873b75f990bea4c06fd212d2862a06d28047e47592b8809eeb164826bdf8 +01723,0xf19dc7c143cd5aac499bab456496409958bc496ed1b807c209069e5fb78089a6 +01724,0x50ba9e2446defbca234aba740d15221152d261f9987e24f6e9ff3833d2422c88 +01725,0x6244c9ba553c0a9fdd9985673ec8dc94558b1208ea0b2c09cae8baec14ef04ef +01726,0xd9ca0531bdadeb4a42bbbe600161d3bc0c29f6de35c37b584d463c87cc8929be +01727,0x019f04b76df87f056d3e85bf6100ad35611dce5c332f9c885cf4ddf9e4b0df05 +01728,0x0bd9139ddae4c9e202aa11614fbe037609445363727e6057db969600bc442615 +01729,0xa85a5ebec5a89cea73285765cd253a54806b53af28dd7577198839114fc037a3 +01730,0xe07d8fc1ad730fc509989b081ff643430c4d25396853553dde4bc01e0a5c774c +01731,0xcdeae685f4d356e7c5cd458638103aa02069a6ca2d8c459bbc49b9e3ac9f302f +01732,0xd4b05748bb2981bff1958a4dba0b0f59559bfd5f8fd4e32b1d6c94d0902e1087 +01733,0x2b75c3c9e417a3ee775e3f6d8b333588c4c8eb482ad9c611c73b8de9fff3403c +01734,0x0b51aa4b64600138e09022ba4fcd58449faf43f4b1f8a5e82d9450fec703516c +01735,0x5b7da9fdc48dac8163f0a2620536639c95e1f3c35f5d09442cd077900ba3397e +01736,0x2d581b4305c5b54aa72fbb2dea7f95fcd7ecd06dbafa7d1f52197cbb86cd7275 +01737,0x053468cbce94fcb5f0170028e0a585bb98000c005cbb0f9d8cdc0274cc3fdcf4 +01738,0xc4ea73550a711a24cdb631632d8b9826098f572e1dd0f5d338a7d571e40a0670 +01739,0x390296d239ff8e7ba83108c01143904890332e29c7fb89f287be70d9e446a4af +01740,0x0bc99a43bd74f339e60b6cb7235925e6bd78a56014979d6dd161ad9e2f65c9db +01741,0x831ca1406a51f08d9e8b7f9b4ae4e9b1562ec6b3a965e648f5fba403985d7c5f +01742,0x6ea854bc3a2a1cad0e25a07bc1a13146837088263c4b906a86f3aff87748a250 +01743,0xcbe74e160ce637284edac7282156fd9a04638631e32dde566ef91abe19e9d7db +01744,0xafde3d1a0a5c90a5b6a8ace6e0c51f287a7baa6cd52fbb530d5cd30d77d1a9e1 +01745,0x265425af9916bed0dd62a2456e7c7da2c9c0f07a25c8974425dc0f116865942f +01746,0xffa83edd16de7ec3db737cea195c255b9711b59c21b1497e26747bed2e13f943 +01747,0x2d7f0f5ad114008c8bcb0c95c1368739149923d73651da238d74d6e4f2e3acb7 +01748,0x7b69dcfeced3aa613f02ad7933e543e8dd53bfaeee20d90f4f1bd38429dfacf0 +01749,0xc08c96110c4d40c906c9f31d2d959c22201f86eade534578a58c391900fa278f +01750,0x6067e2dac2ea8b7d928570e0b358cb2bde6a09b5169325a6d553e6215ab5b5c6 +01751,0x50262a09aa1822e9da30e2dfd935d89e012d1d336a88f24d8db38e4ec1608284 +01752,0x0488926e04563f273a6ad741c30908764e8dac6e38d7032eb8d398a39b6e0f42 +01753,0x7477c0a14e3afe6b1210829b4fd571ddba704e062565ee06f8fc00631cc348ba +01754,0x646def35e15739fb4e6b897511c4a71c34b323e0107a079a03ffe1be11480962 +01755,0x84f4fc01aa6c9e739865d63f71d6860875ba166ea67b4aa068de28cb1adffc8f +01756,0x308e058035fe5998006d16d2b6f6fb289d120e402b96d10100c98e92efc86619 +01757,0x8b98854f27b4a6d80d520f8fe71c52fafbe55252d3df554a907a9c0c90f1de89 +01758,0x7c7bd9920cdb8efaed244a333152b7f205bfee6f2eff4e0da455d882b070ab6c +01759,0xef9dd1ae52176b521f99f60ae0a16baa1832aec7ce2b95c0e6b20cbd0943b218 +01760,0xc908c0cba78857bee8eaac7c241106164154782cf8c712987f4b6eb687161ed5 +01761,0x4c223079fd963774b68c0c75835a4f73a591a7f6647c09fa5def8021344fd209 +01762,0x58e9482fe6e25ceccb977c5945db92bc2ff9fd044336dbfd13714e6f84d9c99a +01763,0xe9b64e4399b811a832bea55ce15fb1a55718352899e8fed5cba324e196b4004e +01764,0x69d58dfd877a727ac73429279bd99ba2562eb358598d6c7f2941cdac9f3307bb +01765,0x565089600e60764e78b07382ce1e0acc93b255ac0d9e20b4ad585767be9e8ab4 +01766,0xe47ad77ca6b9d30cefda397443229cb1df5561c9a436fa9d94d3752dbab1b8cd +01767,0xc92526a4d2bacdc047f4e86f6a2b159f6c72df8157178c4ca89cda1780245b1b +01768,0x0f318bcdb0e0d78f54276c87b5be9aa21919381bf2e82205072e8c10cb8cbc21 +01769,0xcc56b7c7ff7ead6cf9f72199ed9ae0a94d5afcd7fc25ad93275a37cdde487e62 +01770,0x8a0d9bcdcf18b4038a4df3f96e0782f2bb1d4d84ef4932b73dd0f2655f1c9187 +01771,0x8c0c7922138320604c1287c6c0f87fdb37566752373a62c150c06653189cf070 +01772,0x490072e141e5099852008eb31e3b432bbc2d71cd988dd62a6872bd723f4464a9 +01773,0x441a3c8c2fe28eede2b4ed609cf3fca8740cac9638c5962e2214c00365a3a787 +01774,0x9d3c41ed132dc44de0d39c9d3dd4cc11c1e8a7f8f0316eb774991a9999c0f372 +01775,0x6023b5ad4e7a8f918fefab880f48288bd8e0da6b9e2e3880f17ab96e3ebcd618 +01776,0x848902b06524297d54f30c1ddb0c7629c03fb1ba49464244cfe8b198ff99dc26 +01777,0x56f9c62bb1fb7eb1575c94cf34a37b136b82db0979412504812d7bd21990d5a2 +01778,0x01a7fc06f4248e48ece709e46292bb7e0a69317fefbd38215c4c093a0d42e425 +01779,0x9ff0b05413db15b73284db1b8d1702ff095cce5810d44c6457693516ac3e4d65 +01780,0x0601be62d83f52db2fd5baa50940e9efb464596f0ed80d11722d2944f56bc38b +01781,0xc73b916a7b1049230c965741275142bf554805f395feeddf9a8a84934fefce35 +01782,0x4ff9deb85b08cc30d36d12e391e9ee9bb72a7db2cb52679b62cbae6059a67a46 +01783,0x6dcf0704c8afbf5b87adf316a01ebff4f641cefff7ba33d672ed51f477a2cf8a +01784,0x37725e0bd787534538108e890787fd1606569bd4db127d22da37f2a4f2373fde +01785,0xbb264cc368c6866747b9a711e14933f8d96f905bdb0b25a07cfcfd2b094a5fa4 +01786,0x8f3dccda34ec0838afc97c36da3b66c7a3c804709ed64b4725809ede5248dbbf +01787,0x8cae5bdc47bc087d43c41f973c4711ea0af9e5ae53fc5a2fa3ff104070524401 +01788,0x7e1c1704cf56b2e8cdf4ec7af790cdffcc0cfb3fa840a43ffd46d4fa0d0458a1 +01789,0xdb34d4b8ff52ebaaca16e0ee46cc56669773768e2c2473470d055004825f6024 +01790,0x0e2fc599445336cd593fe78469762a0eaef058edc4f9a10a7083b42578eb6b18 +01791,0x0dabc8f4f2cc029e70b238f3ba3f2478038729cbdab741e25e934f3828891e60 +01792,0x648d0dd207d0201595e12a8a30b247f7d51ee8385935ba68393db91c846459b6 +01793,0x77485ef35b5343f0b16fab3492a9565a3fabb6b97d3076f2877c489b0a808ad5 +01794,0xe291673e64217556218b47874f5d9d4c6bf392894f6cabd9f572cf4750bd4d47 +01795,0xd1d496b1a49c1b8f9e5a7e1146dca4e3c28ac4be22ec0d8764f56ff3ccda0e69 +01796,0x33a5546bb26b46559e6b72502faf6dfa1060fb41a69bf9fff988c463f6132aa0 +01797,0x34123297e57b8a075114c3698558387086e3a4b2acfdd54041901f952e7afb91 +01798,0x3ca0aeadff3449302ce20766cc4dc0b1628f85cbd26665a40b0f509493428f08 +01799,0xe949b50c73fe40ff59ab7e8b460a5c81a411b02931151d95eba96ba7e422b731 +01800,0x07cb6fc533ed260b5b01e470e4d874270270fc5332f423e620be1dd92b06ff6a +01801,0x8edf5827b93f9dd727c25e4cdf558bdef0c8d1962c993666fb469082ae607e6e +01802,0xf95306bb3bc429f9229f80e3fd50446435e98eb615bffdb379d202abcad65f98 +01803,0x4e1d05e25890a1b0b1f301452321893b91ec09ca755dea16b16fd8eb0d02a39d +01804,0xa24b5a4a59adcc97ac586cf83a7314357ae74c48d9099ca9463954f8ca24db24 +01805,0x81d9a9522808c36c1845abcc5a080b237f69ec54c4f263c31c3fb2738bddbf38 +01806,0x66534ad9878fc2792c46d45c62a93320cdbd40c276025bcfb786dda3b53e775c +01807,0x37ac18016b4a26060dde93000fe2b5614ae011c506725b391bdafaf9d613f8fa +01808,0x3f1a883d82a05988793b449444221a6baa67a0975a8bdc20bd5c8044fb059bd7 +01809,0x45d0f53f5567f627b64e808129a7730badce39d542584ac3b4e392e549eebe9b +01810,0x6ccaab76edecb5af607c5f4a741d30e9b9762ac77bfcac89b087ac9fdb51727f +01811,0x9ab98ad907f0df327b31733e17eca703d44c5315e0f3f381dee38a6716e9bbb6 +01812,0x80d86e96ae3c138cb93d8b83e1aca9930c3aef9845f19e164076a319c12b3d29 +01813,0x1b4ae400e53cfcfe9027f84324909f496fdba244a748a8786a8b6f30126bedb6 +01814,0xe0064cce975cf20b2bf11f501c61e1cfc5df450c0231fea9b29df7d134b1b5cd +01815,0xa2d0424093b6f41d5bc9c2d6bc63596e722f91e214f3453d692e27404d58cb31 +01816,0x9a493dd73536b40fe784e7710b23ead682163b5c2873d06fb634b41821df1d12 +01817,0xf534c5f3151aba70c4902307fd1d8cb8a9227ea3bfe00099879f9af4458f7cca +01818,0xc34b86c65e0db470eb8f644fc648b5520546535adecff743126a2bb394fb474a +01819,0x918b86fa5fabcbe1535ff25b9cc6bf18399033a10feab07b1b2a44e652c890c7 +01820,0x17e7111cf764fe48d55ae33eb9992d4fa0c443e17aba5ed8121665d09e719642 +01821,0xe118ce724863baafe5822a6df3eb6322f52b0efac93df5ce30f2890249a5301b +01822,0xd7b7b15d51895e067d217712e532f4c1ca318bec69483371d584eca1fcd35dd9 +01823,0x3fe7a945dc87c69c3c018c68cc45a5ad9d5c76a9623a615305eb03b30bde5286 +01824,0x6ad87d358fe720d6207c7189c458f01246ef8fdbcebe5bf977590c5053395226 +01825,0x7f98124406ff6a0ac572d6cbedd187c905ab77a2957904ba9df742ddd37616d9 +01826,0xc17dc5a387763a48690eeff9f15e2c8a17d46585c0330f855207bf83db5ba7ca +01827,0xfa5fbccba9509f70ed5a39bbc8148708230e37f26fb18b7a74aea1616e3e4609 +01828,0x540009e54254fad311b1b69490c7587db7dbf71ce7a15e62f94d49eaf22525e6 +01829,0x41ed6fe79b33dc5a32a019496131ea6805aef33a6aaf93982d37dd7653decb41 +01830,0x2afebfecd0c3c447d920747a1346c865aa846b0ae6f7eb900e25606c8d9ed725 +01831,0x7289db8d2960f6402252c8699465253d4e3efdc31c832a9ba82b535bbe39dfa1 +01832,0xb1198d248f79e07609cf29ef8984e2786258b474c17a982d2e4e9219af3d6592 +01833,0x0bef12618bd2905629f0c9d7427431884e203e70d78f5c9308a3215d79a28556 +01834,0xfdca337f0afcb8f508449dcfebafb6de99c44f1a468a0c162785b36b20c01446 +01835,0xa45d06eca259ea9bf79a23c0a8a50cd784fa072330050f7da63a0e4acd14b4f6 +01836,0x87fe297ba8e996cf2b1fdb854e86b043f485149eea31c3c74187402b58892cce +01837,0xe26e40bdb2425b55bd59c814f5839f7ff9f74aa1aa86d23e95988048d319e64c +01838,0xec6b0c035002b5d12e30ff8e3f97f281f562593eff842cf8905468c3d9c9777e +01839,0x07950048304ce616f23f40789e4f7995ce30e164dc5e35d97ab241998924b825 +01840,0xe287972bf569570a6f2f8d3dd01ceebff3c9c849706e2ebe133ce72dbbbadcec +01841,0x2a6039e5b858d952e07cbc9057a4506b30edd01944b253c0bb68fdc9e4616b6b +01842,0x5567d80f36494b4f26232e2a26f06fc382bdddf8b9eb7a20d56087f13e1cd561 +01843,0x3153e10ad6830573f85e149d79579aaa27e4161239b5bef085dfe1c86d2d04cf +01844,0x03b0963dd2f6917a141dcb843dcdc7b8fe71ffc51a29cf86b7f909ba9ff178b2 +01845,0x03b93b158737ecadc1a498bbe78e247ec652f5707571512674bb231e4c35593f +01846,0x3e05673eeaabb4293f6eba4fc8597b21e935e72e7d614665480e881bba552938 +01847,0x2de5f285569a2744c7dc3b94d992c655037d370f4f8d8ca04a26b4f30ccbf5ed +01848,0x113a0599656907adc266ada978194806c922455ded32bdb8578ddedcc0e31d8b +01849,0x71675e40a1ede46ed372c411541b1a66c4d76d33fbfd97db91b9a3a96a45e669 +01850,0xeb0e8dced91d0329228af294e8273236ae0a4e6f8590ed770ce6b8ecb9d4e9b2 +01851,0x27b488ec8baa7adbc492e5c2311f57d1bb025e42fb362933096f7dbf66112277 +01852,0xa405f5f3d7c35326f18a1a85fcd88a897d5e3a31867791cee9489042b950375b +01853,0xde7294f59c86cf434f1b51c11d36eec758c73de3e0cfdfb0d88f7ef4e6aaf946 +01854,0x1b3a9f72ed4d4521657db928917a7abdd71f4ba2cf1fa4915b68d1c840fe3eb8 +01855,0xbb9869151522b5034619c9983d1c21d253a8a46dfc03bdb7c4e8771faa4cd31d +01856,0x10e8b0ee7a9e05e342cbdf4cc408d4d207163bf652e9d45a715f63a14079b558 +01857,0xe0a70c38b92eb6cda8f9b7e2253b88bb8a25833d34f1174e9d5a3dc11d709fb0 +01858,0x96299d525632a3677163bc6f18e98439e410f1c3f0a0e561bcbb63ed8022b860 +01859,0x056f7f9b622e013fd1a31107cddb7843babb80ad494781ecc0408a4551a6a04c +01860,0xbe17dd25f8ad8b238b69e317126128e379aa87af72ab99cac240b4d6362ef148 +01861,0x31641a0876c1fef62d170f84f2c6113d88d4d38ce90538e30bed4565fc6a3027 +01862,0xdeb651e11a7f6e50e2c2adc32ec89af247c4c71763ab3d213bfca70b0e26c311 +01863,0x500103a06c6cf65606e2c734912c6448844b87904ee9d68c7be782ac5f6188ca +01864,0x168be6df9d2a7ba553609c9235d1cef41b783323f60f7c59ca210f3e9db4d764 +01865,0xd69771c57985c9c43d6195e8be9d199c3b3ca206a682a0c6c2a274b8294b644a +01866,0x3cf6a306ef85f605b6b8610c42f3200bc04bf7cfd1b325b8574ed2c28d4ffb62 +01867,0x69891a16fc79a0e6fd885f23b106806ecf71ad7b3e5d51a579193c4f2583dc5e +01868,0xfb7b596a80d0782f73d11fae09d7da314be8143b471193a28901a36d6b58d8f1 +01869,0xd864488dca9ec72930dbba8d9f554af78dacec003a6f58fbe05cbeeaa8eaca21 +01870,0x3dc73a6d1c0433c0d98800a9877d3e0e9651e6eace71413ae0f52a7bf58616c8 +01871,0xca53dc21977789285d08334ce43b0469a5bd54cf890a4ed1e0cf4543b1575457 +01872,0xd571c79ae2f0b29d334f8c33b14b21a83491d21da2650ccd9d7e3f1b307ca7a4 +01873,0xc71b3cef8fd89a79abb07c140f1cf9b90f4afaffa3d269ba2dcc9e2831cd0c3b +01874,0xb43aeeecf3e3603fc7f82cc03948d50a9cab2c30d26a371afa8d7b0526c20853 +01875,0x24fb77820016a3b7ff7cd3ec7407364b0b660fb2a6bb0e26e4b8da1deb6275c2 +01876,0x41ac34f85491e5d80275e95298185b3df6bc6e522b1b6e18a81b4a954573d27d +01877,0x54983d685feaa65ccbaed699e5c85a9cc5fb2275ee5ecc15295fa056f35dff42 +01878,0x56db2145e5e6ffb8f46ab7fd0bf8192af4b7ee8701fc92e3066697fc7fdab1c1 +01879,0x793c08df7c9a354e39b31fa213f2944ea8361ed33203f0e1e438351e185d241a +01880,0x0412a89eb5bf0325ce228aa64f66dcab0855c002db872dd94f3ee97496d41a1f +01881,0x8d9912853e99f373036df7a07e47eff4dba631f7456c6fee1bb79a292f530c13 +01882,0x44df0aab52827e4608b4fab902457682fa019ad5cbbdf7502bb1ba74607078b7 +01883,0xbd172681ef1b3e781763591809db8067a65590760a1a823716d2afffcd893492 +01884,0x5732d988076cc1fedf316e07aa3a8567fd55a04ca989876d4bdc63681cbcce48 +01885,0x5480f07444c8ba60faf8b853c77b72b2e0aee4894a176f920d0965eb92df90f9 +01886,0xb5e8b2b00ba1708ec31ca0a7e64540c1b02d837991d4e12cdb19d6c75ed0da6b +01887,0xdededef33d83e607868d87e8f058511a152de71d8a04b12499d5f1666b89071d +01888,0xcdbce5e36cfff749d0ee9ccb6dc344a822ed097e4b8eb812ada19521890d5663 +01889,0x4a09fe43bd97064993f18d214062005a1ffc76d03495b2b7c65c6137d3dd055e +01890,0xff7a1b1127af6429b799637ff6cffb9169aa5000f01b67a54e2c7f9a155e7027 +01891,0x0f7bffdd015be88c78d30778d5bd66b75e86f9867e221f857352d0cb95c927a1 +01892,0x9671b1edc7dc58206e18de1e4d107bf2e8508483017749146ff5c82c674408e6 +01893,0x1b07973b9e818e0e014e52c587149c9775fd44bd5ccd095dee3221ba7c7a9efe +01894,0x804008940c025a4e8a00ea42a659b484ba32c14dff133e9d3b7bf3685c1e54de +01895,0x3f81607c8cb3f0448a11cab8df0e504b605581f4891a9a35bd9c0dd37a71834f +01896,0xe6ebe562c89bc8ecb94dc9b2889a27a816ec05d3d6bd1625acad72227071e721 +``` + +## Security Considerations + +The accumulator root should be verified by community members before being +accepted. Although the accumulator root can be verified at anytime by anyone in +the future, it is likely clients and other tooling will begin relying on proofs +against the aforementioned root in the near term. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7645.md b/EIPS/eip-7645.md new file mode 100644 index 00000000000000..c3e049b0377dd8 --- /dev/null +++ b/EIPS/eip-7645.md @@ -0,0 +1,73 @@ +--- +eip: 7645 +title: Alias ORIGIN to SENDER +description: Eliminate ORIGIN tech debt to lay groundwork for account abstraction and close security holes +author: Cyrus Adkisson (@cyrusadkisson), Eirik Ulversøy (@EirikUlversoy) +discussions-to: https://ethereum-magicians.org/t/eip-7645-alias-origin-to-sender/19047 +status: Draft +type: Standards Track +category: Core +created: 2024-03-03 +--- + +## Abstract + +This EIP proposes aliasing the ORIGIN opcode to the SENDER opcode within the Ethereum Virtual Machine (EVM). The purpose of this change is to move Ethereum closer to enabling account abstraction by harmonizing the treatment of externally owned accounts (EOAs) and smart contracts and to address the security concerns associated with the use of ORIGIN that have and will continue to surface in all or most account abstraction proposals. + +## Motivation + +The ORIGIN opcode in Ethereum returns the address of the account that started the transaction chain, differing from the SENDER (or CALLER) opcode, which returns the address of the direct caller. The use of ORIGIN has been discouraged and deemed deprecated since mid-2016 due to the security problems it introduces, such as susceptibility to phishing attacks and other vulnerabilities where the distinction between the original sender and the immediate sender can be exploited. + +For instance, if an [ERC-4337](./eip-4337.md) bundler has tokens or other authority in a smart contract determined by ORIGIN, any of the transactions it bundles can hijack this authority since ORIGIN remains the bundler address throughout each child transaction. + +More apropos in the current context of EVM evolution, the differentiation between the ORIGIN and SENDER opcodes presents a challenge for all account abstraction efforts, such as those outlined in [EIP-7377](./eip-7377.md) and [EIP-3074](./eip-3074.md), because any move towards account abstraction must address the ORIGIN opcode's role, either by modifying or completely bypassing it. Without addressing this, the ORIGIN opcode stands as a barrier to the evolution of Ethereum's account model towards greater flexibility and functionality. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +This EIP proposes the alteration of the behavior of the ORIGIN opcode within the Ethereum Virtual Machine (EVM). Currently, the ORIGIN opcode returns the address of the original transaction initiator. Under this EIP, the ORIGIN opcode would, instead, return the same value as the SENDER opcode, which is the address of the immediate sender of the message or transaction. + +Definition Change: The ORIGIN opcode (0x32) MUST, in all contexts of execution, return the same value as that returned by the SENDER (also known as CALLER) opcode (0x33). + +EVM Implementation: All Ethereum clients MUST implement the following change to the EVM: Whenever the ORIGIN opcode is called, the value to be pushed onto the stack is the current call's sender address, as if the SENDER opcode was executed instead. + +Transaction Validation: Transactions MUST be validated as before, with no changes to the transaction structure or processing logic beyond the EVM opcode behavior specified above. + +Compatibility: Smart contracts relying on the ORIGIN opcode for obtaining the transaction initiator's address MUST be reviewed to ensure they function correctly under the new definition and worked-around or avoided if this EIP introduces breaking changes. + +Implementers are encouraged to provide feedback on this specification and report any potential issues encountered during the implementation or testing phases. + +## Rationale + +The rationale behind aliasing ORIGIN to SENDER is to: + +Facilitate Account Abstraction: Elegantly nullify a universal barrier to account abstraction, enabling more flexible and powerful account models in Ethereum. + +Enhance Security: Eliminate the security vulnerabilities associated with differentiating between the original transaction initiator and the immediate caller. + +Clean up tech debt and simplify the EVM Model: Reduce the complexity of the EVM's transaction and execution model by removing an outdated and deprecated feature, making future changes easier and safer. + +## Backwards Compatibility + +This change is not fully backwards compatible. Contracts relying on the distinction between ORIGIN and SENDER for logic or security will be affected. However, given the longstanding discouragement of ORIGIN's use, the minimal impact of the change, the widespread desire for a future account abstraction solution in the EVM, and the reality that any AA solution will ultimately have to deal with ORIGIN one way or the other, this incompatibility is considered a necessary step forward for Ethereum's development. + +No backward compatibility issues found. + +## Test Cases + +For each CALL, STATICCALL, DELEGATECALL, CALLCODE: + +Direct - Ensure that, at the target smart contract, ORIGIN and SENDER produce the same value. (For simple no-hop EOA-to-EOA/SCA transactions, this is already the case today.) + +Multi-hop - Ensure that, at each frame in a multi-hop transaction, ORIGIN and SENDER produce the same value. + +## Security Considerations + +By aliasing ORIGIN to SENDER, the specific security vulnerabilities associated with the ORIGIN opcode are addressed and eliminated. Outside the scope of this EIP, it may be wise to ban all use of ORIGIN to eliminate further misunderstanding or misuse. This can be done via tooling changes outside the EVM or, inside the EVM, reverting smart contract deployments that use ORIGIN. + +For existing misuse of ORIGIN affected negatively by this aliasing to SENDER (of yet a clear example has yet to be identified), it may be necessary to educate users to avoid this problematic legacy code. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7650.md b/EIPS/eip-7650.md new file mode 100644 index 00000000000000..807a866ab88ea1 --- /dev/null +++ b/EIPS/eip-7650.md @@ -0,0 +1,91 @@ +--- +eip: 7650 +title: Programmable access lists +description: Add a precompiled contract that add access lists programmatically +author: Qi Zhou (@qizhou), Zhiqiang Xu (@zhiqiangxu) +discussions-to: https://ethereum-magicians.org/t/eip-7650-programmable-access-lists/19159 +status: Draft +type: Standards Track +category: Core +created: 2024-03-10 +requires: 2929, 2930 +--- + +## Abstract + +We introduce a new precompiled contract named `prefetch`, which accepts an `accessList`. + +The `accessList` specifies a list of addresses and local storage keys; these addresses and local storage keys are added into the `accessed_addresses` and `accessed_storage_keys` global sets (introduced in [EIP-2929](./eip-2929.md)). Similar to [EIP-2930](./eip-2930.md), prefetching data through this precompile incurs a gas charge, albeit at a reduced rate compared to accesses made outside of this list. + +## Motivation + +The primary goal of this EIP is to enhance EIP-2930 by enabling contracts to add access lists programmatically. The advantage of implementing this precompile within a contract is the sustained reduction in gas costs for data access operations, leveraging the concurrent computing and IOs that most nodes have. + +## Specification + +The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. + +### Parameters + +| Constant | Value | +| ----------------------------- | ----- | +| `FORK_BLOCK_NUMBER` | `TBD` | +| `PREFETCH_PRECOMPILE_ADDRESS` | `TBD` | +| `CONCURRENCY` | `TBD` | + +As of `FORK_BLOCK_NUMBER`, a new precompile is deployed at `PREFETCH_PRECOMPILE_ADDRESS`. The encoding of the precompile input is the following: + +```text +[32 bytes for local storage key length n][n * 32 bytes local storage keys][32 bytes for address length m][m * 32 bytes addresses] +``` + +At the beginning of the call, we will charge `2100 * (N + CONCURRENCY - 1) // CONCURRENCY + 2600 * (M + CONCURRENCY - 1) // CONCURRENCY`, where `//` is the integer division operator, `N` is the number of local storage keys not in `accessed_storage_keys` global set, and `M` is the number of addresses not in `accessed_addresses` global set. The client should concurrently read the keys and addresses and put the keys and addresses into the `accessed_addresses` and `accessed_storage_keys` global sets. The following read cost of the storage keys and addresses obeys `WARM_STORAGE_READ_COST` as defined in [EIP-2929](./eip-2929.md). + + +### Examples + +Using UniswapV2 `swap()` function as an example: + +``` + // this low-level function should be called from a contract which performs important safety checks + function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { + prefetch { + token0.slot, + token1.slot, + reserve0.slot, + price0CumulativeLast.slot, + price1CumulativeLast.slot, + } // add the storage keys `accessed_storage_keys` + prefetch { + token0, + token1, + } // add the contracts of token0 and token1 to `accessed_addresses` + ... + } +``` + +## Rationale + +### Charging less for accesses in the access list + +Similar to EIP-2930, we encourage contract developers to use the `prefetch` precompile as much as possible, especially assuming the nodes have some decent concurrent capabilities (e.g., some cores and IO bandwidth). + +### Allowing duplicates + +Similar to EIP-2930, we allow duplicates in the list to maximize simplicity. + +### No storage keys for external contract + +Unlike EIP-2930, the `prefetch` precompile only accepts local storage keys and addresses. Prefetching the data of the storage keys of external contracts assumes that the contract knows the storage layout of an external contract, which may not be a good practice. To better employ the concurrency of a node, the precompile may accept a list of static calls of external contracts together with the calldata. This work may be done in the future EIP. + +## Backwards Compatibility + +If the EIP is not yet implemented, a contract calling the precompile should result in no operation. + +## Security Considerations + +No security considerations were found. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7657.md b/EIPS/eip-7657.md new file mode 100644 index 00000000000000..9016136d2a57e4 --- /dev/null +++ b/EIPS/eip-7657.md @@ -0,0 +1,336 @@ +--- +eip: 7657 +title: Sync committee slashings +description: Slashing condition for malicious sync committee messages +author: Etan Kissling (@etan-status) +discussions-to: https://ethereum-magicians.org/t/eip-7657-sync-committee-slashings/19288 +status: Draft +type: Standards Track +category: Core +created: 2024-03-21 +--- + +## Abstract + +This EIP defines a slashing condition for malicious [sync committee messages](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/validator.md#containers). + +## Motivation + +A dishonest supermajority of sync committee members is able to convince applications relying on Ethereum's [light client sync protocol](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/sync-protocol.md) to assume a non-canonical finalized header, and to potentially take over the sync authority for future `SyncCommitteePeriod`. By signing a malicious beacon block root, a malicious (but valid!) `LightClientUpdate` message can be formed and subsequently used to, for example, exploit a trust-minimized bridge contract based on the light client sync protocol. + +An additional type of slashing is introduced to deter against signing non-canonical beacon block roots as a sync committee member. As is the case with [`ProposerSlashing`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#proposerslashing) and [`AttesterSlashing`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#attesterslashing), only malicious behaviour is slashable. This includes simultaneous contradictory participation across multiple chain branches, but a validator that is simply tricked into syncing to an incorrect checkpoint should not be slashable even though it is participating on a non-canonical chain. Note that a slashing must be verifiable even without access to history, e.g., by a checkpoint synced beacon node. + +Note that regardless of the slashing mechanism, a slashing can only be applied retroactively after an attack has already occurred. Use cases that secure a larger amount than `SYNC_COMMITTEE_SIZE * MAX_EFFECTIVE_BALANCE` = `512 * 32 ETH` = `16384 ETH` (on mainnet) should combine the light client sync protocol with other established methods such as a multisig, or may want to require posting additional collateral to be eligible for submitting updates. Other methods are out of scope for this EIP. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### State transition checks + +Note: This still allows having contradictions between attestations/proposals and sync committee messages. This also, by design, allows a validator to not participate at all in honest sync committee messages but solely participate in dishonest sync committee messages. + +| Name | Value | +| - | - | +| `BLOCK_STATE_ROOT_INDEX` | `get_generalized_index(BeaconBlock, 'state_root')` (= 11) | +| `STATE_BLOCK_ROOTS_INDEX` | `get_generalized_index(BeaconState, 'block_roots')` (= 37) | +| `STATE_HISTORICAL_ROOTS_INDEX` | `get_generalized_index(BeaconState, 'historical_roots')` (= 39) | +| `HISTORICAL_BATCH_BLOCK_ROOTS_INDEX` | `get_generalized_index(HistoricalBatch, 'block_roots')` (= 2) | +| `MAX_SYNC_COMMITTEE_SLASHINGS` | `2**0` (= 1) | + +```python +class SyncCommitteeSlashingEvidence(Container): + attested_header: BeaconBlockHeader + next_sync_committee: SyncCommittee + next_sync_committee_branch: Vector[Root, floorlog2(NEXT_SYNC_COMMITTEE_INDEX)] + finalized_header: BeaconBlockHeader + finality_branch: Vector[Root, floorlog2(FINALIZED_ROOT_INDEX)] + sync_aggregate: SyncAggregate + signature_slot: Slot + sync_committee_pubkeys: Vector[BLSPubkey, SYNC_COMMITTEE_SIZE] + actual_finalized_block_root: Root + actual_finalized_branch: List[Root, ( + floorlog2(BLOCK_STATE_ROOT_INDEX) + + floorlog2(STATE_HISTORICAL_ROOTS_INDEX) + + 1 + floorlog2(HISTORICAL_ROOTS_LIMIT) + + floorlog2(HISTORICAL_BATCH_BLOCK_ROOTS_INDEX) + + 1 + floorlog2(SLOTS_PER_HISTORICAL_ROOT))] + +class SyncCommitteeSlashing(Container): + slashable_validators: List[ValidatorIndex, SYNC_COMMITTEE_SIZE] + evidence_1: SyncCommitteeSlashingEvidence + evidence_2: SyncCommitteeSlashingEvidence + recent_finalized_block_root: Root + recent_finalized_slot: Slot + +def sync_committee_slashing_evidence_has_sync_committee(evidence: SyncCommitteeSlashingEvidence) -> bool: + return evidence.next_sync_committee_branch != [Root() for _ in range(floorlog2(NEXT_SYNC_COMMITTEE_INDEX))] + +def sync_committee_slashing_evidence_has_finality(evidence: SyncCommitteeSlashingEvidence) -> bool: + return evidence.finality_branch != [Root() for _ in range(floorlog2(FINALIZED_ROOT_INDEX))] + +def is_valid_sync_committee_slashing_evidence(evidence: SyncCommitteeSlashingEvidence, + recent_finalized_block_root: Root, + recent_finalized_slot: Slot, + genesis_validators_root: Root) -> bool: + # Verify sync committee has sufficient participants + sync_aggregate = evidence.sync_aggregate + if sum(sync_aggregate.sync_committee_bits) < MIN_SYNC_COMMITTEE_PARTICIPANTS: + return False + + # Verify that the `finality_branch`, if present, confirms `finalized_header` + # to match the finalized checkpoint root saved in the state of `attested_header`. + # Note that the genesis finalized checkpoint root is represented as a zero hash. + if not sync_committee_slashing_evidence_has_finality(evidence): + if evidence.actual_finalized_block_root != Root(): + return False + if evidence.finalized_header != BeaconBlockHeader(): + return False + else: + if evidence.finalized_header.slot == GENESIS_SLOT: + if evidence.actual_finalized_block_root != Root(): + return False + if evidence.finalized_header != BeaconBlockHeader(): + return False + finalized_root = Root() + else: + finalized_root = hash_tree_root(evidence.finalized_header) + if not is_valid_merkle_branch( + leaf=finalized_root, + branch=evidence.finality_branch, + depth=floorlog2(FINALIZED_ROOT_INDEX), + index=get_subtree_index(FINALIZED_ROOT_INDEX), + root=evidence.attested_header.state_root, + ): + return False + + # Verify that the `next_sync_committee`, if present, actually is the next sync committee saved in the + # state of the `attested_header` + if not sync_committee_slashing_evidence_has_sync_committee(evidence): + if evidence.next_sync_committee != SyncCommittee(): + return False + else: + if not is_valid_merkle_branch( + leaf=hash_tree_root(evidence.next_sync_committee), + branch=evidence.next_sync_committee_branch, + depth=floorlog2(NEXT_SYNC_COMMITTEE_INDEX), + index=get_subtree_index(NEXT_SYNC_COMMITTEE_INDEX), + root=evidence.attested_header.state_root, + ): + return False + + # Verify that the `actual_finalized_block_root`, if present, is confirmed by `actual_finalized_branch` + # to be the block root at slot `finalized_header.slot` relative to `recent_finalized_block_root` + if recent_finalized_block_root == Root(): + if evidence.actual_finalized_block_root != Root(): + return False + if evidence.actual_finalized_block_root == Root(): + if len(evidence.actual_finalized_branch) != 0: + return False + else: + finalized_slot = evidence.finalized_header.slot + if recent_finalized_slot < finalized_slot: + return False + distance = recent_finalized_slot - finalized_slot + if distance == 0: + gindex = GeneralizedIndex(1) + else: + gindex = BLOCK_STATE_ROOT_INDEX + if distance <= SLOTS_PER_HISTORICAL_ROOT: + gindex = (gindex << floorlog2(STATE_BLOCK_ROOTS_INDEX)) + STATE_BLOCK_ROOTS_INDEX + else: + gindex = (gindex << floorlog2(STATE_HISTORICAL_ROOTS_INDEX)) + STATE_HISTORICAL_ROOTS_INDEX + gindex = (gindex << uint64(1)) + 0 # `mix_in_length` + historical_batch_index = finalized_slot // SLOTS_PER_HISTORICAL_ROOT + gindex = (gindex << floorlog2(HISTORICAL_ROOTS_LIMIT)) + historical_batch_index + gindex = (gindex << floorlog2(HISTORICAL_BATCH_BLOCK_ROOTS_INDEX)) + HISTORICAL_BATCH_BLOCK_ROOTS_INDEX + gindex = (gindex << uint64(1)) + 0 # `mix_in_length` + block_root_index = finalized_slot % SLOTS_PER_HISTORICAL_ROOT + gindex = (gindex << floorlog2(SLOTS_PER_HISTORICAL_ROOT)) + block_root_index + if len(evidence.actual_finalized_branch) != floorlog2(gindex): + return False + if not is_valid_merkle_branch( + leaf=evidence.actual_finalized_block_root, + branch=evidence.actual_finalized_branch, + depth=floorlog2(gindex), + index=get_subtree_index(gindex), + root=recent_finalized_block_root, + ): + return False + + # Verify sync committee aggregate signature + sync_committee_pubkeys = evidence.sync_committee_pubkeys + participant_pubkeys = [ + pubkey for (bit, pubkey) in zip(sync_aggregate.sync_committee_bits, sync_committee_pubkeys) + if bit + ] + fork_version = compute_fork_version(compute_epoch_at_slot(evidence.signature_slot)) + domain = compute_domain(DOMAIN_SYNC_COMMITTEE, fork_version, genesis_validators_root) + signing_root = compute_signing_root(evidence.attested_header, domain) + return bls.FastAggregateVerify(participant_pubkeys, signing_root, sync_aggregate.sync_committee_signature) + +def process_sync_committee_slashing(state: BeaconState, sync_committee_slashing: SyncCommitteeSlashing) -> None: + is_slashable = False + + # Check that evidence is ordered descending by `attested_header.slot` and is not from the future + evidence_1 = sync_committee_slashing.evidence_1 + evidence_2 = sync_committee_slashing.evidence_2 + assert state.slot >= evidence_1.signature_slot > evidence_1.attested_header.slot >= evidence_1.finalized_header.slot + assert state.slot >= evidence_2.signature_slot > evidence_2.attested_header.slot >= evidence_2.finalized_header.slot + assert evidence_1.attested_header.slot >= evidence_2.attested_header.slot + + # Only conflicting data among the current and previous sync committee period is slashable; + # on new periods, the sync committee initially signs blocks in a previous sync committee period. + # This allows a validator synced to a malicious checkpoint to contribute again in a future period + evidence_1_attested_period = compute_sync_committee_period_at_slot(evidence_1.attested_header.slot) + evidence_2_attested_period = compute_sync_committee_period_at_slot(evidence_2.attested_header.slot) + assert evidence_1_attested_period <= evidence_2_attested_period + 1 + + # It is not allowed to sign conflicting `attested_header` for a given slot + if evidence_1.attested_header.slot == evidence_2.attested_header.slot: + if evidence_1.attested_header != evidence_2.attested_header: + is_slashable = True + + # It is not allowed to sign conflicting finalized `next_sync_committee` + evidence_1_finalized_period = compute_sync_committee_period_at_slot(evidence_1.finalized_header.slot) + evidence_2_finalized_period = compute_sync_committee_period_at_slot(evidence_2.finalized_header.slot) + if ( + evidence_1_attested_period == evidence_2_attested_period + and evidence_1_finalized_period == evidence_1_attested_period + and evidence_2_finalized_period == evidence_2_attested_period + and sync_committee_slashing_evidence_has_finality(evidence_1) + and sync_committee_slashing_evidence_has_finality(evidence_2) + and sync_committee_slashing_evidence_has_sync_committee(evidence_1) + and sync_committee_slashing_evidence_has_sync_committee(evidence_2) + ): + if evidence_1.next_sync_committee != evidence_2.next_sync_committee: + is_slashable = True + + # It is not allowed to sign a non-linear finalized history + recent_finalized_slot = sync_committee_slashing.recent_finalized_slot + recent_finalized_block_root = sync_committee_slashing.recent_finalized_block_root + if ( + not sync_committee_slashing_evidence_has_finality(evidence_1) + or not sync_committee_slashing_evidence_has_finality(evidence_2) + ): + assert recent_finalized_block_root == Root() + if recent_finalized_block_root == Root(): + assert recent_finalized_slot == 0 + else: + # Merkle proofs may be included to indicate that `finalized_header` does not match + # the `actual_finalized_block_root` relative to a given `recent_finalized_block_root`. + # The finalized history is linear. Therefore, a mismatch indicates signing on an unrelated chain. + # Note that it is not slashable to sign solely an alternate history, as long as it is consistent. + # This allows a validator synced to a malicious checkpoint to contribute again in a future period + linear_1 = (evidence_1.actual_finalized_block_root == hash_tree_root(evidence_1.finalized_header)) + linear_2 = (evidence_2.actual_finalized_block_root == hash_tree_root(evidence_2.finalized_header)) + assert not linear_1 or not linear_2 + assert linear_1 or linear_2 # Do not slash on signing solely an alternate history + + # `actual_finalized_branch` may be rooted in the provided `finalized_header` with highest slot + rooted_in_evidence_1 = ( + evidence_1.finalized_header.slot >= evidence_2.finalized_header.slot + and recent_finalized_slot == evidence_1.finalized_header.slot + and recent_finalized_block_root == evidence_1.actual_finalized_block_root and linear_1 + ) + rooted_in_evidence_2 = ( + evidence_2.finalized_header.slot >= evidence_1.finalized_header.slot + and recent_finalized_slot == evidence_2.finalized_header.slot + and recent_finalized_block_root == evidence_2.actual_finalized_block_root and linear_2 + ) + + # Alternatively, if evidence about non-linearity cannot be obtained directly from an attack, + # it can be proven that one of the `finalized_header` is part of the canonical finalized chain + # that our beacon node is synced to, while the other `finalized_header` is unrelated. + rooted_in_canonical = ( + recent_finalized_slot < state.slot <= recent_finalized_slot + SLOTS_PER_HISTORICAL_ROOT + and recent_finalized_slot <= compute_start_slot_at_epoch(state.finalized_checkpoint.epoch) + and recent_finalized_block_root == state.state_roots[recent_finalized_slot % SLOTS_PER_HISTORICAL_ROOT] + ) + assert rooted_in_evidence_1 or rooted_in_evidence_2 or rooted_in_canonical + is_slashable = True + + assert is_slashable + + # Check that slashable validators are sorted, known, and participated in both signatures + will_slash_any = False + sync_aggregate_1 = evidence_1.sync_aggregate + sync_aggregate_2 = evidence_2.sync_aggregate + sync_committee_pubkeys_1 = evidence_1.sync_committee_pubkeys + sync_committee_pubkeys_2 = evidence_2.sync_committee_pubkeys + participant_pubkeys_1 = [ + pubkey for (bit, pubkey) in zip(sync_aggregate_1.sync_committee_bits, sync_committee_pubkeys_1) + if bit + ] + participant_pubkeys_2 = [ + pubkey for (bit, pubkey) in zip(sync_aggregate_2.sync_committee_bits, sync_committee_pubkeys_2) + if bit + ] + slashable_validators = sync_committee_slashing.slashable_validators + num_validators = len(state.validators) + for i, index in enumerate(slashable_validators): + assert ( + index < num_validators + and (i == 0 or index > slashable_validators[i - 1]) + ) + assert state.validators[index].pubkey in participant_pubkeys_1 + assert state.validators[index].pubkey in participant_pubkeys_2 + if is_slashable_validator(state.validators[index], get_current_epoch(state)): + will_slash_any = True + assert will_slash_any + + # Validate evidence, including signatures + assert is_valid_sync_committee_slashing_evidence( + evidence_1, + recent_finalized_block_root, + recent_finalized_slot, + state.genesis_validator_root, + ) + assert is_valid_sync_committee_slashing_evidence( + evidence_2, + recent_finalized_block_root, + recent_finalized_slot, + state.genesis_validator_root, + ) + + # Perform slashing + for index in slashable_validators: + if is_slashable_validator(state.validators[index], get_current_epoch(state)): + slash_validator(state, index) +``` + +## Rationale + +### What's the use case? + +Without a slashing, the light client sync protocol is somewhat limited. While wallet applications may benefit from it (the risk being, that incorrect data is displayed) and new beacon nodes may use it for accelerating chain synchronization, other interesting use cases such as bridges, token distributions or other systems requiring proofs depend on the mechanism providing higher security guarantees. + +By making attacks by sync committee members slashable, a sufficiently high deterrent could be provided. A majority of the sync committee would have to be bribed to succeed in an attack even in the most simple cases, representing a sizable slashable balance. + +## Backwards Compatibility + +This EIP requires a hard fork as it introduces new consensus validation rules. + +Supporting infrastructure may be introduced separately once the consensus validation rules are in place, including but not limited to: + +- Slashing protection DB updates, to guarantee that honest validators cannot be slashed on reorgs +- Validator client / remote signer APIs, to pass along information related to slashing protection +- libp2p meshes for exchanging slashing evidence between beacon nodes +- Slasher, to monitor potential targets and construct slashing evidence +- Beacon APIs, to submit and monitor slashing evidence + +## Test Cases + +TBD + +## Reference Implementation + +TBD + +## Security Considerations + +TBD + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7658.md b/EIPS/eip-7658.md new file mode 100644 index 00000000000000..65e441920fa179 --- /dev/null +++ b/EIPS/eip-7658.md @@ -0,0 +1,175 @@ +--- +eip: 7658 +title: Light client data backfill +description: Mechanism for beacon nodes for syncing historical light client data +author: Etan Kissling (@etan-status) +discussions-to: https://ethereum-magicians.org/t/eip-7658-light-client-data-backfill/19290 +status: Review +type: Standards Track +category: Core +created: 2024-03-21 +--- + +## Abstract + +This EIP defines a mechanism for syncing [light client data](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/full-node.md) between beacon nodes. + +## Motivation + +[Light client data](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/full-node.md) is collected by beacon nodes to assist [light clients](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/light-client.md) to sync with the network. The [sync protocol](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/sync-protocol.md) defines a mechanism to sync forward in time. However, it cannot be used to sync backward. + +Collecting light client data is challenging because beacon nodes need to have access to the corresponding [`BeaconState`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#beaconstate) and [`SignedBeaconBlock`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#signedbeaconblock). `BeaconState` are not available before the initially synced checkpoint state, and `SignedBeaconBlock` have a limited retention period on libp2p. + +Furthermore, each [sync committee period](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/beacon-chain.md#get_next_sync_committee) consists of `EPOCHS_PER_SYNC_COMMITTEE_PERIOD * SLOTS_PER_EPOCH` slots. To support archive services such as Portal network to provide a consistent view regardless of backend, it is necessary to choose a single canonical slot for which to derive the representative light client data for that period. Such data should be verifiable to be canonical and optimal in a decentralized and independent manner. + +To support light client data backfill, this EIP proposes to track the canonical and optimal [`SyncAggregate`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/beacon-chain.md#syncaggregate) in the `BeaconState`. This minimal addition allows proving that derived [`LightClientUpdate`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/sync-protocol.md#lightclientupdate) and [`LightClientBootstrap`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/sync-protocol.md#lightclientbootstrap) are also canonical and optimal. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Containers + +#### New containers + +##### `SyncData` + +```python +class SyncData(Container): + # Sync committee aggregate signature + sync_aggregate: SyncAggregate + # Slot at which the aggregate signature was created + signature_slot: Slot +``` + +#### Extended containers + +##### `BeaconState` + +New fields are added to the end of `BeaconState` from the activating fork onward to track the current and previous sync committee period's best sync data. + +```python +class BeaconState(Container): + ... + # Sync history + previous_best_sync_data: SyncData + current_best_sync_data: SyncData + parent_block_has_sync_committee_finality: bool +``` + +### Helper functions + +#### `default_sync_data` + +```python +def default_sync_data() -> SyncData: + return SyncData( + sync_aggregate=SyncAggregate( + sync_committee_bits=Bitvector[SYNC_COMMITTEE_SIZE]() + sync_committee_signature=G2_POINT_AT_INFINITY, + ), + signature_slot=GENESIS_SLOT, + ) +``` + +### Beacon chain state transition function + +#### Epoch processing + +##### Modified `process_sync_committee_updates` + +On sync committee boundaries, current period data is moved to previous period. This allows proving that light client data for the previous period is canonical. + +```python +def process_sync_committee_updates(state: BeaconState) -> None: + next_epoch = get_current_epoch(state) + Epoch(1) + if next_epoch % EPOCHS_PER_SYNC_COMMITTEE_PERIOD == 0: + ... + state.previous_best_sync_data = state.current_best_sync_data + state.current_best_sync_data = default_sync_data() + state.parent_block_has_sync_committee_finality = False +``` + +#### Block processing + +Block processing is extended to track the optimal light client data for the current period. Due to the possibility for empty slots this must be tracked before the block header is overwritten; this allows tracking the exact block after which `next_sync_committee` becomes finalized. + +```python +def process_block(state: BeaconState, block: BeaconBlock) -> None: + process_best_sync_data(state, block) + process_block_header(state, block) + ... +``` + +##### New `process_best_sync_data` + +```python +def process_best_sync_data(state: BeaconState, block: BeaconBlock) -> None: + signature_period = compute_sync_committee_period_at_slot(block.slot) + attested_period = compute_sync_committee_period_at_slot(state.latest_block_header.slot) + + # Track sync committee finality + old_has_sync_committee_finality = state.parent_block_has_sync_committee_finality + if state.parent_block_has_sync_committee_finality: + new_has_sync_committee_finality = True + elif state.finalized_checkpoint.epoch < ALTAIR_FORK_EPOCH: + new_has_sync_committee_finality = False + else: + finalized_period = compute_sync_committee_period(state.finalized_checkpoint.epoch) + new_has_sync_committee_finality = (finalized_period == attested_period) + state.parent_block_has_sync_committee_finality = new_has_sync_committee_finality + + # Track best sync data + if attested_period == signature_period: + max_active_participants = len(block.body.sync_aggregate.sync_committee_bits) + new_num_active_participants = sum(block.body.sync_aggregate.sync_committee_bits) + old_num_active_participants = sum(state.current_best_sync_data.sync_aggregate.sync_committee_bits) + new_has_supermajority = new_num_active_participants * 3 >= max_active_participants * 2 + old_has_supermajority = old_num_active_participants * 3 >= max_active_participants * 2 + if new_has_supermajority != old_has_supermajority: + is_better_sync_data = new_has_supermajority + elif not new_has_supermajority and new_num_active_participants != old_num_active_participants: + is_better_sync_data = new_num_active_participants > old_num_active_participants + elif new_has_sync_committee_finality != old_has_sync_committee_finality: + is_better_sync_data = new_has_sync_committee_finality + else: + is_better_sync_data = new_num_active_participants > old_num_active_participants + if is_better_sync_data: + state.current_best_sync_data = SyncData( + sync_aggregate=block.body.sync_aggregate, + signature_slot=block.slot, + ) +``` + +## Rationale + +### How to rank `SyncAggregate`? + +The EIP reuses the [`is_better_update`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/light-client/sync-protocol.md#is_better_update) function from existing specs. + +### How could a backfill protocol use this? + +Once the data is available in the `BeaconState`, a light client data backfill protocol could be defined that serves, for past periods: + +1. A `LightClientUpdate` from requested `period` + 1 that proves that the entirety of `period` is finalized. +2. `BeaconState.historical_summaries[period].block_summary_root` at (1)'s `attested_header.beacon.state_root` + Merkle proof. +3. For each epoch's slot 0 block within requested `period`, the corresponding `LightClientHeader` + Merkle multi-proof for the block's inclusion into (2)'s `block_summary_root`. +4. For each of the entries from (3) with `beacon.slot` within `period`, the `current_sync_committee_branch` + Merkle proof for constructing `LightClientBootstrap`. +5. If (4) is not empty, the requested `period`'s `current_sync_committee`. +6. The best `LightClientUpdate` from `period`, if one exists, + Merkle proof that its `sync_aggregate` + `signature_slot` is selected as the canonical best one in (1)'s `attested_header.beacon.state_root`. + +Only the proof in (6) depends on `BeaconState` tracking the best light client data. This modification would enshrine the logic of a subset of `is_better_update`, but does not require adding any `LightClientXyz` data structures to the `BeaconState`. + +## Backwards Compatibility + +This EIP requires a hard fork as it introduces new consensus validation rules. + +Only light client data following the hard fork can be proven to be canonical and optimal. However, after finalization of the fork transition block, earlier light client data can no longer change and could be locked in using a hash. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7664.md b/EIPS/eip-7664.md new file mode 100644 index 00000000000000..754179e96a5f26 --- /dev/null +++ b/EIPS/eip-7664.md @@ -0,0 +1,148 @@ +--- +eip: 7664 +title: Access-Key opcode +description: The access-key opcode enables contracts to read inputs that are statically declared in access-lists. +author: Diederik Loerakker (@protolambda) +discussions-to: https://ethereum-magicians.org/t/access-key-opcode/19395 +status: Withdrawn +withdrawal-reason: Niche use-case, better implemented with EIP-7702. +type: Standards Track +category: Core +created: 2024-03-27 +requires: 1153, 2930, 4844 +--- + +## Abstract + +This EIP introduces a new opcode to inspect the access-list keys of the executing address. + +## Motivation + +This EIP serves as a substitute of top-level-call detection to enable a smart-contract to +enforce static declaration of attributes. + +Previously, application-layer contracts, against common advice from account-abstraction proponents, used to rely +on the `tx.origin` to enforce a top-level call, such that the contract inputs are encoded as transaction input. + +While the access-list of transactions directly affects the execution, it only affects the gas-costs. +This EIP enhances the access-list feature to provide the property of statically-defined contract-inputs, +without relying on top-level calls, the `tx.origin` behavior, or gas introspection. + +This enables smart contracts to reliably enforce static declaration of inputs. + +This is a step towards fulfilling the purposes as described in the Motivation of [EIP-2930](./eip-2930.md): + +> Introduces the access list format and the logic for handling the format. +> This logic can later be repurposed for many other purposes, including block-wide witnesses, +> use in ReGenesis, moving toward static state access over time, and more." + +## Specification + +### Parameters + +| Constant | Value | +|----------------------------|--------| +| `ACCESS_KEY_OPCODE_GAS` | `3` | +| `ACCESS_KEY_OPCODE_BYTE` | `0x4B` | + +### Opcode + +We add an instruction `ACCESS_KEY` (with opcode `ACCESS_KEY_OPCODE_BYTE`) which pops `index` from the top +of the stack as big-endian `uint256`, and pushes `tx.access_list[address][index]` back on the stack, +if `address` is present in the `tx.access_list` and `index < len(tx.access_list[address])`, +and otherwise pushes a zeroed `bytes32` value. + +### Gas costs + +The opcode has a fixed gas cost of `ACCESS_KEY_OPCODE_GAS`. + +The intrinsic gas costs of the access-list contents of the transaction itself do not change. + +## Rationale + +### Static analysis of transactions + +Static declaration of contract-inputs enables advanced layer-two constructions and block-building techniques: +data is available without EVM introspection, and contracts can reliably tell if the executing transaction +declared critical properties to the block builder and verifying nodes. + +Static-declaration of contract inputs is now independent of account-abstraction related changes, +such as transaction bundlers, as well as in-protocol with 3074. + + +### Global read-only values + +Akin to `TLOAD`, as described in [EIP-1153](./eip-1153.md), +the `ACCESS_KEY` opcode provides contracts with a view that is global +to the message-execution of the transaction in the EVM. + +However, with `ACCESS_KEY` it is guaranteed to be read-only, and cannot change during the execution of a transaction. + +### Access-list utility + +Access-lists are under-utilized today: +very few users utilize this to warm-up storage interactions for reduced gas costs. +Generally the gas cost savings achieved with EIP-2930 are not applicable in as many use-cases. + +With this EIP, the utility of the access-list functionality increases, +without requiring additional resources from the EVM. + +### Witness data + +This EIP supports the transformation of applications to reduce statefulness, +by supporting read-only application state to be provided to contracts without +requiring the contract caller to support forwarding of data. + +The access-list contents may contain witness-data, which the contract can verify and utilize statelessness. + +### Gas costs + +The gas cost of `ACCESS_KEY_OPCODE_GAS` gas matches that of similar operations, +specifically the `BLOBHASH` opcode of [EIP-4844](./eip-4844.md): +this opcode also pop an index-like EVM word from the stack, +and pushes a full 32 byte EVM word back on the stack, based on a list of hashes embedded in the transaction. + +The `BLOBHASH` functionality of [EIP-4844](./eip-4844.md) is not re-usable for the purposes of this EIP however, +as the intention is to have access to just the statically declared hash, and not the cost of a blob. + +### Naming of `ACCESS_KEY` + +Access-lists currently only support a list of access-keys. +The list is not enforced to be sorted, and thus supports indexed lookups. + +This is not a `LOAD` opcode, as `SLOAD` or `TLOAD` are, since the opcode returns a key. + +## Backwards Compatibility + +### No transaction-type changes + +This enhancement of access-lists utility does not affect the access-list encoding, +or the existing transaction types that support access-lists. + +### Minimal impact on EVM transaction-context + +With EIP-2930, the access-list contents are already readily available in the transaction-context during EVM execution, +and the RPC methods that trigger said execution. + +This EIP thus does not require significant changes to the construction of the EVM context, +nor any changes to RPC methods. + +## Test Cases + +The block fee-recipient, and any other warmed-up attributes not declared statically in the transaction access-list, +must not be considered to be part of the access-list. + +## Security Considerations + +The access-list attributes are already gas-metered in EIP-2930, +and readily accessible in the EVM to determine storage gas-costs. In terms of denial-of-service risks, +this EIP introduces no new significant data or data-processing costs. + +The access-list is read-only, and thus forms a minimal risk to application-developers. + +The access is scoped strictly to the contract that would otherwise perform a warm `SLOAD`, +and thus storage-layout abstractions do not leak between different smart contract applications. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7666.md b/EIPS/eip-7666.md new file mode 100644 index 00000000000000..320b90b6360d64 --- /dev/null +++ b/EIPS/eip-7666.md @@ -0,0 +1,54 @@ +--- +eip: 7666 +title: EVM-ify the identity precompile +description: Remove the identity precompile, and put into place a piece of EVM code that has equivalent functionality +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7561-evm-ify-the-identity-precompile/19445 +status: Draft +type: Standards Track +category: Core +created: 2024-03-31 +--- + +## Abstract + +Remove the identity precompile at 0x04. At the start of executing the block in which this change activates, put into that contract a short piece of EVM code that has the same functionality. + +## Motivation + +Ethereum today has a large number of precompiles. Nearly half of these precompiles are not seeing significant use, and are contributing to ongoing maintenance cost and risk of consensus bugs, as well as increased development effort for new Ethereum client implementations, including ZK-EVMs and implementations in formal-verification-friendly languages. + +This EIP proposes a path for the Ethereum ecosystem to gracefully abandon these precompiles, and takes a first step by applying this procedure to the simplest precompile of all: the identity precompile (which outputs returndata equal to the input calldata). The identity precompile was originally introduced because memory copying is a common operation, and there was no opcode available to do it directly. Since then, norms around what is acceptable for an opcode have changed, and we have introduced the MCOPY opcode with [EIP-5656](eip-5656.md). And so we can remove the identity precompile, and replace it with an ultra-minimal piece of EVM code that replicates its functionality. + +In the future, this technique can be applied to other more complex precompiles, such as little-used hash functions and MODEXP. + +## Specification + +| Parameter | Value | +| - | - | +| `IDENTITY_PRECOMPILE_ADDRESS` | `0x0000....0004` | +| `EVM_CODE` | `0x365f5f37365ff3` | + +At the start of the block in which this fork activates, set the code of `IDENTITY_PRECOMPILE_ADDRESS` to `EVM_CODE`. Starting from and including that block, `IDENTITY_PRECOMPILE_ADDRESS` should no longer be treated as a precompile. + +## Rationale + +The given `EVM_CODE` corresponds to + +``` +CALLDATASIZE PUSH0 PUSH0 CALLDATACOPY CALLDATASIZE PUSH0 RETURN +``` + +Which copies calldata into memory, and then returns the same memory slice. This is thus a minimally disruptive change to Ethereum that preserves functionality, and accomplishes the goal of reducing the number of precompiles by 1. + +## Backwards Compatibility + +The functionality of the given `EVM_CODE` is the same as the identity precompile. Gas costs are slightly different, though gas repricings have been done in the Ethereum ecosystem several times before and their effects are well understood. + +## Security Considerations + +As no new functionality is introduced or made cheaper, no security concerns are raised. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7667.md b/EIPS/eip-7667.md new file mode 100644 index 00000000000000..84d9c3c6e89fd5 --- /dev/null +++ b/EIPS/eip-7667.md @@ -0,0 +1,70 @@ +--- +eip: 7667 +title: Raise gas costs of hash functions +description: Raise the gas costs of hash function opcodes and precompiles, to match prover expenses in ZK-EVMs +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7562-raise-gas-costs-of-hash-functions/19446 +status: Draft +type: Standards Track +category: Core +created: 2024-03-31 +--- + +## Abstract + +Raise the gas costs of opcodes and precompiles that involve hash functions. + +## Motivation + +Gas costs for hash function opcodes and precompiles were originally set based on the time that it takes to execute them on a regular CPU. Since then, however, there has emerged another equally important execution substrate that the EVM is executed on: zero knowledge proof (ZK-SNARK) systems. By that standard, these opcodes and precompiles are _very_ underpriced relative to other operations. + +Blocks that are heavy with hash function executions take much longer to ZK-SNARK prove than average blocks. Today, many layer-2 protocols are using workarounds such as arbitrary limits and rules enforced by centralized sequencers to deal with this issue. These workarounds are often poorly designed and lead to unneeded security and centralization concerns. + +Additionally, there is a design goal of eventually using ZK-SNARKs to prove the correctness of layer-1 Ethereum blocks. To do this, we need to establish very tight bounds on how long it takes to generate a ZK-SNARK proof of an Ethereum execution block's correctness. Today, the difference between average-case proving time and worst-case proving time is large, and hash function executions are the largest reason why. + +Verkle trees solve the part of this problem that comes from Keccak hashing in the Merkle Patricia tree. Today, the theoretical worst case is a block with `30000000 / 2600 = 11538` account accesses (minus a small percent for EVM overhead), where proving each access would require proving `24000` bytes of code, plus a roughly `512 * log(500m) / log(16) = 3712` byte Merkle-Patricia proof: roughly `305 MB` of hashing spread between `83650` hash calls. Verkle trees solve this. However, using opcodes, a block execution can still require roughly the following amount of hashing: + +| Hash | Cost per word | Maximum bytes from 30 million gas | +| - | - | - | +| `KECCAK` (opcode) | 6 | 160 million | +| `SHA256` (precompile) | 12 | 80 million | +| `RIPEMD` (precompile) | 120 | 8 million | +| `BLAKE2` (precompile) | 3 (12 per 128 bytes) | 320 million | +| `LOG*` (hashing data) | 256 (8 per byte) | 3.75 million | + +These hash functions have been optimized for rapid CPU computation, so CPUs can compute them quickly: for example, this author's laptop can compute a 160-million byte keccak in less than half a second. In ZK-SNARKs, however, these operations are _very_ time-consuming and inefficient. This is mitigated in newer proof systems based on small fields, but hashes remain underpriced. + +## Specification + +| Parameter | Previous value | New value | +| - | - | - | +| `KECCAK_BASE_COST` | 30 | 300 | +| `KECCAK_WORD_COST` | 6 | 60 | +| `SHA256_BASE_COST` | 60 | 300 | +| `SHA256_WORD_COST` | 12 | 60 | +| `RIPEMD_BASE_COST` | 600 | 600 | +| `RIPEMD_WORD_COST` | 120 | 120 | +| `BLAKE2_GFROUND` | 1 | 10 | +| `GLOGBYTE` | 8 | 10 | + +Change the above parameters to their new values. + +## Rationale + +The above increases the gas costs of all opcodes and precompiles that can be used to require large amounts of hashing in the EVM. All hashing costs are increased to 300 per hash plus 60 per word (or kept the same if they are already higher than this). +'" +A possible alternative to this approach is to implement either multidimensional gas pricing (ie. a separate floating basefee and per-block target and limit for hashes) or a "total gas cost floor" similar to what [EIP-7623](eip-7623.md) does for calldata. However, this approach is much harder to implement for in-EVM gas costs such as hashes than it is for calldata and blobs, because EVM gas limits are set not just by users, for whom new transaction types that specify newly required limits, max-basefees and priority fees can easily be added, but also by contracts making sub-calls to other contracts. + +## Backwards Compatibility + +For most applications, a reasonable upper bound is that data that is getting hashed in the EVM is getting brought in as calldata. If the hashing being done is binary Merkle proof verification, every 32 bytes of data corresponds to a 64-byte (2-word) hash. A word of costs 512 gas. Under the new costs, the hashing per word in that situation would be `300 + 60 * 2 = 420` gas. Hence, this will increase gas consumption for that component of the application by less than 2x. + +Concretely, a length-20 Keccak-based binary Merkle proof gas cost would increase from `(512 + 42) * 20 = 11080` to `(512 + 420) * 20 = 18640`. This is a small increase, especially taking into account other costs associated with such an application. + +## Security Considerations + +As no new operations are introduced or made cheaper, no security concerns were raised. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7668.md b/EIPS/eip-7668.md new file mode 100644 index 00000000000000..d4df256bda7112 --- /dev/null +++ b/EIPS/eip-7668.md @@ -0,0 +1,45 @@ +--- +eip: 7668 +title: Remove bloom filters +description: Remove bloom filters from the execution block +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7653-remove-bloom-filters/19447 +status: Draft +type: Standards Track +category: Core +created: 2024-03-31 +--- + +## Abstract + +Require the bloom filters in an execution block, including at the top level and in the receipt object, to be empty. + +## Motivation + +Logs were originally introduced to give applications a way to record information about onchain events, which decentralized applications (dapps) would be able to easily query. Using bloom filters, dapps would be able to quickly go through the history, identify the few blocks that contained logs relative to their application, and then quickly identify which individual transactions have the logs that they need. + +In practice, this mechanism is far too slow. Almost all dapps that access history end up doing so not through RPC calls to an Ethereum node (even a remote-hosted one), but through centralized extra-protocol services. + +This EIP proposes recognizing that reality, and removing bloom filters from the protocol. Applications that need history querying would be encouraged to develop and use decentralized protocols that create provable log indexes using eg. ZK-SNARKs and incrementally-verifiable computation. + +## Specification + +The logs bloom of an execution block is now required to be empty (ie. 0 bytes long). The logs bloom of a transaction receipt is now required to be empty (ie. 0 bytes long). + +## Rationale + +This is a minimally disruptive way to remove the need to handle blooms from clients. A future EIP can later clean up by removing this field entirely, along with other fields that have been deprecated. + +Gas costs of LOG are not reduced, because while the externality of polluting the bloom filter no longer needs to be accounted for, the costs of hashing have increased due to the needs of ZK-SNARK EVM implementations. + +## Backwards Compatibility + +Applications that depend on bloom filters to read events will cease to work. Very few applications depend on this feature today, because at current gas limits the false positive rate is so high and processing the logs in a long history query is so slow, especially for light clients (whom this feature was primarily intended to benefit). + +## Security Considerations + +As no new features are introduced or made cheaper, no security concerns are raised. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7675.md b/EIPS/eip-7675.md new file mode 100644 index 00000000000000..bb504b7f404fa6 --- /dev/null +++ b/EIPS/eip-7675.md @@ -0,0 +1,52 @@ +--- +eip: 7675 +title: Retroactively Included EIPs +description: Core EIPs activated independently of an Ethereum hard fork. +author: Tim Beiko (@timbeiko) +discussions-to: https://ethereum-magicians.org/t/eip-7675-retroactively-included-eips/19541 +status: Draft +type: Meta +created: 2024-04-04 +requires: 2681, 3607, 7523, 7610 +--- + +## Abstract + +This Meta EIP lists Core EIPs introducing changes to Ethereum's consensus which were activated independently of an Ethereum hard fork due to their backward compatible nature. These EIPs generally introduce constraints to underspecified protocol rules or clarify how certain edge cases should be handled. + +## Motivation + +To maintain consensus across all nodes, backward incompatible changes to Ethereum must be activated synchronously. Given the coordination required for this, changes are usually bundled together in network upgrades. A Meta EIP is typically used to list the changes included in a network upgrade, as well as its activation time. + +However, backward compatible consensus changes do not require a network upgrade to be activated. For example, if a consensus rule is underspecified, an EIP can propose a constraint to bound it. If the constraint was never broken in Ethereum's history and is unlikely to be broken in the future, the EIP can be considered backward compatible. It could then be "retroactively activated", as both nodes which support the change and those which do not would agree on the current network state and history. + +This Meta EIP lists all such EIPs which core developers have retroactively included as part of the Ethereum protocol specification. + +## Specification + +### Retroactively Activated EIPs + +* [EIP-2681](./eip-2681.md): Limit account nonce to 2^64-1 +* [EIP-3607](./eip-3607.md): Reject transactions from senders with deployed code +* [EIP-7523](./eip-7523.md): Empty accounts deprecation +* [EIP-7610](./eip-7610.md): Revert creation in case of non-empty storage + +### Activation + +All EIPs listed above are considered activated as of Ethereum's genesis block. Note that EIP-7523 distinguishes pre- and post-merge behavior on the Ethereum mainnet. + +## Rationale + +This Meta EIP provides a global view of all changes included in the Ethereum protocol without an explicit network upgrade, as well as links to full specification. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +None. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7676.md b/EIPS/eip-7676.md new file mode 100644 index 00000000000000..0d0483b942781f --- /dev/null +++ b/EIPS/eip-7676.md @@ -0,0 +1,120 @@ +--- +eip: 7676 +title: EOF - Prepare for Address Space Extension +description: Update EOF opcodes so addresses are not trimmed during execution +author: Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/eof-prepare-for-address-space-extension/19537 +status: Draft +type: Standards Track +category: Core +created: 2024-04-03 +requires: 3540, 3670, 7069 +--- + +## Abstract + +Operations in the Legacy EVM trim off the top 12 bytes of an address operand before evaluation. This +EIP changes the handling of those opcodes within EOF so that no trimming occurs and the top twelve +bytes need to be zero or an exceptional halt is raised. + +## Motivation + +There have been proposals to extend Ethereum Addresses from 160 bits to 256, such as one that would +use the extra bits for state expiry (such as the ethereum magicians forum topic "Increasing the +address size from 20 to 32 bytes"). One issue ground the work to a halt: EVM opcodes that accept +addresses trim all but the lowest 20 bytes out from the operand before processing. EVM Reference +tests verify this behavior in the 'stBadOpcode/invalidAddr.json' tests. + +The EVM Object Format presents an opportunity to remove this address masking in a backwards +compatible way, by baking it into the format definition from the start. + +Most of the work is already in place. The following 5 operations have already been banned from +EOF: `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, `CALLCODE`, and `SELFDESTRUCT`. Three call +operations, `CALL`, `DELEGATECALL`, and `STATICCALL` are being revamped +in [EIP-7069](./eip-7069.md). That leaves only one operation, `BALANCE`, with issues. + +When future uses of address space extension are specified it is expected that the exceptional halt +behavior will be modified. + +## Specification + +We introduce one new instruction: + +- `EXTBALANCE` (`tbd`) with arguments `(target_address)`, returning `balance` + +`EXTBALANCE` will pop one stack item off of the stack, the address of another account or contract. +The balance of that account or contract will be pushed onto the stack. + +If `EXTBALANCE` is invoked with any of the high 12 bytes in `target_address` set to a non-zero value +the operation will cause an exceptional halt. All gas in the current frame will be consumed on +failure, no gas schedule change is needed. + +The gas cost of `EXTBALANCE` will be costed according to the gas schedule for the `BALANCE` +operation specified in [EIP-2929](./eip-2929.md). This means if the account is not +in `accessed_addresses` then it is charged 2600 gas and added to `accessed_addresses`. If the +account is in `accessed_addresses` then 100 gas is charged. The `accessed_addresses` is shared with +all other operands described in [EIP-2929](./eip-2929). + +Also, for the `EXTCALL`, `EXTDELEGATECALL`, and `EXTSTATICCALL` operations a new step is added just +before the memory expansion check: halt with exceptional failure if any of the high 96 bits of +the `target_address` are set. + +It is anticipated that future EIPs will alter the behavior in a way that will not result in an +exceptional halt. Contract implementors should not depend on the exceptional halt. + +## Rationale + +### New Opcode + +There is no need to ban the `BALANCE` opcode as it does not cause any problems that would require +banning it within an EOF container. Adding a new opcode also allows the existing opcode to behave +the same in EOF and legacy code, reducing potential friction points for end user confusion and bugs. + +### Revert on invalid address + +There are two alternative ways to handle accounts with high bits set. The specification calls for +an exceptional halt, but the alternative was to treat the account as empty. The reason the "empty +account" approach was rejected is twofold: + +- The `accessed_addresses` list could be required to track 256 bit accounts when an invalid address + is accessed. +- The `EXTCALL` series instructions could still send balance to those addresses and such accounts + would then hold an (inaccessible) balance that would need to be reflected in the merkle trie. + +### No change in gas costing + +Because the BALANCE operation already needs to check `accessed_addresses` there is already a good +amount of processing that must go into the operation. Hence, no changes to the gas schedule are +needed to prevent abuse of the failures. Such incremental costs will be dominated by costs related +to reverts and address checking for valid accounts. + +## Backwards Compatibility + +Preparing for Address Space Expansion is explicitly done inside the scope of EOF with the intent +that it will not require changes in old contracts, but with the caveat that old contracts may not be +able to use addresses in the expanded space. + +Future EIPs should be mindful when adding new operation with an address operand or parameter to how +it interacts with EOF and legacy contracts. Authors should ensure that such additions remain in +harmony with this EIP. + +## Test Cases + +Test cases similar to `invalidAddr.json` tests in the standard reference tests will need to be +written for the EOF tests, except they would check for halts on invalid addresses. + +## Reference Implementation + +TBD + +## Security Considerations + +This EIP only defines a revert behavior for previously stripped addresses. Compilers will need to be +aware of the need to mask addresses coming in from call data. Some of this is already present in +existing Solidity ABI standards, but more care should be taken in examining the flow +around `EXTBALANCE` and code for `EXTCALL` operations to ensure that compiled code strips the high +bytes. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7684.md b/EIPS/eip-7684.md new file mode 100644 index 00000000000000..55a91cba765079 --- /dev/null +++ b/EIPS/eip-7684.md @@ -0,0 +1,67 @@ +--- +eip: 7684 +title: Return deposits for distinct credentials +description: Automatically withdraw deposits for existing validator records but with distinct execution withdrawal credentials +author: Lion (@dapplion) +discussions-to: https://ethereum-magicians.org/t/eip-7684-return-deposits-for-distinct-credentials/19632 +status: Draft +type: Standards Track +category: Core +created: 2024-04-12 +--- + +## Abstract + +Automatically withdraw deposits for existing validator records, but where the deposit includes a distinct execution withdrawal credential. + +## Motivation + +Some staking operations feature two distinct entities, one operating the validating key, and one funding the deposit. The funding entity delegates control of the stake operation but must retain ultimate control of funds. If the funding entity naively submits a single deposit with the full stake amount and the other entity's validating key, it is subject to a front-run attack. The validating entity can front-run the bigger deposit with a second deposit with its own set of withdrawal credentials. The full stake amount deposit becomes a top-up, in control of the validating entity. + +There exist workarounds to the front-run attack. Using some distributed key generation protocol between the funding and validating entity, such that a deposit must be made with the consent of both entities. Submit a 1 ETH deposit first wait for its inclusion then send the full stake amount as a top-up, to bind the maximum loss under the attack to 1 ETH. While these workarounds, work; they difficult the operation of trustless autonomous staking protocols. + +This specification reduces the total loss on a naive deposit submission from the full deposit amount to `RETURN_DEPOSIT_PENALTY`. + +## Specification + +### Consensus Layer + +The configuration values and mechanics of the specification can be found in the [Consensus Layer specs](https://github.com/ethereum/consensus-specs/blob/2360756c8c19c0f7b0e91135f5bbcddecdf0a835/specs/_features/eip9999/beacon_chain.md). + +A sketch of the resulting changes to the consensus layer is included below. + +- Modify `apply_deposit` to queue for withdrawal deposits with distinct execution withdrawal credentials +- Modify `get_expected_withdrawals` to return pending withdrawals first +- Modify `process_withdrawals` to clear the pending withdrawals queue + +### Execution Layer + +This specification does not require any changes to the Execution Layer. + +## Rationale + +### Persist pending withdrawals + +Rejected deposits from block at slot N can not be withdrawn in block N due to a cyclic dependency. An execution client must know the full list of withdrawals before constructing a payload for slot N. After [EIP-6110](./eip-6110.md), a consensus client must know the full execution payload for slot N before constructing the beacon block for slot N. Therefore, rejected deposits must be withdrawn in some future slot. All pending withdrawals are processed at once in the very next slot for simplicity but could be queued and processed progressively if there are DOS concerns. + +## Backwards Compatibility + +This is a backward incompatible change to the Consensus Layer of Ethereum and must be scheduled with a hard fork. + +There are no forwards / backwards compatibility issues with the Execution Layer + +## Test Cases + +Test cases are work-in-progress within the standard Consensus Layer tests. + +## Security Considerations + +The worst-case number of withdrawals is raised from a fixed 16 to 1,271 under current gas rules and a 30M gas block. Citing [EIP-6110](./eip-6110.md), future gas efficiencies can increase the number to 1,916 withdrawals in a 30M gas block. Each withdrawal results in a single address balance change. There is no explicit pricing for such an operation, but under the worst case, it results in a notable increase in the total block gas (30% assuming 6,900 gas per withdrawal and current gas rules). + +`RETURN_DEPOSIT_PENALTY` disincentivizes rejected deposits, and imposes a gas cost of 144,927 Gwei / gas, assuming 6,900 gas per withdrawal. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + + diff --git a/EIPS/eip-7685.md b/EIPS/eip-7685.md new file mode 100644 index 00000000000000..d2f13be207ff69 --- /dev/null +++ b/EIPS/eip-7685.md @@ -0,0 +1,148 @@ +--- +eip: 7685 +title: General purpose execution layer requests +description: A general purpose bus for sharing EL triggered requests with the CL +author: lightclient (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-7685-general-purpose-execution-layer-requests/19668 +status: Review +type: Standards Track +category: Core +created: 2024-04-14 +--- + +## Abstract + +This proposal defines a general purpose framework for storing contract-triggered +requests. It extends the execution header and body with a single field each to +store the request information. This inherently exposes the requests to the +consensus layer, which can then process each one. + +## Motivation + +The proliferation of smart contract controlled validators has caused there to be +a demand for additional EL triggered behaviors. By allowing these systems to +delegate administrative operations to their governing smart contracts, they can +avoid intermediaries needing to step in and ensure certain operations occur. +This creates a safer system for end users. + +## Specification + +### Execution Layer + +#### Request + +A `request` consists of a `request_type` prepended to an opaque byte array +`request_data`: + +``` +request = request_type ++ request_data +``` + +Let `requests` be the list of all `request` objects in the block in ascending +order by type. For example: + +``` +[0x00_request_0, 0x01_request_0, 0x01_request_1, 0x02_request_0, ...] +``` + +The ordering of requests within a type is to be defined by each request type. + +#### Block structure + +The block body is appended with a list of requests. RLP encoding of the extended +block body structure is computed as follows: + +```python +block_body_rlp = rlp([ + field_0, + ..., + # Latest block body field before `requests` + field_n, + [request_0, ..., request_k], +]) +``` + +#### Block Header + +Extend the header with a new 32 byte value `requests_root`. + +Let `requests_root` be the root of a Merkle-Patricia trie keyed by the index in +the list of `requests`. This is equivalent to how the transaction trie root is +computed. + + The `requests_root` field value is therefore computed as follows: + +```python +def compute_trie_root_from_indexed_data(data): + trie = Trie.from([(i, obj) for i, obj in enumerate(data)]) + return trie.root + +block.header.requests_root = compute_trie_root_from_indexed_data(block.body.requests) +``` + +### Consensus Layer + +Each proposal may choose how to extend the beacon chain types to include the new +EL request. + +## Rationale + +### Opaque byte array rather than an RLP array + +By having the bytes of `request_data` array from second byte on be opaque bytes, rather than an RLP (or other +encoding) list, we can support different encoding formats for the transaction +payload in the future such as SSZ, LEB128, or a fixed width format. + +### Request source and validity + +This EIP makes no strict requirement where a request may come from nor when/how +a request must be validated. This is to provide future protocol designers +maximum flexibility. + +The authors' recommendations on source and validity of requests are: + +* The source of requests should be from the execution of transactions. More + specifically, transactions which make calls to designated system contracts + that store the request in account. The storage would later be retrieved by a + post-block system call to the contract. Alternatively, if the system call does + not need to be inherently concerned with rate limiting, it could rely simply + on emitting an event which is later parsed post-block by the system and + converted into a request. +* A request's validity can often not be fully verified at the execution layer. + This is why they are referred to merely as "requests"; they do not carry the + authority on their own to unilaterally catalyze an action. We expect the system + contracts to perform whatever validation is possible by the EL and then pass + it on to the CL for further validation. + +### Ordering + +The ordering across types is ascending by type. This is to simplify the process +of verifying that all requests which were committed to in `requests_root` were +found in the block. + +An alternative could be to order by when the request was generated within the +block. Since it's expected that many requests will be accumulated at the end of +the block via system calls, this would be difficult to enforce. Therefore, +ordering by type is the most straightforward ordering which ensures integrity. + +#### Intra-type + +Within the same type, order is not defined. This is because the data of the +request is opaque as far as this EIP is concerned. Therefore, it is to be +determined by each request type individually. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Test Cases + +TODO + +## Security Considerations + +Needs discussion. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7686.md b/EIPS/eip-7686.md new file mode 100644 index 00000000000000..cae72554596f67 --- /dev/null +++ b/EIPS/eip-7686.md @@ -0,0 +1,75 @@ +--- +eip: 7686 +title: Linear EVM memory limits +description: Adjust memory limits and gas limits of sub-calls to create a clear linear bound on how much total memory an EVM execution can consume +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7686-linear-evm-memory-limits/19448 +status: Draft +type: Standards Track +category: Core +created: 2024-04-15 +--- + +## Abstract + +Add a hard memory limit equal to the gas limit of the current context. Make the maximum gas cost of a sub-call depend on the memory used in the current context. The two rules together ensure that a transaction with N gas can use at most N bytes of memory. + +## Motivation + +Today, memory pricing rules are complicated: we have the quadratic cost for expanding memory as well as the 63/64 rule for how much gas can go into a child call. This also makes it extremely hard to calculate a maximum possible amount of memory required to process a given EVM execution. + +The rules in this post simplify these rules, and add a new hard limit: an EVM execution with N gas can require at most N total bytes of memory to process. This limit is tight: there are easy ways for an N-gas call to use `N - O(1)` bytes of memory. + +## Specification + +Change `memory_cost` from: + +```python +memory_size_word = (memory_byte_size + 31) / 32 +memory_cost = (memory_size_word ** 2) / 512 + (3 * memory_size_word) +``` + +To: + +```python +memory_size_word = (memory_byte_size + 31) / 32 +memory_cost = 3 * memory_size_word +``` + +Additionally, if a memory expansion would lead to `memory_byte_size` strictly exceeding the current call's initial gas limit, revert with an error. + +When making any type of call, change the maximum gas limit from the current [EIP-150](eip-150.md) definition: + +```python +def max_call_gas(gas): + return gas - (gas // 64) +``` + +To: + +```python +def max_call_gas(gas, memory_byte_size): + return gas - max(gas // 64, memory_byte_size) +``` + +## Rationale + +With this EIP, there is a simple EVM implementation that can process an N-gas call using an N-byte bytearray as memory: allocate all bytes to the current context, when doing a child call use the remaining memory starting from the position `memory_byte_size` for the child call's memory, and so on recursively. + +Having this clean invariant is useful for EVM implementations, especially EVM implementations in constrained environments (eg. ZK-SNARK provers). + +The 3 gas per word memory expansion cost is retained because it is equivalent to MCOPY, and so the operation of clearing memory at the end of a child call (cheap in regular machines, but more expensive in ZK-SNARKs and other unusual contexts) can be implemented with the same logic as that used to implement the MCOPY opcode itself. + +The 63/64 rule is maintained in order to maintain the current de-facto call stack depth limit of roughly `1 + log((gaslimit + 6300) / 6400) / log(64/63) = 537`. + +## Backwards Compatibility + +It is theoretically possible for EVM code that works today to fail to work under this new EIP, if that code accesses a high index in memory but is called with a low gas limit. However, almost all EVM execution consumes far more code than it uses bytes of memory. For example, for a call to cause even a single state change, it must have at least 5000 gas. This would allow it 5000 bytes of memory, which is greater than that used by almost all applications. More complex applications would have even higher limits. + +## Security Considerations + +No security concerns were raised. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7688.md b/EIPS/eip-7688.md new file mode 100644 index 00000000000000..857294e0586d93 --- /dev/null +++ b/EIPS/eip-7688.md @@ -0,0 +1,300 @@ +--- +eip: 7688 +title: Forward compatible consensus data structures +description: Transition consensus SSZ data structures to StableContainer +author: Etan Kissling (@etan-status), Cayman (@wemeetagain) +discussions-to: https://ethereum-magicians.org/t/eip-7688-forward-compatible-consensus-data-structures/19673 +status: Draft +type: Standards Track +category: Core +created: 2024-04-15 +requires: 6110, 7002, 7251, 7495, 7549, 7569 +--- + +## Abstract + +This EIP defines the changes needed to adopt `StableContainer` from [EIP-7495](./eip-7495.md) in consensus data structures. + +## Motivation + +Ethereum's consensus data structures make heavy use of [Simple Serialize (SSZ)](https://github.com/ethereum/consensus-specs/blob/ef434e87165e9a4c82a99f54ffd4974ae113f732/ssz/simple-serialize.md) `Container`, which defines how they are serialized and merkleized. The merkleization scheme allows application implementations to verify that individual fields (and partial fields) have not been tampered with. This is useful, for example, in smart contracts of decentralized staking pools that wish to verify that participating validators have not been slashed. + +While SSZ `Container` defines how data structures are merkleized, the merkleization is prone to change across the different forks. When that happens, e.g., because new features are added or old features get removed, existing verifier implementations need to be updated to be able to continue processing proofs. + +`StableContainer`, of [EIP-7495](./eip-7495.md), is a forward compatible alternative that guarantees a forward compatible merkleization scheme. By transitioning consensus data structures to use `StableContainer`, smart contracts that contain verifier logic no longer have to be maintained in lockstep with Ethereum's fork schedule as long as the underlying features that they verify don't change. For example, as long as the concept of slashing is represented using the boolean `slashed` field, existing verifiers will not break when unrelated features get added or removed. This is also true for off-chain verifiers, e.g., in hardware wallets or in operating systems for mobile devices that are on a different software update cadence than Ethereum. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +### Conversion procedure + +For each converted data structure, a new fork agnostic `StableContainer` type `B` is introduced that serves as the primary definition of each data structure. + +- Each `StableContainer` is assigned a capacity to represent its potential design space that SHALL NOT change across future forks; if it is later determined that it is insufficient, a new field can be added to contain additional fields in a sub-container. +- The `StableContainer` starts as a copy of the latest fork's `Container` equivalent, except that all field types `T` are wrapped into `Optional[T]`. +- To guarantee forward and backward compatibility, new fields from future forks MUST only be appended to the `StableContainer` definition. +- The type of existing fields MUST NOT change, including the capacity of `List`/`Bitlist`. If a change is necessary, the old field SHALL NOT be used anymore and a new field with a new name SHALL be considered. It is important to anticipate potential future extensions when deciding on the capacities of the `StableContainer` itself and of the various lists. +- For `List`/`Bitlist`, the opportunity SHOULD be used to re-evaluate their design space capacity. If the design space is increased, application logic SHALL check the fork specific length limit; the SSZ library solely defines the merkleization limit, not the serialization limit. +- The conversion process is repeated for each field type. All field types referred to by the `StableContainer` MUST be `StableContainer` themselves, or are considered immutable. + +Subsequently, for each `StableContainer` base type `B`, a fork specific `Profile[B]` type is introduced that matches the latest fork's `Container` equivalent. The old `Container` is no longer necessary. The SSZ serialization of `Profile` is compatible with `Container`, but the merkleization and `hash_tree_root` are computed differently. Furthermore, `Profile` MAY use fields of `Optional` type if necessary. + +Subsequent forks specify a new `Profile`. + +- If new fields of type `T` are added, they are appended to the `StableContainer` as `Optional[T]` to register them with the stable merkleization scheme. In the new fork's `Profile`, the new field MAY be `T` (required), or `Optional[T]` (optional). +- If old fields are deprecated, they are kept in the `StableContainer` to retain the stable merkleization scheme. In the new fork's `Profile`, the field is omitted from the definition. The SSZ library guarantees that `hash_tree_root` and all generalized indices remain the same. +- Other fields MAY be changed between `T` (required) and `Optional[T]` (optional) in the new fork's `Profile`. No changes to the `StableContainer` are required for such changes. + +### Immutable types + +These types are used as part of the `StableContainer` definitions, and, as they are not `StableContainer` themselves, are considered to have immutable Merkleization. If a future fork requires changing these types in an incompatible way, a new type SHALL be defined and assigned a new field name. + +| Type | Description | +| - | - | +| [`Slot`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Slot number on the beacon chain | +| [`Epoch`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Epoch number on the beacon chain, a group of slots | +| [`CommitteeIndex`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Index of a committee within a slot | +| [`ValidatorIndex`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Unique index of a beacon chain validator | +| [`Gwei`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Amount in Gwei (1 ETH = 10^9 Gwei = 10^18 Wei) | +| [`Root`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Byte vector containing an SSZ Merkle root | +| [`Hash32`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Byte vector containing an opaque 32-byte hash | +| [`Version`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Consensus fork version number | +| [`BLSPubkey`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Cryptographic type representing a BLS12-381 public key | +| [`BLSSignature`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#custom-types) | Cryptographic type representing a BLS12-381 signature | +| [`KZGCommitment`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/_features/sharding/polynomial-commitments.md#custom-types) | G1 curve point for the KZG polynomial commitment scheme | +| [`Fork`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#fork) | Consensus fork information | +| [`Checkpoint`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#checkpoint) | Tuple referring to the most recent beacon block up through an epoch's start slot | +| [`Validator`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#validator) | Information about a beacon chain validator | +| [`AttestationData`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#attestationdata) | Vote that attests to the availability and validity of a particular consensus block | +| [`Eth1Data`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#eth1data) | Target tracker for importing deposits from transaction logs | +| [`DepositData`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#depositdata) | Log data emitted as part of a transaction's receipt when depositing to the beacon chain | +| [`BeaconBlockHeader`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#beaconblockheader) | Consensus block header | +| [`ProposerSlashing`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#proposerslashing) | Tuple of two equivocating consensus block headers | +| [`Deposit`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#deposit) | Tuple of deposit data and its inclusion proof | +| [`VoluntaryExit`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#voluntaryexit) | Consensus originated request to exit a validator from the beacon chain | +| [`SignedVoluntaryExit`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/phase0/beacon-chain.md#signedvoluntaryexit) | Tuple of voluntary exit request and its signature | +| [`SyncAggregate`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/beacon-chain.md#syncaggregate) | Cryptographic type representing an aggregate sync committee signature | +| [`ExecutionAddress`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/bellatrix/beacon-chain.md#custom-types) | Byte vector containing an account address on the execution layer | +| [`Transaction`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/bellatrix/beacon-chain.md#custom-types) | Byte list containing an RLP encoded transaction | +| [`WithdrawalIndex`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/capella/beacon-chain.md#custom-types) | Unique index of a withdrawal from any validator's balance to the execution layer | +| [`Withdrawal`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/capella/beacon-chain.md#withdrawal) | Withdrawal from a beacon chain validator's balance to the execution layer | +| [`DepositReceipt`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#depositreceipt) | Tuple of flattened deposit data and its sequential index | +| [`ExecutionLayerWithdrawalRequest`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#executionlayerwithdrawalrequest) | Execution originated request to withdraw from a validator to the execution layer | +| [`BLSToExecutionChange`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/capella/beacon-chain.md#blstoexecutionchange) | Request to register the withdrawal account address of a beacon chain validator | +| [`SignedBLSToExecutionChange`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/capella/beacon-chain.md#signedblstoexecutionchange) | Tuple of withdrawal account address registration request and its signature | +| [`Consolidation`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#consolidation) | Request to consolidate the balances of two beacon chain validators into one | +| [`SignedConsolidation`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#signedconsolidation) | Tuple of consolidation request and its signature | +| [`ParticipationFlags`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/altair/beacon-chain.md#custom-types) | Participation tracker of a beacon chain validator within an epoch | +| [`HistoricalSummary`](https://github.com/ethereum/consensus-specs/blob/4afe39822c9ad9747e0f5635cca117c18441ec1b/specs/capella/beacon-chain.md#historicalsummary) | Tuple combining a historical block root and historical state root | +| [`PendingBalanceDeposit`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#pendingbalancedeposit) | Pending operation for depositing to a beacon chain validator | +| [`PendingPartialWithdrawal`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#pendingpartialwithdrawal) | Pending operation for withdrawing from a beacon chain validator | +| [`PendingConsolidation`](https://github.com/ethereum/consensus-specs/blob/2c1f677187e6534aec77057a7d1cc746a40d3630/specs/electra/beacon-chain.md#pendingconsolidation) | Pending operation for consolidating two beacon chain validators | + +### `StableContainer` capacities + +| Name | Value | Description | +| - | - | - | +| `MAX_ATTESTATION_FIELDS` | `uint64(2**3)` (= 8) | Maximum number of fields to which `StableAttestation` can ever grow in the future | +| `MAX_INDEXED_ATTESTATION_FIELDS` | `uint64(2**3)` (= 8) | Maximum number of fields to which `StableIndexedAttestation` can ever grow in the future | +| `MAX_EXECUTION_PAYLOAD_FIELDS` | `uint64(2**6)` (= 64) | Maximum number of fields to which `StableExecutionPayload` can ever grow in the future | +| `MAX_BEACON_BLOCK_BODY_FIELDS` | `uint64(2**6)` (= 64) | Maximum number of fields to which `StableBeaconBlockBody` can ever grow in the future | +| `MAX_BEACON_STATE_FIELDS` | `uint64(2**7)` (= 128) | Maximum number of fields to which `StableBeaconState` can ever grow in the future | + +Maximum proof depth: + +- `StableBeaconState` > `validators` (1 + 7) > `` (1 + 40) > `pubkey` (3) > `` (1) = 53 bits +- `StableBeaconBlockBody` > `execution_payload` (1 + 6) > `transactions` (1 + 6) > `` (1 + 20) > `` (1 + 25) = 61 bits + +### Fork-agnostic `StableContainer` definitions + +These type definitions are fork independent and shared across all forks. They are not exchanged over libp2p. + +```python +class StableAttestation(StableContainer[MAX_ATTESTATION_FIELDS]): + aggregation_bits: Optional[Bitlist[MAX_VALIDATORS_PER_COMMITTEE * MAX_COMMITTEES_PER_SLOT]] + data: Optional[AttestationData] + signature: Optional[BLSSignature] + committee_bits: Optional[Bitvector[MAX_COMMITTEES_PER_SLOT]] + +class StableIndexedAttestation(StableContainer[MAX_INDEXED_ATTESTATION_FIELDS]): + attesting_indices: Optional[List[ValidatorIndex, MAX_VALIDATORS_PER_COMMITTEE * MAX_COMMITTEES_PER_SLOT]] + data: Optional[AttestationData] + signature: Optional[BLSSignature] + +class StableAttesterSlashing(Container): + attestation_1: StableIndexedAttestation + attestation_2: StableIndexedAttestation + +class StableExecutionPayload(StableContainer[MAX_EXECUTION_PAYLOAD_FIELDS]): + parent_hash: Optional[Hash32] + fee_recipient: Optional[ExecutionAddress] # 'beneficiary' in the yellow paper + state_root: Optional[Bytes32] + receipts_root: Optional[Bytes32] + logs_bloom: Optional[ByteVector[BYTES_PER_LOGS_BLOOM]] + prev_randao: Optional[Bytes32] # 'difficulty' in the yellow paper + block_number: Optional[uint64] # 'number' in the yellow paper + gas_limit: Optional[uint64] + gas_used: Optional[uint64] + timestamp: Optional[uint64] + extra_data: Optional[ByteList[MAX_EXTRA_DATA_BYTES]] + base_fee_per_gas: Optional[uint256] + block_hash: Optional[Hash32] # Hash of execution block + transactions: Optional[List[Transaction, MAX_TRANSACTIONS_PER_PAYLOAD]] + withdrawals: Optional[List[Withdrawal, MAX_WITHDRAWALS_PER_PAYLOAD]] # [New in Capella] + blob_gas_used: Optional[uint64] # [New in Deneb:EIP4844] + excess_blob_gas: Optional[uint64] # [New in Deneb:EIP4844] + deposit_receipts: Optional[List[DepositReceipt, MAX_DEPOSIT_RECEIPTS_PER_PAYLOAD]] # [New in Electra:EIP6110] + # [New in Electra:EIP7002:EIP7251] + withdrawal_requests: Optional[List[ExecutionLayerWithdrawalRequest, MAX_WITHDRAWAL_REQUESTS_PER_PAYLOAD]] + +class StableExecutionPayloadHeader(StableContainer[MAX_EXECUTION_PAYLOAD_FIELDS]): + parent_hash: Optional[Hash32] + fee_recipient: Optional[ExecutionAddress] + state_root: Optional[Bytes32] + receipts_root: Optional[Bytes32] + logs_bloom: Optional[ByteVector[BYTES_PER_LOGS_BLOOM]] + prev_randao: Optional[Bytes32] + block_number: Optional[uint64] + gas_limit: Optional[uint64] + gas_used: Optional[uint64] + timestamp: Optional[uint64] + extra_data: Optional[ByteList[MAX_EXTRA_DATA_BYTES]] + base_fee_per_gas: Optional[uint256] + block_hash: Optional[Hash32] # Hash of execution block + transactions_root: Optional[Root] + withdrawals_root: Optional[Root] # [New in Capella] + blob_gas_used: Optional[uint64] # [New in Deneb:EIP4844] + excess_blob_gas: Optional[uint64] # [New in Deneb:EIP4844] + deposit_receipts_root: Optional[Root] # [New in Electra:EIP6110] + withdrawal_requests_root: Optional[Root] # [New in Electra:EIP7002:EIP7251] + +class StableBeaconBlockBody(StableContainer[MAX_BEACON_BLOCK_BODY_FIELDS]): + randao_reveal: Optional[BLSSignature] + eth1_data: Optional[Eth1Data] # Eth1 data vote + graffiti: Optional[Bytes32] # Arbitrary data + proposer_slashings: Optional[List[ProposerSlashing, MAX_PROPOSER_SLASHINGS]] + attester_slashings: Optional[List[StableAttesterSlashing, MAX_ATTESTER_SLASHINGS_ELECTRA]] # [Modified in Electra:EIP7549] + attestations: Optional[List[StableAttestation, MAX_ATTESTATIONS_ELECTRA]] # [Modified in Electra:EIP7549] + deposits: Optional[List[Deposit, MAX_DEPOSITS]] + voluntary_exits: Optional[List[SignedVoluntaryExit, MAX_VOLUNTARY_EXITS]] + sync_aggregate: Optional[SyncAggregate] # [New in Altair] + execution_payload: Optional[StableExecutionPayload] # [New in Bellatrix] + bls_to_execution_changes: Optional[List[SignedBLSToExecutionChange, MAX_BLS_TO_EXECUTION_CHANGES]] # [New in Capella] + blob_kzg_commitments: Optional[List[KZGCommitment, MAX_BLOB_COMMITMENTS_PER_BLOCK]] # [New in Deneb:EIP4844] + consolidations: Optional[List[SignedConsolidation, MAX_CONSOLIDATIONS]] # [New in Electra:EIP7251] + +class StableBeaconState(StableContainer[MAX_BEACON_STATE_FIELDS]): + # Versioning + genesis_time: Optional[uint64] + genesis_validators_root: Optional[Root] + slot: Optional[Slot] + fork: Optional[Fork] + # History + latest_block_header: Optional[BeaconBlockHeader] + block_roots: Optional[Vector[Root, SLOTS_PER_HISTORICAL_ROOT]] + state_roots: Optional[Vector[Root, SLOTS_PER_HISTORICAL_ROOT]] + historical_roots: Optional[List[Root, HISTORICAL_ROOTS_LIMIT]] # Frozen in Capella, replaced by historical_summaries + # Eth1 + eth1_data: Optional[Eth1Data] + eth1_data_votes: Optional[List[Eth1Data, EPOCHS_PER_ETH1_VOTING_PERIOD * SLOTS_PER_EPOCH]] + eth1_deposit_index: Optional[uint64] + # Registry + validators: Optional[List[Validator, VALIDATOR_REGISTRY_LIMIT]] + balances: Optional[List[Gwei, VALIDATOR_REGISTRY_LIMIT]] + # Randomness + randao_mixes: Optional[Vector[Bytes32, EPOCHS_PER_HISTORICAL_VECTOR]] + # Slashings + slashings: Optional[Vector[Gwei, EPOCHS_PER_SLASHINGS_VECTOR]] # Per-epoch sums of slashed effective balances + # Participation + previous_epoch_participation: Optional[List[ParticipationFlags, VALIDATOR_REGISTRY_LIMIT]] # [Modified in Altair] + current_epoch_participation: Optional[List[ParticipationFlags, VALIDATOR_REGISTRY_LIMIT]] # [Modified in Altair] + # Finality + justification_bits: Optional[Bitvector[JUSTIFICATION_BITS_LENGTH]] # Bit set for every recent justified epoch + previous_justified_checkpoint: Optional[Checkpoint] + current_justified_checkpoint: Optional[Checkpoint] + finalized_checkpoint: Optional[Checkpoint] + # Inactivity + inactivity_scores: Optional[List[uint64, VALIDATOR_REGISTRY_LIMIT]] # [New in Altair] + # Sync + current_sync_committee: Optional[SyncCommittee] # [New in Altair] + next_sync_committee: Optional[SyncCommittee] # [New in Altair] + # Execution + latest_execution_payload_header: Optional[StableExecutionPayloadHeader] # [New in Bellatrix] + # Withdrawals + next_withdrawal_index: Optional[WithdrawalIndex] # [New in Capella] + next_withdrawal_validator_index: Optional[ValidatorIndex] # [New in Capella] + # Deep history valid from Capella onwards + historical_summaries: Optional[List[HistoricalSummary, HISTORICAL_ROOTS_LIMIT]] # [New in Capella] + deposit_receipts_start_index: Optional[uint64] # [New in Electra:EIP6110] + deposit_balance_to_consume: Optional[Gwei] # [New in Electra:EIP7251] + exit_balance_to_consume: Optional[Gwei] # [New in Electra:EIP7251] + earliest_exit_epoch: Optional[Epoch] # [New in Electra:EIP7251] + consolidation_balance_to_consume: Optional[Gwei] # [New in Electra:EIP7251] + earliest_consolidation_epoch: Optional[Epoch] # [New in Electra:EIP7251] + pending_balance_deposits: Optional[List[PendingBalanceDeposit, PENDING_BALANCE_DEPOSITS_LIMIT]] # [New in Electra:EIP7251] + # [New in Electra:EIP7251] + pending_partial_withdrawals: Optional[List[PendingPartialWithdrawal, PENDING_PARTIAL_WITHDRAWALS_LIMIT]] + pending_consolidations: Optional[List[PendingConsolidation, PENDING_CONSOLIDATIONS_LIMIT]] # [New in Electra:EIP7251] +``` + +### Fork-specific `Profile` definitions + +The consensus type definitions specific to the fork that introduces this EIP are updated to inherit the Merkleization of the `StableContainer` definitions. Fields are kept as is. + +```python +class Attestation(Profile[StableAttestation]): + ... + +class IndexedAttestation(Profile[StableIndexedAttestation]): + ... + +class ExecutionPayload(Profile[StableExecutionPayload]): + ... + +class ExecutionPayloadHeader(Profile[StableExecutionPayloadHeader]): + ... + +class BeaconBlockBody(Profile[StableBeaconBlockBody]): + ... + +class BeaconState(Profile[StableBeaconState]): + ... +``` + +## Rationale + +### Best timing? + +Applying this EIP breaks `hash_tree_root` and Merkle tree verifiers a single time, while promising forward compatibility from the fork going forward. It is best to apply it before merkleization would be broken by different changes. Merkleization is broken by a `Container` reaching a new power of 2 in its number of fields. + +### Can this be applied retroactively? + +While `Profile` serializes in the same way as the legacy `Container`, the merkleization and `hash_tree_root` of affected data structures changes. Therefore, verifiers that wish to process Merkle proofs of legacy variants still need to support the corresponding legacy schemes. + +### Immutability + +Once a field in a `StableContainer` has been published, its name can no longer be used to represent a different type in the future. This includes list types with a higher capacity than originally intended. This is in line with historical management of certain cases: + +- Phase0: `BeaconState` contained `previous_epoch_attestations` / `current_epoch_attestations` +- Altair: `BeaconState` replaced these fields with `previous_epoch_participation` / `current_epoch_participation` + +Furthermore, new fields have to be appended at the end of `StableContainer`. This is in line with historical management of other cases: + +- Capella appended `historical_summaries` to `BeaconState` instead of squeezing the new field next to `historical_roots` + +With `StableContainer`, stable Merkleization requires these rules to become strict. + +## Backwards Compatibility + +Existing Merkle proof verifiers need to be updated to support the new Merkle tree shape. This includes verifiers in smart contracts on different blockchains and verifiers in hardware wallets, if applicable. + +Note that backwards compatibility is also broken when one of the converted `Container` data structures would reach a new power of 2 in its number of fields. + +## Security Considerations + +None + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7692.md b/EIPS/eip-7692.md new file mode 100644 index 00000000000000..f0e7661ee0d16e --- /dev/null +++ b/EIPS/eip-7692.md @@ -0,0 +1,43 @@ +--- +eip: 7692 +title: EVM Object Format (EOFv1) Meta +description: List of EIPs belonging to the EOFv1 proposal +author: Alex Beregszaszi (@axic), Paweł Bylica (@chfast), Andrei Maiboroda (@gumb0), Piotr Dobaczewski (@pdobacz), Danno Ferrin (@shemnon) +discussions-to: https://ethereum-magicians.org/t/eip-7692-evm-object-format-eof-meta/19686 +status: Review +type: Meta +created: 2024-04-17 +requires: 663, 3540, 3670, 4200, 4750, 5450, 6206, 7069, 7480, 7620, 7698 +--- + +## Abstract + +This Meta EIP lists the EIPs which belong to the EVM Object Format (EOF) proposal, in its first version (EOFv1), also known as the "Mega EOF". + +## Specification + +### EIPs Included + +- [EIP-3540](./eip-3540.md): EOF - EVM Object Format v1 +- [EIP-3670](./eip-3670.md): EOF - Code Validation +- [EIP-4200](./eip-4200.md): EOF - Static relative jumps +- [EIP-4750](./eip-4750.md): EOF - Functions +- [EIP-5450](./eip-5450.md): EOF - Stack Validation +- [EIP-6206](./eip-6206.md): EOF - JUMPF and non-returning functions +- [EIP-7480](./eip-7480.md): EOF - Data section access instructions +- [EIP-663](./eip-663.md): SWAPN, DUPN and EXCHANGE instructions +- [EIP-7069](./eip-7069.md): Revamped CALL instructions +- [EIP-7620](./eip-7620.md): EOF Contract Creation +- [EIP-7698](./eip-7698.md): EOF - Creation transaction + +## Rationale + +Refer to the individual EIPs. + +## Security Considerations + +Discussed in the individual EIPs. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7698.md b/EIPS/eip-7698.md new file mode 100644 index 00000000000000..7dd9e85b65f214 --- /dev/null +++ b/EIPS/eip-7698.md @@ -0,0 +1,79 @@ +--- +eip: 7698 +title: EOF - Creation transaction +description: Deploy EOF contracts using creation transactions +author: Piotr Dobaczewski (@pdobacz), Andrei Maiboroda (@gumb0), Paweł Bylica (@chfast), Alex Beregszaszi (@axic) +discussions-to: https://ethereum-magicians.org/t/eip-7698-eof-creation-transaction/19784 +status: Review +type: Standards Track +category: Core +created: 2024-04-24 +requires: 3540, 7620 +--- + +## Abstract + +Creation transactions (i.e. the ones with empty `to`) can be used to deploy EOF contracts by providing EOF initcontainer concatenated with `calldata` for initcontainer execution in transaction's `data`. Initcontainer execution is similar to its execution during `EOFCREATE` instruction, ending with `RETURNCONTRACT` instruction. New account address calculation is based on sender's address and nonce. + +## Motivation + +Creation transaction is one if the three ways alongside creation instructions provided by legacy EVM to deploy new code. Given that legacy creation instructions (`CREATE` and `CREATE2`) are not allowed to deploy EOF code, supporting EOF in creation transactions is the only way to get the first EOF on-chain. + +The mechanism for providing constructor arguments to initcontainer is exactly the same as for deploying legacy code (just concatenating them with initcontainer), therefore existing deployment tooling can be used as is to deploy EOF. + +## Specification + +### Parameters + +| Constant | Value | +| - | - | +| `EOF_MAGIC` | Defined as `0xEF00` in [EIP-3540](./eip-3540.md) | +| `MAX_CODE_SIZE` | Defined as `24576` in [EIP-170](./eip-170.md) | + + +In case a creation transaction (transaction with empty `to`) has `data` starting with `EOF_MAGIC`, `data` is interpreted as a concatenation of EOF `initcontainer` and `calldata`. More specifically: + +1. Intrinsic gas cost rules and limits defined in [EIP-3860](./eip-3860.md) for creation transactions apply. The entire `data` of the transaction is used for these calculations. +2. Find the split of `data` into `initcontainer` and `calldata`: + - Parse EOF header + - Find `intcontainer` size by reading all section sizes from the header and adding them up with the header size to get the full container size. +3. Validate the `initcontainer` and all its subcontainers recursively. + - Unlike in general validation, `initcontainer` is additionally required to have `data_size` declared in the header equal to actual `data_section` size. + - Validation includes checking that the container is an "initcode" container as defined in [EIP-7620](./eip-7620.md), that is, it does not contain `RETURN` or `STOP` +4. If EOF header parsing or full container validation fails, transaction is considered valid and failing. Gas for initcode execution is not consumed, only intrinsic creation transaction costs are charged. +5. `calldata` part of transaction `data` that follows `initcontainer` is treated as calldata to pass into the execution frame. +6. Execute the container and deduct gas for execution. + 1. Calculate `new_address` as `keccak256(sender || sender_nonce)[12:]` + 2. A successful execution ends with initcode executing `RETURNCONTRACT{deploy_container_index}(aux_data_offset, aux_data_size)` instruction. After that: + - load deploy-contract from EOF subcontainer at `deploy_container_index` in the container from which `RETURNCONTRACT` is executed, + - concatenate data section with `(aux_data_offset, aux_data_offset + aux_data_size)` memory segment and update data size in the header, + - let `deployed_code_size` be updated deploy container size, + - if `deployed_code_size > MAX_CODE_SIZE` instruction exceptionally aborts, + - set `state[new_address].code` to the updated deploy container (rules of [EIP-3541](./eip-3541.md), prohibiting deployment of `code` starting with `EF` from creation transactions, do not apply in this case). +7. Deduct `200 * deployed_code_size` gas. + +## Rationale + +### Irregular state change to deploy Creator Contract + +Originally it was proposed to deploy the first EOF contract via irregular state change. This contract would execute `TXCREATE` instruction and could be used then as an entry point to deploy any other EOF code. This would also require an introduction of `InitcodeTransaction`, required by `TXCREATE`. It was decided against this variant for the benefit of reduced scope of changes. + +### Constructor arguments outside of initcontainer vs in data section + +Alternative mechanism for providing constructor arguments to initcontainer execution was considered, where they are concatenated with data section of the initcontainer and are accessed via `DATA*` instructions instead of `CALLDATA*`. This has a benefit of not requiring the step finding the split of `transaction.data` into `initcontainer` and `calldata`, as entire `transaction.data` is an EOF container. However it was rejected for the following reasons: + +- Existing tooling could not be used for deploying EOF without modification. To construct EOF creation transaction, the tooling would need to append constructor arguments to the container, as well as update data section size in the EOF header. Compiler could predict the size of constructor arguments to put the anticipated data size in the header, but it would not be possible for variadic length constructor arguments. +- In case a specialized EOF creation transaction is introduced in a later upgrade (such as `InitcodeTransaction` defined in [EIP-7620](./eip-7620.md)), it would have a dedicated field for initcontainer execution input (`calldata`), and it will be accessed with `CALLDATA*` instructions in initcode. It is better to avoid the situation where compilers would need to generate initcontainer code differently depending on which context it will be used in. +- As a general argument, data section can be seen to contain the data that execution considers validated and being closely coupled with the code definition, whereas calldata is an input from the outside that may be arbitrary and not validated. + +## Backwards Compatibility + +Creation transactions deploying legacy code are not affected, because any such transaction starting with `EF` byte previously would fail on executing invalid instruction. + +## Security Considerations + +TBA + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7701.md b/EIPS/eip-7701.md new file mode 100644 index 00000000000000..5ea95cd60374c6 --- /dev/null +++ b/EIPS/eip-7701.md @@ -0,0 +1,213 @@ +--- +eip: 7701 +title: Native Account Abstraction with EOF +description: A variant of RIP-7560 transactions relying on EOF Smart Contract Accounts +author: Vitalik Buterin (@vbuterin), Yoav Weiss (@yoavw), Alex Forshtat (@forshtat), Dror Tirosh (@drortirosh), Shahaf Nacson (@shahafn) +discussions-to: https://ethereum-magicians.org/t/eip-7701-native-account-abstraction-with-eof/19893 +status: Draft +type: Standards Track +category: Core +created: 2024-05-01 +requires: 3540 +--- + +## Abstract + +This proposal describes a slight variation of the Native Account Abstraction design fully described in RIP-7560. +This version's difference compared to the original proposal is in relying on features of "EVM Object Format" to +distinguish between validation and execution code sections. + +## Motivation + +Talking about Full Native Account Abstraction, the fundamental idea any solution has to address is a +mechanism for a Smart Contract Account to separate its validation and execution code sections. + +RIP-7560 is build on the current Ethereum contract structure, and therefore has little choice but to rely +on using some higher-level abstraction. + +In its current form, RIP-7560 transactions use Solidity method selectors in order to achieve this separation. + +This, however, is far from ideal as this approach "leaks" the concept from a programming language widely used +in the EVM into the core design of the Ethereum protocol. + +While there is no purely technical reason to disallow it and there are already instances of Solidity code +being "enshrined" in the Ethereum protocol, e.g. the validator deposit contract, such violation of abstraction levels +often lead to unnecessary technical debt and are worth avoiding if possible. + +Additionally, method selectors provide very weak indication of the contract developer's decision to become a +participant in Native Account Abstraction transaction flow. +The chance of accidentally exposing a function with a colliding 4 byte +method identifier that returns a valid 4 byte magic to indicate approval is pretty low, but a malicious developer +can easily hide such a function giving it an innocent name, making it hard to spot a Native Account Abstraction entity. + +This issue to some extent is also present in [ERC-4337](./eip-4337.md). + +As an alternative, if Native Account Abstraction is to be implemented in coordination with [EIP-3540](./eip-3540), +relying on the concept of "code sections" it introduces is a superior approach. + +## Specification + +### System-level code entry points + +Modify the EOF container format to consist of the following sections: + +``` +container := header, body +header := + magic, version, + kind_types, types_size, + kind_entrypoints, entrypoints_size, + kind_code, num_code_sections, code_size+, + [kind_container, num_container_sections, container_size+,] + kind_data, data_size, + terminator +body := types_section, entrypoints_section, code_section+, container_section*, data_section +types_section := (inputs, outputs, max_stack_height)+ +entrypoints_section := (entrypoints_role, target_section_index, target_section_pc_offset)+ +``` + +For regular calls to the contract, the execution always starts at the first byte of code section 0, and pc is set to 0. + +Here the `entrypoints_section` defines alternative indexes of code sections to start the execution for system calls. +This is reserved for execution of special roles in the `entrypoints_role` range. + +Note: do not confuse code execution `entrypoint` with the `EntryPoint` contract defined in ERC-4337. + +### Validation and PostTransaction code entry points + +The contract that may have a role in an Account Abstraction transaction, either as a Sender, a Paymaster or a Deployer, +has to contain a section marked with one of the following `entrypoints_role` marker: + +``` +role_sender_execution = 0x0000 +role_sender_deployment = 0x0001 +role_sender_validation = 0x0002 +role_paymaster_validation = 0x0003 +role_paymaster_posttx = 0x0004 +``` + +This section is equivalent to a code section. + +Its code can be executed during a regular transaction execution and has no special effects. +If it is the first code section of a contract, it can act as an entry point during regular transaction execution. + +Only a single section per role is allowed in a contract. +This rule is validated during contract creation. + +### Execution entry point for Account Abstraction transaction type participant entity (Sender, Paymaster and Deployer) + +During a regular contract code execution, its behaviour is defined as follows by EIP-3540: + +``` +Execution starts at the first byte of code section 0, and pc is set to 0 +``` + +However, if a contract is referenced in an `AA_TX_TYPE` transaction as a Sender, Paymaster or a Deployer, +execution starts at the first byte of code section with the `entrypoints_role` marker corresponding to the current step, +and `pc` is set to the corresponding `target_section_pc_offset`. + +If the specified contract does not contain such a section, or is not an EOF contract, the transaction is not valid. + +### Encoding inputs for different execution frames + +#### Sender Deployment + +Inputs to the `deployer` contract are not defined by the protocol and are controlled by the `deployerData` parameter. + +The sender deployment frame MUST result in the `sender` address becoming initialized with contract code. + +This step is performed with the `role_sender_validation` code section. + +#### Sender Validation + +Inputs to the `Sender` validation section are defined by the protocol as an SSZ encoding of the transaction data, +excluding the `chainId` and `accessList` fields and with an extra field of the `txHash`: + +``` +ssz([ + subtype, + sender, nonce, builderFee, + callData, + paymaster, paymasterData, + deployer, deployerData, + maxPriorityFeePerGas, maxFeePerGas, + validationGasLimit, paymasterValidationGasLimit, + callGasLimit, paymasterPostOpGasLimit + signature, txHash +] +``` + +This step is performed with the `role_sender_deployment` code section. + +In order for the transaction to be considered valid the +sender validation frame MUST return two 64-bit values: + +``` +ssz(bool success, uint64 validUntil, uint64 validAfter) +``` + +#### Paymaster Validation + +Inputs to the `Paymaster` validation section are same as the ones in the [Sender Validation](#sender-validation) step. + +This step is performed with the `role_paymaster_validation` code section. + +In order for the transaction to be considered valid the +paymaster validation frame MUST return the following values: + +``` +ssz(uint64 validUntil, uint64 validAfter, bytes context) +``` + +#### Sender Execution + +This step is performed with the `role_sender_execution` code section. + +Inputs to the `Sender` contract are not defined by the protocol and are controlled by the `callData` parameter. + +#### Paymaster post-transaction frame + +Inputs to the `Paymaster` post-transaction are defined by the protocol as an SSZ encoding of the following data: + +``` +ssz([uint256 actualGasCost, bool success, bytes context]) +``` + +This step is performed with the `role_paymaster_posttx` code section. + +## Rationale + +### SSZ encoding for system frames' input and output data + +Using an SSZ encoding format for data provided by the protocol itself does represent an abstraction levels violation, +however it is a relatively safe and any alternative solution would require some trade-offs. + +The validation section of a Smart Contract Account code needs to have full access to the majority of transaction +details in order to be able to make an informed decision about either accepting or rejecting the transaction. + +A small subset of this data is available with the existing opcodes, however creating an opcode for every transaction +parameter is not feasible. + +Allowing wallets to specify their own encoding for this data is also not feasible as Smart Contract Accounts must +avoid any ambiguity about the meaning of the received data. + +## Backwards Compatibility + +An EOF contract with `kind_entrypoints` section is not valid according to EIP-3540 and cannot exist on-chain +before this proposal is implemented. + +The introduction of `kind_entrypoints` will break an assumption that a contract code can only have a single +execution starting point, which might confuse some developer tooling that relies on this assumption. + +## Security Considerations + +A contract with a `kind_entrypoints` section explicitly indicates its role as a Native Account Abstraction entity. +This is a significant improvement over ERC-4337 and RIP-7560 where entities are not explicitly marked. + +As the `kind_entrypoints` code sections represent a generic way to authorize any action on behalf of the contract, +correct and secure implementation of this code is critical. +We expect compilers targeting EVM will play a major role in enabling and ensuring Smart Contract Accounts' security. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7702.md b/EIPS/eip-7702.md new file mode 100644 index 00000000000000..b04782b4d2bfcd --- /dev/null +++ b/EIPS/eip-7702.md @@ -0,0 +1,184 @@ +--- +eip: 7702 +title: Set EOA account code for one transaction +description: Add a new tx type that sets the code for an EOA during one transaction execution +author: Vitalik Buterin (@vbuterin), Sam Wilson (@SamWilsn), Ansgar Dietrichs (@adietrichs), Matt Garnett (@lightclient) +discussions-to: https://ethereum-magicians.org/t/eip-set-eoa-account-code-for-one-transaction/19923 +status: Review +type: Standards Track +category: Core +created: 2024-05-07 +requires: 2718, 2929, 2930 +--- + +## Abstract + +Add a new transaction type that adds a list of `[address, y_parity, r, s]` authorization tuples, and converts the signing accounts (not necessarily the same as the `tx.origin`) into smart contract wallets for the duration of that transaction. + +## Motivation + +There is a lot of interest in adding short-term functionality improvements to EOAs, increasing the usability of applications and in some cases allowing improved security. Three particular applications include: + +* **Batching**: allowing multiple operations from the same user in one atomic transaction. One common example is an [ERC-20](./eip-20.md) approval followed by spending that approval, a common workflow in DEXes that requires two transactions today. Advanced use cases of batching occasionally involve dependencies: the output of the first operation is part of the input to the second operation. +* **Sponsorship**: account X pays for a transaction on behalf of account Y. Account X could be paid in some other ERC-20 for this service, or it could be an application operator including the transactions of its users for free. +* **Privilege de-escalation**: users can sign sub-keys, and give them specific permissions that are much weaker than global access to the account. For example, you could imagine a permission to spend ERC-20 tokens but not ETH, or to spend up to 1% of total balance per day, or to interact only with a specific application. + +## Specification + +### Parameters + +| Parameter | Value | +| -------------------- | ------ | +| `SET_CODE_TX_TYPE` | `0x04` | +| `MAGIC` | `0x05` | +| `PER_AUTH_BASE_COST` | `2500` | + +### Set Code Transaction + +We introduce a new [EIP-2718](./eip-2718.md) transaction, "set code transaction", where the `TransactionType` is `SET_CODE_TX_TYPE` and the `TransactionPayload` is the RLP serialization of the following: + +``` +rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, value, data, access_list, authorization_list, signature_y_parity, signature_r, signature_s]) + +authorization_list = [[chain_id, address, [nonce], y_parity, r, s], ...] +``` + +The fields `chain_id`, `nonce`, `max_priority_fee_per_gas`, `max_fee_per_gas`, `gas_limit`, `destination`, `value`, `data`, and `access_list` of the outer transaction follow the same semantics as [EIP-1559](./eip-1559.md). + +The `authorization_list` is a list of tuples that store the address to code which the signer desires to set in their EOA temporarily. The third element is a list item mimicking an optional value. When the list length is zero, consider the authorization nonce to be null. When the list length is one, consider the single integer value to be the provided nonce authorization. Other lengths and value types in this optional are invalid. + +The [EIP-2718](./eip-2718.md) `ReceiptPayload` for this transaction is `rlp([status, cumulative_transaction_gas_used, logs_bloom, logs])`. + +#### Behavior + +At the start of executing the transaction, for each `[chain_id, address, [nonce], y_parity, r, s]` tuple: + +1. `authority = ecrecover(keccak(MAGIC || rlp([chain_id, [nonce], address])), y_parity, r, s]` +2. Verify the chain id is either 0 or the chain's current ID. +3. Verify that the code of `authority` is empty. +4. If nonce list item is length one, verify the nonce of `authority` is equal to `nonce`. +5. Set the code of `authority` to code associated with `address`. +6. Add the `authority` account to `accessed_addresses` (as defined in [EIP-2929](./eip-2929.md).) + +If any of the above steps fail, immediately stop processing that tuple and continue to the next tuple in the list. It will In the case of multiple tuples for the same authority, set the code specified by the address in the first occurrence. + +At the end of the transaction, set the code of each `authority` back to empty. + +Note that the signer of an authorization tuple may be different than `tx.origin` of the transaction. + +#### Gas Costs + +The intrinsic cost of the new transaction is inherited from [EIP-2930](./eip-2930.md), specifically `21000 + 16 * non-zero calldata bytes + 4 * zero calldata bytes + 1900 * access list storage key count + 2400 * access list address count`. Additionally, we add a cost of `PER_CONTRACT_CODE_BASE_COST * authorization list length`. + +The transaction sender will pay for all authorization tuples, regardless of validity or duplication. + +## Rationale + +### No initcode + +Running initcode is not desirable for many reasons. The chief concern is it's unnatural. Initcode is intended to initialize and deploy contracts. With this EIP, it will take on a new role of determine whether it is appropriate to deploy code to the EOA. Suppose a user only wants code deployed to their account if they also have an operation bundled with the general transaction calldata. This gives EOA a unique power to control when and what code executes in their account. Although [EIP-7702](./eip-7702.md) as written still allows this to a degree, the lack of programmability in the decision will force wallets to not sign many authorization tuples and instead focus signing only a tuple pointing to a configurable proxy. This affords EOAs a similar experience to smart contract wallets + +Additionally, initcode in transaction tends to be propagated inside the transaction. That means it would need to be included in the authorization tuple and signed over. The minimum initcode would be around 15 bytes and that would simply copy the contract code from an external address. The total cost would be `16 * 15 = 240` calldata cost, plus the [EIP-3860](./eip-3860.md) cost of `2 * 15 = 30`, plus the runtime costs of around `150`. So nearly `500` additional gas would be spent simply preparing the account; and even more likely, 1200+ gas if not copying from an external account. + +### Creation by template + +Initcode or not, there is a question of how users should specify the code they intend to run in their account. The two main options are to specify the bytecode directly in the transaction or to specify a pointer to the code. The simplest pointer would just the address of some code deployed on-chain. + +The cost analysis makes the answer clear. The smallest proxy would be around 50 bytes and an address is 20 bytes. The 30 byte difference provides no useful additional functionality and will be inefficiently replicated billions of times on the chain. + +Furthermore, specifying code directly would again make it possible for EOAs to have a new, unique ability to execute arbitrary code specified in the transaction calldata. + +### Lack of instruction prohibition + +Consistency is a valuable property in the EVM, both from an implementation perspective and a user understanding perspective. Despite considering bans on several families of instructions in the context of EOAs, the authors feel there is not a compelling reason to do so. It will force smart contract wallets and EOA smart contract wallets to proceed down distinct paths of contract development. + +The main families of instructions where a ban was considered were storage related and contract creation related. The decision to not ban storage instructions hinged mostly on their importance to smart contract wallets. Although it's possible to have an external storage contract that the smart contract wallet calls into, it is unnecessarily inefficient. In the future, new state schemes may even allow substantially cheaper access to certain storage slots. This is something smart contract wallets will very much want to take advantage of that a storage contract wouldn't support. + +Creation instructions were considered for a ban on other similar EIPs, however because this EIP allows EOAs to spend value intra-transaction, the concern with bumping the nonce intra-transaction and invalidating pending transactions is not significant. A neat byproduct of this is that by combining EIP-7702 and CREATE2 it will be possible to commit to deploy specific bytecode to an address without committing to any fee market parameters. This solves the long standing issue of universal cross-chain contract deployment. + +### Signature structure + +The signature scheme in this EIP supports flexible design patterns, allowing for both full delegation to `address` and more protected delegations to `address`. + +#### Code pointer + +One consideration when signing a code pointer is what code might that address point to on another chain. For some use cases, it may not be desirable to expend the effort verifying the deployment was deterministic. In such situations, the chain ID can be set to reduce the scope of the authorization. For other situations where universal deployment is preferred, e.g. delegating to a wallet proxy. In these cases, it's possible to set chain ID to 0 for validity on all EIP-7702 chains. Wallet maintainers will be able to hard code a single EIP-7702 authorization message into their wallet so that cross-chain code malleability never becomes a concern. + +An alternative to adding chain ID could be to sign over the code the address points to. This seems to have the benefit of both minimizing the on-chain size of auth tuples while retaining specificity of the actual code running in the account. One unfortunate issue of this format though is that it imposes a database lookup to determine the signer of each auth tuple. This imposition itself seems to create enough complexity in transaction propagation that it is decided to avoid and simply sign over address directly. + +#### In-protocol revocation + +A hotly debated element of this EIP is the need for in-protocol revocation. Although it is possible to implement revocation logic within delegated code, for some this isn't sufficient and it is the duty of the protocol to provide a revocation option of last resort. + +For this reason, the proposal provides two separate schemes. The first is an eternal delegation to a smart contract. At the protocol level, it is not possible to revoke. However, the contract you delegate to is one which can expect to use in your account for perpetuity; similar to how smart contract wallet users deploy proxy contracts to their account and point the target at a wallet implementation. The second is a scoped delegation with a revocation mechanism based on the EOA's nonce. This is a safer to begin using smart contract code in the context of your EOA without potentially committing to a specific piece of code forever. + +### Self-sponsoring: allowing `tx.origin` to set code + +Allowing `tx.origin` to set code enables simple transaction batching, where the sender of the outer transaction would be the signing account. The ERC-20 approve-then-transfer pattern, which currently requires two separate transactions, could be completed in a single transaction with this proposal. + +Once code exists in the EOA, it's possible for self-sponsored EIP-7702 transactions to have `msg.sender == tx.origin` anytime the code in the EOA dispatches a call. Without EIP-7702, this situation can only ever arise in the topmost execution layer of a transaction. Therefore this EIP breaks that invariant and so it affects smart contracts containing `require(msg.sender == tx.origin)` checks. This check is used for at least three purposes: + + 1. Ensuring that `msg.sender` is an EOA (given that `tx.origin` always has to be an EOA). This invariant does not depend on the execution layer depth and, therefore, is not affected. + 2. Protecting against atomic sandwich attacks like flash loans, that rely on the ability to modify state before and after the execution of the target contract as part of the same atomic transaction. This protection would be broken by this EIP. However, relying on `tx.origin` in this way is considered bad practice, and can already be circumvented by miners conditionally including transactions in a block. + 3. Preventing reentrancy. + +Examples of (1) and (2) can be found in contracts deployed on Ethereum mainnet, with (1) being more common (and unaffected by this proposal.) On the other hand, use case (3) is more severely affected by this proposal, but the authors of this EIP did not find any examples of this form of reentrancy protection, though the search was non-exhaustive. + +This distribution of occurrences—many (1), some (2), and no (3)—is exactly what the authors of this EIP expect, because: + + * Determining if `msg.sender` is an EOA without `tx.origin` is difficult (if not impossible.) + * The only execution context which is safe from atomic sandwich attacks is the topmost context, and `tx.origin == msg.sender` is the only way to detect that context. + * In contrast, there are many direct and flexible ways of preventing reentrancy (ex. using a transient storage variable.) Since `msg.sender == tx.origin` is only true in the topmost context, it would make an obscure tool for preventing reentrancy, rather than other more common approaches. + +There are other approaches to mitigate this restriction which do not break the invariant: + + * Set `tx.origin` to a constant `ENTRY_POINT` address when using `CALL*` instruction in the context of an EOA. + * Set `tx.origin` to a special address derived from the sender or signer addresses. + * Disallow `tx.origin` from setting code. This would make the simple batching use cases impossible, but could be relaxed in the future. + +### Forward-compatibility with future account abstraction + +This EIP is designed to be very forward-compatible with endgame account abstraction, without over-enshrining any fine-grained details of [ERC-4337](./eip-4337.md) or RIP-7560. + +Specifically: + +* The code that users would need to sign could literally be existing ERC-4337 wallet code. +* The "code pathways" that are used are code pathways that would, in many cases (though perhaps not all), continue to "make sense" in a pure-smart-contract-wallet world. +* Hence, it avoids the problem of "creating two separate code ecosystems", because to a large extent they would be the same ecosystem. There would be some workflows that require kludges under this solution that would be better done in some different "more native" under "endgame AA", but this is relatively a small subset. +* It does not require adding any opcodes, that would become dangling and useless in a post-EOA world. +* It allows EOAs to temporarily convert themselves into contracts to be included in ERC-4337 bundles, in a way that's compatible with the existing `EntryPoint`. +* Once this is implemented, allowing EOAs to migrate permanently is "only one line of code": just add a flag to not set the code back to empty at the end. + +## Backwards Compatibility + +This EIP breaks the invariant that an account balance can only decrease as a result of transactions originating from that account. It also breaks the invariant that an EOA nonce may not increase after transaction execution has begun. These breakages have consequences for mempool design, and for other EIPs such as inclusion lists. However, because the accounts are listed statically in the outer transaction it is possible to modify transaction propagation rules so that conflicting transactions are not forwarded. + +## Security Considerations + +### Secure delegation + +The following is a non-exhaustive list of checks/pitfalls/conditions that delegate contracts *should* be wary of and require a signature over from the account's authority: + + * Replay protection -- (ex. a nonce) should be implemented by the delegate and signed over. Without it, a malicious actor can reuse a signature, repeating its effects. + * `value` -- without it, a malicious sponsor could cause unexpected effects in the callee. + * `gas` -- without it, a malicious sponsor could cause the callee to run out of gas and fail, griefing the sponsee. + * `target` / `calldata` -- without them, a malicious actor may call arbitrary functions in arbitrary contracts. + +A poorly implemented delegate can *allow a malicious actor to take near complete control over a signer's EOA*. + +### Setting code as `tx.origin` + +Allowing the sender of an EIP-7702 to also set code has the possibility to: + + * Break atomic sandwich protections which rely on `tx.origin`; + * Break reentrancy guards of the style `require(tx.origin == msg.sender)`. + +The authors of this EIP believe the risks of allowing this are acceptable for the reasons outlined in the Rationale section. + +### Sponsored Transaction Relayers + +It is possible for the `authorized` account to cause sponsored transaction relayers to spend gas without being reimbursed by either invalidating the authorization (i.e. increasing the account's nonce) or by sweeping the relevant assets out of the account. Relayers should be designed with these cases in mind, possibly by requiring a bond to be deposited or by implementing a reputation system. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7703.md b/EIPS/eip-7703.md new file mode 100644 index 00000000000000..ffeb6abd5e56d6 --- /dev/null +++ b/EIPS/eip-7703.md @@ -0,0 +1,43 @@ +--- +eip: 7703 +title: Increase calldata cost +description: Increase calldata cost to decrease the maximum block size +author: William Morriss (@wjmelements) +discussions-to: https://ethereum-magicians.org/t/eip-7703-increase-calldata-cost/19933 +status: Draft +type: Standards Track +category: Core +created: 2024-05-07 +--- + +## Abstract + +An adjustment in the Ethereum calldata cost which reduces the maximum possible block size and allows a higher block gas limit. + +## Motivation + +Larger blocks take longer to propagate through the network. +In this way, the maximium potential block size is constraining the block gas limit. +Therefore, in order to safely increase the block gas limit, the calldata gas must be increased. + +## Specification + +* Increase `G_CALLDATAZERO` from 4 to 12. +* Increase `G_CALLDATANONZERO` from 16 to 48. + +## Rationale + +Tripling the gas cost of calldata reduces the maximimum possible block size by a factor of three. + +## Backwards Compatibility + +Activation can cause some transactions to revert due to the increased gas costs. +Ahead of activation, `eth_estimateGas` could be calculated using the new parameters in order to provide results viable for activation, avoiding out-of-gas reverts. + +## Security Considerations + +No security issues have been found. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7705.md b/EIPS/eip-7705.md new file mode 100644 index 00000000000000..c14118084db26e --- /dev/null +++ b/EIPS/eip-7705.md @@ -0,0 +1,53 @@ +--- +eip: 7705 +title: NONREENTRANT and REENTRANT opcodes +description: Opcodes to mark a contract as nonreentrant +author: Charles Cooper (@charles-cooper) +discussions-to: https://ethereum-magicians.org/t/eip-7705-nonreentrant-opcodes/19957 +status: Draft +type: Standards Track +category: Core +created: 2024-05-09 +--- + +## Abstract + +Add two opcodes, `NONREENTRANT` and `REENTRANT`, which set and clear a contract's reentrancy status. After invoking `NONREENTRANT`, a contract cannot be `CALL`ed (or `STATICCALL`ed, or `DELEGATECALL`ed) until `REENTRANT` is invoked. + +## Motivation + +Reentrancy attacks account for a substantial portion of user funds stolen on EVM chains, including the famous "DAO hack". However, due to the cost of preventing against reentrancy attacks in application code, developers often opt-out of reentrancy protection. This cost has come down with the advent of transient storage ([EIP-1153](./eip-1153.md)), but it is still not cheap enough where it is a "no-brainer" to use it by default. This EIP proposes opcodes which make it cheaper to protect against reentrancy in application code. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Two new opcodes are introduced, `NONREENTRANT` (0xF6) and `REENTRANT` (0xF7), which set and clear a contract's nonreentrancy flag. The effect of invoking `NONREENTRANT` is that a contract can no longer have execution context transferred to it (via any of the `*CALL` opcodes), until `REENTRANT` is invoked. `CALL`ing a contract which has the nonreentrancy flag set is equivalent to executing a single `REVERT` opcode. + +Both `NONREENTRANT` and `REENTRANT` are idempotent; that is, invoking `NONREENTRANT` when a contract already has nonreentrant status is a no-op, and likewise for `REENTRANT`. + +The scope of the nonreentrant flag is limited to the current transaction. That is, nonreentrant flags are cleared at the end of every transaction. In the presence of reversion (`REVERT` or exceptional halt), the contract's nonreentrancy flag reverts to whatever its value was before the call. + +The cost of `NONREENTRANT` and `REENTRANT` are both set at 5 (`G_mid`). + +## Rationale + +The computational cost of pushing the current value to the call stack (for handling reverts) is accounted for in the overhead cost of the `*CALL` opcodes. + +An alternative design could be considered which only introduces one opcode. This opcode, `NONREENTRANT`, would take a single stack item and set the nonreentrancy flag based on its value. This alternative design can be considered based on feedback. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Test Cases + +## Reference Implementation + +## Security Considerations + +TBD + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7706.md b/EIPS/eip-7706.md new file mode 100644 index 00000000000000..7548abc40c679b --- /dev/null +++ b/EIPS/eip-7706.md @@ -0,0 +1,246 @@ +--- +eip: 7706 +title: Separate gas type for calldata +description: Create a separate basefee and gaslimit for calldata +author: Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7706-create-a-separate-basefee-and-gaslimit-for-calldata/19998 +status: Draft +type: Standards Track +category: Core +created: 2024-05-13 +requires: 1559, 4844 +--- + +## Abstract + +Add a new type of gas for transaction calldata. Add a new transaction type that provides `max_basefee` and `priority_fee` as a vector, providing values for execution gas, blob gas and calldata gas. Modify the basefee adjustment to use the same mechanism for the three types of gas. + +## Motivation + +A major argument against raising the Ethereum gas limit, making calldata cheaper, or increasing the [EIP-4844](./eip-4844.md) blob count before technologies like PeerDAS become available, is that the theoretical maximum size of an Ethereum block is already too large, and we cannot afford to increase it further. However, there is an inefficiency here: the current average size of a block (not including blobs) is ~100 kB, and the theoretical max is `30,000,000 / 16 = 1,875,000` bytes (one could make larger blocks using zero bytes, but in practice zero-byte-heavy blocks would be compressed to less than 1.87 million bytes due to snappy compression). Ideally, we would have a way to bound the maximum, without making calldata more scarce _on average_. + +This EIP does exactly this, by adopting the same technique that was applied for blob data in EIP-4844: we introduce a separate fee market for calldata, with a separate basefee and a separate per-block gas limit. The theoretical max calldata size of a block would be greatly reduced, while basic economic analysis suggests that _on average_, calldata would become considerably cheaper. + +The EIP also introduces a new transaction type which includes the three types of max-basefees and priority fees as a vector, allowing the same code paths to handle all three types of gas. We also make the basefee adjustment, which currently uses separate mechanisms for execution gas (introduced in [EIP-1559](./eip-1559.md)) and blobs (introduced in EIP-4844), use the same approach for all three types of gas. This simplifies the basefee adjustment rules, and ensures that the stronger mathematical properties of the newer EIP-4844 basefee adjustment algorithm cover all three types of gas. + +## Specification + +The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +### Parameters + +* `FORK_BLKNUM` = `TBD` +* `NEW_TX_TYPE` = `TBD` +* `CALLDATA_GAS_PER_TOKEN` = `4` +* `TOKENS_PER_NONZERO_BYTE` = `4` +* `CALLDATA_GAS_LIMIT_RATIO` = `4` +* `LIMIT_TARGET_RATIOS = [2, 2, 4]` +* `MIN_BASE_FEE_PER_GAS = 1` # Rename of EIP-4844 MIN_BASE_FEE_PER_BLOB_GAS +* `BASE_FEE_UPDATE_FRACTION = 8` # Roughly matches EIP-4844 parameters + +### New transaction type + +As of `FORK_BLOCK_NUMBER`, a new [EIP-2718](./eip-2718.md) transaction is introduced with `TransactionType` = `TX_TYPE(NEW_TX_TYPE)`. + +The [EIP-2718](./eip-2718.md) `TransactionPayload` for this transaction is + +``` +[chain_id, nonce, gas_limit, to, value, data, access_list, blob_versioned_hashes, max_fees_per_gas, priority_fees_per_gas, y_parity, r, s] +``` + +We require `max_fees_per_gas` and `priority_fees_per_gas` to be length-3 vectors, each of which contain integers from `0` to `2**64-1`. + +The intrinsic cost of the new transaction is inherited from EIP-4844, except that the calldata gas cost (16 per nonzero byte, 4 per zero byte) is removed. + +### Block processing and transaction fees + +We add the functions `get_max_fees` and `get_priority_fees`, to compute these length-3 vectors for previous transaction types: + +``` +def get_max_fees(tx: Transaction) -> [int, int, int]: + if tx.type == NEW_TX_TYPE: + return tx.max_fees_per_gas + elif tx.type == BLOB_TX_TYPE: + return [tx.max_fee_per_gas, tx.max_fee_per_blob_gas, tx.max_fee_per_gas] + elif is_eip_1559(tx.type): + return [tx.max_fee_per_gas, 0, tx.max_fee_per_gas] + else: + return [tx.gasprice, 0, tx.gasprice] +``` + +``` +def get_priority_fees(tx: Transaction) -> [int, int, int]: + if tx.type == NEW_TX_TYPE: + return tx.priority_fees_per_gas + elif tx.type == BLOB_TX_TYPE: + return [tx.max_priority_fee_per_gas, 0, tx.max_priority_fee_per_gas] + elif is_eip_1559(tx.type): + return [tx.max_priority_fee_per_gas, 0, tx.max_priority_fee_per_gas] + else: + return [tx.gasprice, 0, tx.gasprice] +``` + +We also add some helpers: + +``` +def all_less_or_equal(v1: [int, int, int], v2: [int, int, int]) -> bool: + return all(x <= y for x, y in zip(v1, v2)) + +def vector_add(v1: [int, int, int], v2: [int, int, int]) -> [int, int, int]: + return [x+y for x, y in zip(v1, v2)] + +def vector_subtract(v1: [int, int, int], v2: [int, int, int]) -> [int, int, int]: + return [x-y for x, y in zip(v1, v2)] + +def vector_subtract_clamp_at_zero(v1: [int, int, int], v2: [int, int, int]) -> [uint, uint, uint]: + return [x-y if x >= y else 0 for x, y in zip(v1, v2)] + +def vector_mul(v1: [int, int, int], v2: [int, int, int]) -> [int, int, int]: + return [x*y for x, y in zip(v1, v2)] +``` + +``` +# Same rules as current calldata pricing, but rephrased (similar language to EIP-7623) +def get_calldata_gas(calldata: bytes) -> int: + tokens = calldata.count(0) + (len(calldata) - calldata.count(0)) * TOKENS_PER_NONZERO_BYTE + return tokens * CALLDATA_GAS_PER_TOKEN +``` + +``` +def get_gaslimits(tx: Transaction) -> [int, int, int]: + if tx.type == NEW_TX_TYPE: + return [tx.gaslimit, len(tx.blob_versioned_hashes) * GAS_PER_BLOB, get_calldata_gas(tx.data)] + elif tx.type == BLOB_TX_TYPE: + return [tx.gaslimit, len(tx.blob_versioned_hashes) * GAS_PER_BLOB, get_calldata_gas(tx.data)] + elif is_eip_1559(tx.type): + return [tx.gaslimit, 0, get_calldata_gas(tx.data)] + else: + return [tx.gaslimit, 0, get_calldata_gas(tx.data)] +``` + +``` +def get_fees_per_gas(tx: Transaction, block_basefees: [int, int, int]) -> [int, int, int]: + max_fees = get_max_fees(tx) + priority_fees = get_priority_fees(tx) + output = [] + # Fee sufficiency check, similar to EIP-1559 and 4844 + require(all_less_or_equal(block_basefees, max_fees)) + # Similar logic to EIP-1559 and 4844 + return [ + min(basefee + priority_fee, max_fee) + for block_basefee, max_fee, priority_fee in zip(block_basefees, max_fees, priority_fees) + ] +``` + +``` +get_block_gaslimits(block: Block) -> [int, int, int]: + return [block.gaslimit, MAX_BLOB_GAS_PER_BLOCK, block.gaslimit // CALLDATA_GAS_LIMIT_RATIO] +``` + +**At the start of block processing**: + +* We initialize a vector `gas_used_so_far` to `[0, 0, 0]` + +**At the start of processing a transaction**: + +* Compute `fees_per_gas = get_fees_per_gas(tx, get_block_basefees(block))` and `tx_gaslimits = get_gaslimits(tx)` +* Check that `all_less_or_equal(vector_add(gas_used_so_far, tx_gaslimits), block.gas_limits)` +* Deduct `sum(vector_mul(fees_per_gas, tx_gaslimits))` wei from the `tx.origin` account + +Note that `get_block_basefees(block)` is not yet defined, we will define it in the section below. The `block.gas_limits` field is also defined in the section below. + +**At the end of processing a transaction**: + +* Compute `tx_gas_consumed` as a three item vector, where the first item is the amount of gas actually consumed by the transaction execution, and the second and third match the values in `get_gaslimits(tx)` +* Refund `sum(vector_mul(fees_per_gas, vector_sub(tx_gaslimits, tx_gas_consumed)))` to the `tx.origin` account (in practice, only the first term will be nonzero for now) +* Set `gas_used_so_far = vector_add(gas_used_so_far, tx_gas_consumed)` + +**At the end of processing a block**: + +* Require `block.gas_used = gas_used_so_far` + +The `block.gas_used` field will be defined in the section below. + +### Block structure: + +We update `BlockHeader` field, to remove the `blob_gas_used`, `gas_used`, `base_fee_per_gas`, `gas_limit` and `excess_blob_gas` fields, and we add new fields, all of the `[int, int, int]` type: `gas_limits`, `gas_used`, `excess_gas`. The resulting RLP encoding becomes: + +``` +rlp([ + parent_hash, + 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, # ommers hash + coinbase, + state_root, + txs_root, + receipts_root, + logs_bloom, + 0, # difficulty + number, + timestamp, + extradata, + prev_randao, + 0x0000000000000000, # nonce + withdrawals_root, + gas_limits, + gas_used, + excess_gas +]) +``` + +We define: + +``` +get_block_gas_targets(parent: Header) -> [int, int, int]: + return [limit // target_ratio for limit, target_ratio in zip(parent.gas_limits, LIMIT_TARGET_RATIOS)] +``` + +We calculate the required `excess_gas` values as follows: + +``` +def calc_excess_gas(parent: Header) -> [int, int, int]: + return vector_subtract_clamp_at_zero(vector_add(parent_excess, parent_used), get_block_gas_targets(parent)) +``` + +We calculate the required `gas_limits` as follows: + +* `gas_limits[0]` must follow the existing adjustment formula +* `gas_limits[1]` must equal `MAX_BLOB_GAS_PER_BLOCK` +* `gas_limits[2]` must equal `gas_limits[0] // CALLDATA_GAS_LIMIT_RATIO` + +Now, we define `get_block_basefees`: + +``` +def get_block_basefees(parent: Header) -> [int, int, int]: + return [ + fake_exponential( + MIN_BASE_FEE_PER_GAS, + excess_gas, + target * BASE_FEE_UPDATE_FRACTION + ) + for (excess_gas, target) in zip(parent.excess_gas, get_block_gas_targets(parent)) + ] +``` + +## Rationale + +### Conversion of all gas-related mechanics into vectors + +This allows the same logic that is used for handling gas to handle all three types of gas. As a result, it's arguably a net simplification of protocol gas handling logic, despite the fact that the total number of gas types increases from 2 to 3 + +### Target ratios + +The target ratios for execution gas and blobs are set to 2; the target ratio for calldata is set to 4. This greatly decreases the number of scenarios in which calldata actually hits the limit, which mitigates economic impact of the EIP, because analysis of EIP-1559-style fee markets is much simpler in "under-the-limit" conditions than in "at-the-limit" conditions. Additionally, it reduces the risk that applications requiring large calldata will outright stop working. + +The current parameters set the target calldata per block to 187,500 bytes, about 2x the current average. Using basic supply-and-demand reasoning, this implies that calldata is likely to become significantly cheaper as a result of this EIP. + +## Backwards Compatibility + +Previous transaction types set the calldata basefee and priority fee to equal each other. The calldata gas costs were intentionally set to be identical to today, and the gas target similar to present-day usage, so that setting the two fees to be equal each other is a reasonable approximation to optimal behavior. In practice, the new transaction type would be superior, so we expect users to switch to it over time. However, the loss suffered by old-style transaction users would not be that high, because priority fees are generally small compared to basefees, and the amount that a user pays is proportional to the basefee. + +## Security Considerations + +Optimal block building behavior becomes more complex as a result of this EIP, particularly under the boundary conditions when blocks are full of one or both types of gas. We argue that the effects of this are not too large, because in practice over 90% of blocks are under-full, and naive "greedy algorithms" can get a close-enough-to-optimal outcome. The centralization risks of proprietary block-building algorithms are thus likely to be much smaller than other existing risks with eg. MEV extraction. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7708.md b/EIPS/eip-7708.md new file mode 100644 index 00000000000000..d3f58878e19162 --- /dev/null +++ b/EIPS/eip-7708.md @@ -0,0 +1,56 @@ +--- +eip: 7708 +title: ETH transfers emit a log +description: All ETH transfers emit a log +author: Vitalik Buterin (@vbuterin), Peter Davies (@petertdavies) +discussions-to: https://ethereum-magicians.org/t/eip-7708-eth-transfers-emit-a-log/20034 +status: Draft +type: Standards Track +category: Core +created: 2024-05-17 +--- + +## Abstract + +All ETH-transfers, including transactions, `CALL` and `SELFDESTRUCT` emit a log. + +## Motivation + +Logs are often used to track when balance changes of assets on Ethereum. Logs work for [ERC-20](./eip-20.md) tokens, but they do not work for ETH. ETH transfers from EOAs can be read from the transaction list in the block, but ETH transfers from smart contract wallets are not automatically logged anywhere. This has already led to problems in the past, eg. early exchanges would often not properly support deposits from smart contract wallets, or only support them with a much longer delay. This EIP proposes that we automatically generate a log every time a value-transferring `CALL` or `SELFDESTRUCT` happens. We also add a similar log for transfers in transactions, so that all ETH transfers can be tracked using one mechanism. + +## Specification + +### Parameters + +* `MAGIC`: `TBD` + +### Functionality + +Whenever (i) a nonzero-value `CALL`, (ii) a nonzero-value-transferring `SELFDESTRUCT`, or (iii) a nonzero-value-transferring transaction takes place, issue a log, identical to a LOG3, with three topics: (i) `MAGIC`, (ii) the sender address, (iii) the recipient address. The log data is a big-endian 32-byte encoding of the transfer value. + +The `LOG` of a value-transferring transaction should be placed before any logs created by EVM execution. The other two `LOG`s are placed at the time that the value transfer executes. + +## Rationale + +This is the simplest possible implementation that ensures that all ETH transfers are implemented in some kind of record that can be easily accessed through making RPC calls into a node, or through asking for a Merkle branch that is hashed into the block root. The log type is compatible with the ERC-20 token standard, but does not introduce any overly-specific ERC-20 features (eg. ABI encodings) into the specification. + +### Open questions + +1. Should withdrawals also trigger a log? If so, what should the sender address be specified as? +2. Should fee payments trigger a log? It would ensure "completeness", in the sense that you can compute the exact current balance table by watching logs, but it would greatly increase the number of logs, perhaps to an unacceptably high amount. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Test Cases + +TODO + +## Security Considerations + +ETH transfers already cost a minimum of 6700 gas, which is much more expensive than the LOG3 opcode (1500 gas). Hence, this EIP does not increase the worst-case number of logs that can be put into a block. It will somewhat increase the average number of logs. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7709.md b/EIPS/eip-7709.md new file mode 100644 index 00000000000000..6f69c9abd491bc --- /dev/null +++ b/EIPS/eip-7709.md @@ -0,0 +1,101 @@ +--- +eip: 7709 +title: Read BLOCKHASH from storage and update cost +description: Read the `BLOCKHASH (0x40)` opcode from the EIP-2935 system contract storage and adjust its gas cost to reflect storage access. +author: Vitalik Buterin (@vbuterin), Tomasz Stanczak (@tkstanczak), Guillaume Ballet (@gballet), Gajinder Singh (@g11tech), Tanishq Jasoria (@tanishqjasoria), Ignacio Hagopian (@jsign), Jochem Brouwer (@jochem-brouwer), Gabriel Rocheleau (@gabrocheleau) +discussions-to: https://ethereum-magicians.org/t/eip-7709-read-blockhash-opcode-from-storage-and-adjust-gas-cost/20052 +status: Draft +type: Standards Track +category: Core +created: 2024-05-18 +requires: 2935 +--- + +## Abstract + +Update the `BLOCKHASH (0x40)` opcode to read and serve from the system contract storage and charge the **additional** (cold or warm) storage costs. + +## Motivation + +The `BLOCKHASH (0x40)` opcode currently assumes that the client has knowledge of the previous blocks, which in Verkle [EIP-6800](./eip-6800.md) would prevent stateless execution. However with [EIP-2935](./eip-2935.md) blockhashes can be retrieved and served from its system contract storage which allows Verkle blocks to include a storage access witness for stateless execution. + +## Specification + +| Parameter | Value | +| ------------------------- | ------ | +| `FORK_TIMESTAMP` | TBD | +| `HISTORY_STORAGE_ADDRESS` | TBD | +| `BLOCKHASH_SERVE_WINDOW` | `256` | + +The `BLOCKHASH` opcode semantics remains the same as before. From the `fork_block` (defined as `fork_block.timestamp >= FORK_TIMESTAMP and fork_block.parent.timestamp < FORK_TIMESTAMP`), the `BLOCKHASH` instruction should be updated to resolve block hash in the following manner: + +```python +def resolve_blockhash(block: Block, state: State, arg: uint64): + # note that outside the BLOCKHASH_SERVE_WINDOW we continue to return 0 + # despite the 2935 history contract being able to serve more hashes + if arg >= block.number or (arg + BLOCKHASH_SERVE_WINDOW) < block.number + return 0 + + # performs an sload on arg % HISTORY_SERVE_WINDOW including gas charges, + # warming effects as well as execution accesses + # + # note that the `BLOCKHASH_SERVE_WINDOW` and the 2935 ring buffer window + # `HISTORY_SERVE_WINDOW` for slot calculation are different + return state.load_slot(HISTORY_STORAGE_ADDRESS, arg % HISTORY_SERVE_WINDOW) +``` + +ONLY if the `arg` is within the correct `BLOCKHASH` window, clients can choose to either + +* do a direct `SLOAD` from state, or +* do a system call to [EIP-2935](./eip-2935.md) contract via its `get` mechanism (caller other than `SYSTEM_ADDRESS`) or +* serve from memory or as per current designs if maintaining requisite history (full clients for e.g.) + +However the entire semantics and after effects of the `SLOAD` operation needs to be applied as per the current fork if the `arg` is within the correct `BLOCKHASH` window: + +* `SLOAD` gas costs (cold or warm) for the `arg % HISTORY_SERVE_WINDOW` slot. +* `SLOAD` after effects on the slot (warming the slot) +* `SLOAD` accesses added to execution witnesses if Verkle ([EIP-6800](./eip-6800.md) and [EIP-4762](./eip-4762.md)) is activated + +### Activation + +This EIP specifies the transition to the new logic assuming that [EIP-2935](./eip-2935.md) has been activated: + +* sufficiently ahead of this EIP's activation (>= `BLOCKHASH_SERVE_WINDOW`) or +* at genesis for testnets/devnets where this EIP could also be activated at genesis + +The current proposal is to activate this EIP with Verkle to allow for stateless execution of the block. + +### Gas costs + +As described above, if the `arg` to be resolved is within the correct window, the corresponding `SLOAD` charges and accesses are to be applied for the slot `arg % HISTORY_SERVE_WINDOW`. Note that the `HISTORY_SERVE_WINDOW` and `BLOCKHASH_SERVE_WINDOW` are different. + +### Reading from the System contract + +Even if the clients choose to resolve `BLOCKHASH` through system call to [EIP-2935](./eip-2935.md) contract, the gas cost for the system code execution (and also the code witnesses if Verkle activated) is not applied. Only the effect of `SLOAD` is applied as described above. + +## Rationale + +* The reason behind the updated gas cost is to match the real operation, which is equivalent to an `SLOAD`. +* The [EIP-2935](./eip-2935.md) system contract execution charges (and accesses) are not applied to keep the gas low and to keep things simple for clients which choose to resolve `BLOCKHASH` in other ways (directly or though memory/maintained history) + +Note that `BLOCKHASH` opcode only serves a limited `BLOCKHASH_SERVE_WINDOW` to be backward compatible (and to not extend the above exemptions). For deeper accesses one will need to directly call [EIP-2935](./eip-2935.md) system contract which will lead to a normal contract execution (as well as charges and accesses) + +## Backwards Compatibility + +This EIP introduces a significant increase in the cost of `BLOCKHASH`, which could break use-cases that rely on the previous gas cost. Also, this EIP introduces a breaking change in the case where less than `BLOCKHASH_SERVE_WINDOW` elapse between the [EIP-2935](./eip-2935.md) fork and this EIP's fork (unless [EIP-2935](./eip-2935.md) is activated in genesis for e.g. in testnets/devnets) as the [EIP-2935](./eip-2935.md) system contract would not have saved the required history. + +## Test Cases + +* If `BLOCKHASH` is not called or there is no [EIP-2935](./eip-2935.md) contract call by any transaction, only the [EIP-2935](./eip-2935.md) system update of the parent hash shows up in witnesses if Verkle is activated. +* If `BLOCKHASH` is called, there MUST be a storage access gas charge (and corresponding access witness if Verkle is activated) for the storage slot but ONLY if the `BLOCKHASH` query is for the last `BLOCKHASH_SERVE_WINDOW` ancestors. This is irrespective of how the client chooses to resolve the `BLOCKHASH` (directly, via system contract or via memory) +* The gas cost for each `BLOCKHASH` operation should still be charged, in addition to the `SLOAD` cost of each lookup (if performed) +* If the [EIP-2935](./eip-2935.md) contract is called directly (i.e. not through `BLOCKHASH`), then the witness and gas costs (including those related to contract code) are applied as per normal contract execution of the current fork. +* `BLOCKHASH` should be consistently resolved if this EIP is activated correctly `>= BLOCKHASH_SERVE_WINDOW` after [EIP-2935](./eip-2935.md) + +## Security Considerations + +No security considerations other than the ones contained in [EIP-2935](./eip-2935.md) are determined as of now. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/EIPS/eip-7716.md b/EIPS/eip-7716.md new file mode 100644 index 00000000000000..8df573d87e8d9b --- /dev/null +++ b/EIPS/eip-7716.md @@ -0,0 +1,85 @@ +--- +eip: 7716 +title: Anti-correlation attestation penalties +description: Adjust penalties for missed attestations based on in-slot correlation of missed attestation +author: dapplion (@dapplion), Toni Wahrstätter (@nerolation), Vitalik Buterin (@vbuterin) +discussions-to: https://ethereum-magicians.org/t/eip-7716-anti-correlation-attestation-penalties/20137 +status: Draft +type: Standards Track +category: Core +created: 2024-05-25 +--- + + +## Abstract + +The decentralization of the validator set is one of the most important properties of Ethereum for credible neutrality and censorship resistance. By adjusting penalties to foster decentralization, diversification and fault-tolerance, this EIP proposes to adjust penalties in a way that more diversified entities get lower penalties while entities with high correlations in their setup face more severe ones. + + +## Motivation + +As of now, during times of usual network operation, there are no economic incentives to diversify node operations through using multiple different nodes, geographical locations, clients, ISP providers, etc., except for reducing the risk of penalties affecting all validators simultaneously, thereby limiting the impact to only a fraction of them. + +Attestation penalties are currently agnostic to other participation actions. This proposal scales attestation penalties as a function of other participants' actions. The goal is to decrease the profitability of participants that exhibit correlated behavior. + + + +## Specification + +| Parameter | Value | +| - | - | +| `PENALTY_ADJUSTMENT_FACTOR` | `4096` | +| `MAX_PENALTY_FACTOR` | `4` | + + +Add a variable `NET_EXCESS_PENALTIES` to the beacon state. + +Let `penalty_factor` be determined through + +``` +min( + (non_attesting_balance * PENALTY_ADJUSTMENT_FACTOR) // (NET_EXCESS_PENALTIES * total_active_balance + 1), + MAX_PENALTY_FACTOR +) +``` + +Let `NET_EXCESS_PENALTIES` be `max(1, NET_EXCESS_PENALTIES + penalty_factor) - 1` + + + +## Rationale + +### PENALTY_ADJUSTMENT_FACTOR + +This variable impacts the sensitivity of the `NET_EXCESS_PENALTIES`. + +Given stable participation, the `penalty_factor` is one. +If participation decreases, the `penalty_factor` will temporarily increase above one until `net_excess_penalties` catches up. +If participation increases, the `penalty_factor` will temporarily be zero until `net_excess_penalties` catches up. + +The `PENALTY_ADJUSTMENT_FACTOR` regulates how fast `net_excess_penalties` catches up. +In other words, the `PENALTY_ADJUSTMENT_FACTOR` determines the frequency that the penalty_factor is not one. + +A high `PENALTY_ADJUSTMENT_FACTOR` causes the `net_excess_penalties` to adjust slower. +A low `PENALTY_ADJUSTMENT_FACTOR` causes the `net_excess_penalties` to react more sensitively to changes in participation. + + +### `MAX_PENALTY_FACTOR` + +The `MAX_PENALTY_FACTOR` puts a ceiling onto the maximum factor with which the penalty for missed attestations is scaled to prevent overly harsh punishments. + + +## Backwards Compatibility + +This is a backwards incompatible adjustment of attestations rewards and penalties that requires a scheduled network upgrade. + + +## Security Considerations + +We acknowledge that splitting validator views can be leveraged as an attack to increase the `penalty_factor` for validators of consecutive slots with little risk for the proposer. +TBD. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). + diff --git a/EIPS/eip-777.md b/EIPS/eip-777.md index d5135dc371f08f..65fde9141b80c9 100644 --- a/EIPS/eip-777.md +++ b/EIPS/eip-777.md @@ -1,1278 +1,7 @@ --- eip: 777 -title: Token Standard -author: Jacques Dafflon , Jordi Baylina , Thomas Shababi -discussions-to: https://github.com/ethereum/EIPs/issues/777 -status: Final -type: Standards Track category: ERC -created: 2017-11-20 -requires: 1820 +status: Moved --- -## Simple Summary - -This EIP defines standard interfaces and behaviors for token contracts. - -## Abstract - -This standard defines a new way to interact with a token contract while remaining backward compatible with [ERC-20]. - -It defines advanced features to interact with tokens. -Namely, *operators* to send tokens on behalf of another address—contract or regular account—and -send/receive *hooks* to offer token holders more control over their tokens. - -It takes advantage of [ERC-1820] to find out whether and where to notify contracts and regular addresses -when they receive tokens as well as to allow compatibility with already-deployed contracts. - -## Motivation - -This standard tries to improve upon the widely used [ERC-20] token standard. -The main advantages of this standard are: - -1. Uses the same philosophy as Ether in that tokens are sent with `send(dest, value, data)`. - -2. Both contracts and regular addresses can control and reject which token they send - by registering a `tokensToSend` hook. - (Rejection is done by `revert`ing in the hook function.) - -3. Both contracts and regular addresses can control and reject which token they receive - by registering a `tokensReceived` hook. - (Rejection is done by `revert`ing in the hook function.) - -4. The `tokensReceived` hook allows to send tokens to a contract and notify it in a single transaction, - unlike [ERC-20] which requires a double call (`approve`/`transferFrom`) to achieve this. - -5. The holder can "authorize" and "revoke" operators which can send tokens on their behalf. - These operators are intended to be verified contracts - such as an exchange, a cheque processor or an automatic charging system. - -6. Every token transaction contains `data` and `operatorData` bytes fields - to be used freely to pass data from the holder and the operator, respectively. - -7. It is backward compatible with wallets that do not contain the `tokensReceived` hook function - by deploying a proxy contract implementing the `tokensReceived` hook for the wallet. - -## Specification - -### ERC777Token (Token Contract) - -``` solidity -interface ERC777Token { - function name() external view returns (string memory); - function symbol() external view returns (string memory); - function totalSupply() external view returns (uint256); - function balanceOf(address holder) external view returns (uint256); - function granularity() external view returns (uint256); - - function defaultOperators() external view returns (address[] memory); - function isOperatorFor( - address operator, - address holder - ) external view returns (bool); - function authorizeOperator(address operator) external; - function revokeOperator(address operator) external; - - function send(address to, uint256 amount, bytes calldata data) external; - function operatorSend( - address from, - address to, - uint256 amount, - bytes calldata data, - bytes calldata operatorData - ) external; - - function burn(uint256 amount, bytes calldata data) external; - function operatorBurn( - address from, - uint256 amount, - bytes calldata data, - bytes calldata operatorData - ) external; - - event Sent( - address indexed operator, - address indexed from, - address indexed to, - uint256 amount, - bytes data, - bytes operatorData - ); - event Minted( - address indexed operator, - address indexed to, - uint256 amount, - bytes data, - bytes operatorData - ); - event Burned( - address indexed operator, - address indexed from, - uint256 amount, - bytes data, - bytes operatorData - ); - event AuthorizedOperator( - address indexed operator, - address indexed holder - ); - event RevokedOperator(address indexed operator, address indexed holder); -} -``` - -The token contract MUST implement the above interface. -The implementation MUST follow the specifications described below. - -The token contract MUST register the `ERC777Token` interface with its own address via [ERC-1820]. - -> This is done by calling the `setInterfaceImplementer` function on the [ERC-1820] registry -> with the token contract address as both the address and the implementer -> and the `keccak256` hash of `ERC777Token` (`0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054`) -> as the interface hash. - -If the contract has a switch to enable or disable ERC777 functions, every time the switch is triggered, -the token MUST register or unregister the `ERC777Token` interface for its own address accordingly via ERC1820. -Unregistering implies calling the `setInterfaceImplementer` with the token contract address as the address, -the `keccak256` hash of `ERC777Token` as the interface hash and `0x0` as the implementer. -(See [Set An Interface For An Address][erc1820-set] in [ERC-1820] for more details.) - -When interacting with the token contract, all amounts and balances MUST be unsigned integers. -I.e. internally, all values are stored as a denomination of 1E-18 of a token. -The display denomination—to display any amount to the end user—MUST -be 1018 of the internal denomination. - -In other words, the internal denomination is similar to a wei -and the display denomination is similar to an ether. -It is equivalent to an [ERC-20]'s `decimals` function returning `18`. -E.g. if a token contract returns a balance of `500,000,000,000,000,000` (0.5×1018) for a user, -the user interface MUST show `0.5` tokens to the user. -If the user wishes to send `0.3` tokens, -the contract MUST be called with an amount of `300,000,000,000,000,000` (0.3×1018). - -User Interfaces which are generated programmatically from the ABI of the token contract -MAY use and display the internal denomination. -But this MUST be made clear, for example by displaying the `uint256` type. - -#### **View Functions** - -The `view` functions detailed below MUST be implemented. - -**`name` function** - -``` solidity -function name() external view returns (string memory) -``` - -Get the name of the token, e.g., `"MyToken"`. - -> **identifier:** `06fdde03` -> **returns:** Name of the token. - -**`symbol` function** - -``` solidity -function symbol() external view returns (string memory) -``` - -Get the symbol of the token, e.g., `"MYT"`. - -> **identifier:** `95d89b41` -> **returns:** Symbol of the token. - -**`totalSupply` function** - -``` solidity -function totalSupply() external view returns (uint256) -``` - -Get the total number of minted tokens. - -*NOTE*: The total supply MUST be equal to the sum of the balances of all addresses—as -returned by the `balanceOf` function. - -*NOTE*: The total supply MUST be equal to the sum of all the minted tokens -as defined in all the `Minted` events minus the sum of all the burned tokens as defined in all the `Burned` events. - -> **identifier:** `18160ddd` -> **returns:** Total supply of tokens currently in circulation. - -**`balanceOf` function** - -``` solidity -function balanceOf(address holder) external view returns (uint256) -``` - -Get the balance of the account with address `holder`. - -The balance MUST be zero (`0`) or higher. - -> **identifier:** `70a08231` -> **parameters** -> `holder`: Address for which the balance is returned. -> -> **returns:** Amount of tokens held by `holder` in the token contract. - -**`granularity` function** - -``` solidity -function granularity() external view returns (uint256) -``` - -Get the smallest part of the token that's not divisible. - -In other words, the granularity is the smallest amount of tokens (in the internal denomination) -which MAY be minted, sent or burned at any time. - -The following rules MUST be applied regarding the *granularity*: - -- The *granularity* value MUST be set at creation time. - -- The *granularity* value MUST NOT be changed, ever. - -- The *granularity* value MUST be greater than or equal to `1`. - -- All balances MUST be a multiple of the granularity. - -- Any amount of tokens (in the internal denomination) minted, sent or burned - MUST be a multiple of the *granularity* value. - -- Any operation that would result in a balance that's not a multiple of the *granularity* value - MUST be considered invalid, and the transaction MUST `revert`. - -*NOTE*: Most tokens SHOULD be fully partition-able. -I.e., this function SHOULD return `1` unless there is a good reason for not allowing any fraction of the token. - -> **identifier:** `556f0dc7` -> **returns:** The smallest non-divisible part of the token. - -*NOTE*: [`defaultOperators`][defaultOperators] and [`isOperatorFor`][isOperatorFor] are also `view` functions, -defined under the [operators] for consistency. - -*[ERC-20] compatibility requirement*: -The decimals of the token MUST always be `18`. -For a *pure* ERC777 token the [ERC-20] `decimals` function is OPTIONAL, -and its existence SHALL NOT be relied upon when interacting with the token contract. -(The decimal value of `18` is implied.) -For an [ERC-20] compatible token, the `decimals` function is REQUIRED and MUST return `18`. -(In [ERC-20], the `decimals` function is OPTIONAL. -If the function is not present, the `decimals` value is not clearly defined and may be assumed to be `0`. -Hence for compatibility reasons, `decimals` MUST be implemented for [ERC-20] compatible tokens.) - -#### **Operators** - -An `operator` is an address which is allowed to send and burn tokens on behalf of some *holder*. - -When an address becomes an *operator* for a *holder*, an `AuthorizedOperator` event MUST be emitted. -The `AuthorizedOperator`'s `operator` (topic 1) and `holder` (topic 2) -MUST be the addresses of the *operator* and the *holder* respectively. - -When a *holder* revokes an *operator*, a `RevokedOperator` event MUST be emitted. -The `RevokedOperator`'s `operator` (topic 1) and `holder` (topic 2) -MUST be the addresses of the *operator* and the *holder* respectively. - -*NOTE*: A *holder* MAY have multiple *operators* at the same time. - -The token MAY define *default operators*. -A *default operator* is an implicitly authorized *operator* for all *holders*. -`AuthorizedOperator` events MUST NOT be emitted when defining the *default operators*. -The rules below apply to *default operators*: - -- The token contract MUST define *default operators* at creation time. - -- The *default operators* MUST be invariants. I.e., the token contract MUST NOT add or remove *default operators* ever. - -- `AuthorizedOperator` events MUST NOT be emitted when defining *default operators*. - -- A *holder* MUST be allowed to revoke a *default operator* - (unless the *holder* is the *default operator* in question). - -- A *holder* MUST be allowed to re-authorize a previously revoked *default operator*. - -- When a *default operator* is explicitly authorized or revoked for a specific *holder*, - an `AuthorizedOperator` or `RevokedOperator` event (respectively) MUST be emitted. - -The following rules apply to any *operator*: - -- An address MUST always be an *operator* for itself. Hence an address MUST NOT ever be revoked as its own *operator*. - -- If an address is an *operator* for a *holder*, `isOperatorFor` MUST return `true`. - -- If an address is not an *operator* for a *holder*, `isOperatorFor` MUST return `false`. - -- The token contract MUST emit an `AuthorizedOperator` event with the correct values - when a *holder* authorizes an address as its *operator* as defined in the - [`AuthorizedOperator` Event][authorizedoperator]. - -- The token contract MUST emit a `RevokedOperator` event with the correct values - when a *holder* revokes an address as its *operator* as defined in the - [`RevokedOperator` Event][revokedoperator]. - -*NOTE*: A *holder* MAY authorize an already authorized *operator*. -An `AuthorizedOperator` MUST be emitted each time. - -*NOTE*: A *holder* MAY revoke an already revoked *operator*. -A `RevokedOperator` MUST be emitted each time. - -**`AuthorizedOperator` event** - -``` solidity -event AuthorizedOperator(address indexed operator, address indexed holder) -``` - -Indicates the authorization of `operator` as an *operator* for `holder`. - -*NOTE*: This event MUST NOT be emitted outside of an *operator* authorization process. - -> **parameters** -> `operator`: Address which became an *operator* of `holder`. -> `holder`: Address of a *holder* which authorized the `operator` address as an *operator*. - -**`RevokedOperator` event** - -``` solidity -event RevokedOperator(address indexed operator, address indexed holder) -``` - -Indicates the revocation of `operator` as an *operator* for `holder`. - -*NOTE*: This event MUST NOT be emitted outside of an *operator* revocation process. - -> **parameters** -> `operator`: Address which was revoked as an *operator* of `holder`. -> `holder`: Address of a *holder* which revoked the `operator` address as an *operator*. - -The `defaultOperators`, `authorizeOperator`, `revokeOperator` and `isOperatorFor` functions described below -MUST be implemented to manage *operators*. -Token contracts MAY implement other functions to manage *operators*. - -**`defaultOperators` function** - -``` solidity -function defaultOperators() external view returns (address[] memory) -``` - -Get the list of *default operators* as defined by the token contract. - -*NOTE*: If the token contract does not have any *default operators*, this function MUST return an empty list. - -> **identifier:** `06e48538` -> **returns:** List of addresses of all the *default operators*. - -**`authorizeOperator` function** - -``` solidity -function authorizeOperator(address operator) external -``` - -Set a third party `operator` address as an *operator* of `msg.sender` to send and burn tokens on its behalf. - -*NOTE*: The *holder* (`msg.sender`) is always an *operator* for itself. -This right SHALL NOT be revoked. -Hence this function MUST `revert` if it is called to authorize the holder (`msg.sender`) -as an *operator* for itself (i.e. if `operator` is equal to `msg.sender`). - -> **identifier:** `959b8c3f` -> **parameters** -> `operator`: Address to set as an *operator* for `msg.sender`. - -**`revokeOperator` function** - -``` solidity -function revokeOperator(address operator) external -``` - -Remove the right of the `operator` address to be an *operator* for `msg.sender` -and to send and burn tokens on its behalf. - -*NOTE*: The *holder* (`msg.sender`) is always an *operator* for itself. -This right SHALL NOT be revoked. -Hence this function MUST `revert` if it is called to revoke the holder (`msg.sender`) -as an *operator* for itself (i.e., if `operator` is equal to `msg.sender`). - -> **identifier:** `fad8b32a` -> **parameters** -> `operator`: Address to rescind as an *operator* for `msg.sender`. - -**`isOperatorFor` function** - -``` solidity -function isOperatorFor( - address operator, - address holder -) external view returns (bool) -``` - -Indicate whether the `operator` address is an *operator* of the `holder` address. - -> **identifier:** `d95b6371` -> **parameters** -> `operator`: Address which may be an *operator* of `holder`. -> `holder`: Address of a *holder* which may have the `operator` address as an *operator*. -> -> **returns:** `true` if `operator` is an *operator* of `holder` and `false` otherwise. - -*NOTE*: To know which addresses are *operators* for a given *holder*, -one MUST call `isOperatorFor` with the *holder* for each *default operator* -and parse the `AuthorizedOperator`, and `RevokedOperator` events for the *holder* in question. - -#### **Sending Tokens** - -When an *operator* sends an `amount` of tokens from a *holder* to a *recipient* -with the associated `data` and `operatorData`, the token contract MUST apply the following rules: - -- Any authorized *operator* MAY send tokens to any *recipient* (except to `0x0`). - -- The balance of the *holder* MUST be decreased by the `amount`. - -- The balance of the *recipient* MUST be increased by the `amount`. - -- The balance of the *holder* MUST be greater or equal to the `amount`—such - that its resulting balance is greater or equal to zero (`0`) after the send. - -- The token contract MUST emit a `Sent` event with the correct values as defined in the [`Sent` Event][sent]. - -- The *operator* MAY include information in the `operatorData`. - -- The token contract MUST call the `tokensToSend` hook of the *holder* - if the *holder* registers an `ERC777TokensSender` implementation via [ERC-1820]. - -- The token contract MUST call the `tokensReceived` hook of the *recipient* - if the *recipient* registers an `ERC777TokensRecipient` implementation via [ERC-1820]. - -- The `data` and `operatorData` MUST be immutable during the entire send process—hence - the same `data` and `operatorData` MUST be used to call both hooks and emit the `Sent` event. - -The token contract MUST `revert` when sending in any of the following cases: - -- The *operator* address is not an authorized operator for the *holder*. - -- The resulting *holder* balance or *recipient* balance after the send - is not a multiple of the *granularity* defined by the token contract. - -- The *recipient* is a contract, and it does not implement the `ERC777TokensRecipient` interface via [ERC-1820]. - -- The address of the *holder* or the *recipient* is `0x0`. - -- Any of the resulting balances becomes negative, i.e. becomes less than zero (`0`). - -- The `tokensToSend` hook of the *holder* `revert`s. - -- The `tokensReceived` hook of the *recipient* `revert`s. - -The token contract MAY send tokens from many *holders*, to many *recipients*, or both. In this case: - -- The previous send rules MUST apply to all the *holders* and all the *recipients*. -- The sum of all the balances incremented MUST be equal to the total sent `amount`. -- The sum of all the balances decremented MUST be equal to the total sent `amount`. -- A `Sent` event MUST be emitted for every *holder* and *recipient* pair with the corresponding amount for each pair. -- The sum of all the amounts from the `Sent` event MUST be equal to the total sent `amount`. - -*NOTE*: Mechanisms such as applying a fee on a send is considered as a send to multiple *recipients*: -the intended *recipient* and the fee *recipient*. - -*NOTE*: Movements of tokens MAY be chained. -For example, if a contract upon receiving tokens sends them further to another address. -In this case, the previous send rules apply to each send, in order. - -*NOTE*: Sending an amount of zero (`0`) tokens is valid and MUST be treated as a regular send. - -*Implementation Requirement*: -- The token contract MUST call the `tokensToSend` hook *before* updating the state. -- The token contract MUST call the `tokensReceived` hook *after* updating the state. -I.e., `tokensToSend` MUST be called first, -then the balances MUST be updated to reflect the send, -and finally `tokensReceived` MUST be called *afterward*. -Thus a `balanceOf` call within `tokensToSend` returns the balance of the address *before* the send -and a `balanceOf` call within `tokensReceived` returns the balance of the address *after* the send. - -*NOTE*: The `data` field contains information provided by the *holder*—similar -to the data field in a regular ether send transaction. -The `tokensToSend()` hook, the `tokensReceived()`, or both -MAY use the information to decide if they wish to reject the transaction. - -*NOTE*: The `operatorData` field is analogous to the `data` field except it SHALL be provided by the *operator*. - -The `operatorData` MUST only be provided by the *operator*. -It is intended more for logging purposes and particular cases. -(Examples include payment references, cheque numbers, countersignatures and more.) -In most of the cases the recipient would ignore the `operatorData`, or at most, it would log the `operatorData`. - -**`Sent` event** - -``` solidity -event Sent( - address indexed operator, - address indexed from, - address indexed to, - uint256 amount, - bytes data, - bytes operatorData -) -``` - -Indicate a send of `amount` of tokens from the `from` address to the `to` address by the `operator` address. - -*NOTE*: This event MUST NOT be emitted outside of a send or an [ERC-20] transfer process. - -> **parameters** -> `operator`: Address which triggered the send. -> `from`: *Holder* whose tokens were sent. -> `to`: Recipient of the tokens. -> `amount`: Number of tokens sent. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -The `send` and `operatorSend` functions described below MUST be implemented to send tokens. -Token contracts MAY implement other functions to send tokens. - -**`send` function** - -``` solidity -function send(address to, uint256 amount, bytes calldata data) external -``` - -Send the `amount` of tokens from the address `msg.sender` to the address `to`. - -The *operator* and the *holder* MUST both be the `msg.sender`. - -> **identifier:** `9bd9bbc6` -> **parameters** -> `to`: Recipient of the tokens. -> `amount`: Number of tokens to send. -> `data`: Information provided by the *holder*. - -**`operatorSend` function** - -``` solidity -function operatorSend( - address from, - address to, - uint256 amount, - bytes calldata data, - bytes calldata operatorData -) external -``` - -Send the `amount` of tokens on behalf of the address `from` to the address `to`. - -*Reminder*: If the *operator* address is not an authorized operator of the `from` address, -then the send process MUST `revert`. - -*NOTE*: `from` and `msg.sender` MAY be the same address. -I.e., an address MAY call `operatorSend` for itself. -This call MUST be equivalent to `send` with the addition -that the *operator* MAY specify an explicit value for `operatorData` -(which cannot be done with the `send` function). - -> **identifier:** `62ad1b83` -> **parameters** -> `from`: *Holder* whose tokens are being sent. -> `to`: Recipient of the tokens. -> `amount`: Number of tokens to send. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -#### **Minting Tokens** - -Minting tokens is the act of producing new tokens. -[ERC-777] intentionally does not define specific functions to mint tokens. -This intent comes from the wish not to limit the use of the [ERC-777] standard -as the minting process is generally specific for every token. - -Nonetheless, the rules below MUST be respected when minting for a *recipient*: - -- Tokens MAY be minted for any *recipient* address (except `0x0`). - -- The total supply MUST be increased by the amount of tokens minted. - -- The balance of `0x0` MUST NOT be decreased. - -- The balance of the *recipient* MUST be increased by the amount of tokens minted. - -- The token contract MUST emit a `Minted` event with the correct values as defined in the [`Minted` Event][minted]. - -- The token contract MUST call the `tokensReceived` hook of the *recipient* - if the *recipient* registers an `ERC777TokensRecipient` implementation via [ERC-1820]. - -- The `data` and `operatorData` MUST be immutable during the entire mint process—hence - the same `data` and `operatorData` MUST be used to call the `tokensReceived` hook and emit the `Minted` event. - -The token contract MUST `revert` when minting in any of the following cases: - -- The resulting *recipient* balance after the mint is not a multiple of the *granularity* defined by the token contract. -- The *recipient* is a contract, and it does not implement the `ERC777TokensRecipient` interface via [ERC-1820]. -- The address of the *recipient* is `0x0`. -- The `tokensReceived` hook of the *recipient* `revert`s. - -*NOTE*: The initial token supply at the creation of the token contract MUST be considered as minting -for the amount of the initial supply to the address(es) receiving the initial supply. -This means one or more `Minted` events must be emitted -and the `tokensReceived` hook of the recipient(s) MUST be called. - -*[ERC-20] compatibility requirement*: -While a `Sent` event MUST NOT be emitted when minting, -if the token contract is [ERC-20] backward compatible, -a `Transfer` event with the `from` parameter set to `0x0` SHOULD be emitted as defined in the [ERC-20] standard. - -The token contract MAY mint tokens for multiple *recipients* at once. In this case: - -- The previous mint rules MUST apply to all the *recipients*. -- The sum of all the balances incremented MUST be equal to the total minted amount. -- A `Minted` event MUST be emitted for every *recipient* with the corresponding amount for each *recipient*. -- The sum of all the amounts from the `Minted` event MUST be equal to the total minted `amount`. - -*NOTE*: Minting an amount of zero (`0`) tokens is valid and MUST be treated as a regular mint. - -*NOTE*: While during a send or a burn, the data is provided by the *holder*, it is inapplicable for a mint. -In this case the data MAY be provided by the token contract or the *operator*, -for example to ensure a successful minting to a *holder* expecting specific data. - -*NOTE*: The `operatorData` field contains information provided by the *operator*—similar -to the data field in a regular ether send transaction. -The `tokensReceived()` hooks MAY use the information to decide if it wish to reject the transaction. - -**`Minted` event** - -``` solidity -event Minted( - address indexed operator, - address indexed to, - uint256 amount, - bytes data, - bytes operatorData -) -``` - -Indicate the minting of `amount` of tokens to the `to` address by the `operator` address. - -*NOTE*: This event MUST NOT be emitted outside of a mint process. - -> **parameters** -> `operator`: Address which triggered the mint. -> `to`: Recipient of the tokens. -> `amount`: Number of tokens minted. -> `data`: Information provided for the *recipient*. -> `operatorData`: Information provided by the *operator*. - -#### **Burning Tokens** - -Burning tokens is the act of destroying existing tokens. -[ERC-777] explicitly defines two functions to burn tokens (`burn` and `operatorBurn`). -These functions facilitate the integration of the burning process in wallets and dapps. -However, the token contract MAY prevent some or all *holders* from burning tokens for any reason. -The token contract MAY also define other functions to burn tokens. - -The rules below MUST be respected when burning the tokens of a *holder*: - -- Tokens MAY be burned from any *holder* address (except `0x0`). - -- The total supply MUST be decreased by the amount of tokens burned. - -- The balance of `0x0` MUST NOT be increased. - -- The balance of the *holder* MUST be decreased by amount of tokens burned. - -- The token contract MUST emit a `Burned` event with the correct values as defined in the [`Burned` Event][burned]. - -- The token contract MUST call the `tokensToSend` hook of the *holder* - if the *holder* registers an `ERC777TokensSender` implementation via [ERC-1820]. - -- The `operatorData` MUST be immutable during the entire burn process—hence - the same `operatorData` MUST be used to call the `tokensToSend` hook and emit the `Burned` event. - -The token contract MUST `revert` when burning in any of the following cases: - -- The *operator* address is not an authorized operator for the *holder*. - -- The resulting *holder* balance after the burn is not a multiple of the *granularity* - defined by the token contract. - -- The balance of *holder* is inferior to the amount of tokens to burn - (i.e., resulting in a negative balance for the *holder*). - -- The address of the *holder* is `0x0`. - -- The `tokensToSend` hook of the *holder* `revert`s. - -*[ERC-20] compatibility requirement*: -While a `Sent` event MUST NOT be emitted when burning; -if the token contract is [ERC-20] enabled, a `Transfer` event with the `to` parameter set to `0x0` SHOULD be emitted. -The [ERC-20] standard does not define the concept of burning tokens, but this is a commonly accepted practice. - -The token contract MAY burn tokens for multiple *holders* at once. In this case: - -- The previous burn rules MUST apply to each *holders*. -- The sum of all the balances decremented MUST be equal to the total burned amount. -- A `Burned` event MUST be emitted for every *holder* with the corresponding amount for each *holder*. -- The sum of all the amounts from the `Burned` event MUST be equal to the total burned `amount`. - -*NOTE*: Burning an amount of zero (`0`) tokens is valid and MUST be treated as a regular burn. - -*NOTE*: The `data` field contains information provided by the holder—similar -to the data field in a regular ether send transaction. -The `tokensToSend()` hook, the `tokensReceived()`, or both -MAY use the information to decide if they wish to reject the transaction. - -*NOTE*: The `operatorData` field is analogous to the `data` field except it SHALL be provided by the *operator*. - -**`Burned` event** - -``` solidity -event Burned( - ddress indexed operator, - address indexed from, - uint256 amount, - bytes data, - bytes operatorData -); -``` - -Indicate the burning of `amount` of tokens from the `from` address by the `operator` address. - -*NOTE*: This event MUST NOT be emitted outside of a burn process. - -> **parameters** -> `operator`: Address which triggered the burn. -> `from`: *Holder* whose tokens were burned. -> `amount`: Number of tokens burned. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -The `burn` and `operatorBurn` functions described below MUST be implemented to burn tokens. -Token contracts MAY implement other functions to burn tokens. - -**`burn` function** - -``` solidity -function burn(uint256 amount, bytes calldata data) external -``` - -Burn the `amount` of tokens from the address `msg.sender`. - -The *operator* and the *holder* MUST both be the `msg.sender`. - -> **identifier:** `fe9d9303` -> **parameters** -> `amount`: Number of tokens to burn. -> `data`: Information provided by the *holder*. - -**`operatorBurn` function** - -``` solidity -function operatorBurn( - address from, - uint256 amount, - bytes calldata data, - bytes calldata operatorData -) external -``` - -Burn the `amount` of tokens on behalf of the address `from`. - -*Reminder*: If the *operator* address is not an authorized operator of the `from` address, -then the burn process MUST `revert`. - -> **identifier:** `fc673c4f` -> **parameters** -> `from`: *Holder* whose tokens will be burned. -> `amount`: Number of tokens to burn. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -*NOTE*: The *operator* MAY pass any information via `operatorData`. -The `operatorData` MUST only be provided by the *operator*. - -*NOTE*: `from` and `msg.sender` MAY be the same address. -I.e., an address MAY call `operatorBurn` for itself. -This call MUST be equivalent to `burn` -with the addition that the *operator* MAY specify an explicit value for `operatorData` -(which cannot be done with the `burn` function). - -#### **`ERC777TokensSender` And The `tokensToSend` Hook** - -The `tokensToSend` hook notifies of any request to decrement the balance (send and burn) for a given *holder*. -Any address (regular or contract) wishing to be notified of token debits from their address -MAY register the address of a contract implementing the `ERC777TokensSender` interface described below via [ERC-1820]. - -> This is done by calling the `setInterfaceImplementer` function on the [ERC-1820] registry -> with the *holder* address as the address, -> the `keccak256` hash of `ERC777TokensSender` -> (`0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895`) as the interface hash, -> and the address of the contract implementing the `ERC777TokensSender` as the implementer. - -``` solidity -interface ERC777TokensSender { - function tokensToSend( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData - ) external; -} -``` - -*NOTE*: A regular address MAY register a different address—the address of a contract—implementing -the interface on its behalf. -A contract MAY register either its address or the address of another contract -but said address MUST implement the interface on its behalf. - -**`tokensToSend`** - -``` solidity -function tokensToSend( - address operator, - address from, - address to, - uint256 amount, - bytes calldata userData, - bytes calldata operatorData -) external -``` - -Notify a request to send or burn (if `to` is `0x0`) an `amount` tokens from the `from` address to the `to` address -by the `operator` address. - -*NOTE*: This function MUST NOT be called outside of a burn, send or [ERC-20] transfer process. - -> **identifier:** `75ab9782` -> **parameters** -> `operator`: Address which triggered the balance decrease (through sending or burning). -> `from`: *Holder* whose tokens were sent. -> `to`: Recipient of the tokens for a send (or `0x0` for a burn). -> `amount`: Number of tokens the *holder* balance is decreased by. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -The following rules apply when calling the `tokensToSend` hook: - -- The `tokensToSend` hook MUST be called for every send and burn processes. - -- The `tokensToSend` hook MUST be called *before* the state is updated—i.e. *before* the balance is decremented. - -- `operator` MUST be the address which triggered the send or burn process. - -- `from` MUST be the address of the *holder* whose tokens are sent or burned. - -- `to` MUST be the address of the *recipient* which receives the tokens for a send. - -- `to` MUST be `0x0` for a burn. - -- `amount` MUST be the number of tokens the *holder* sent or burned. - -- `data` MUST contain the extra information (if any) provided to the send or the burn process. - -- `operatorData` MUST contain the extra information provided by the address - which triggered the decrease of the balance (if any). - -- The *holder* MAY block a send or burn process by `revert`ing. - (I.e., reject the withdrawal of tokens from its account.) - -*NOTE*: Multiple *holders* MAY use the same implementation of `ERC777TokensSender`. - -*NOTE*: An address can register at most one implementation at any given time for all [ERC-777] tokens. -Hence the `ERC777TokensSender` MUST expect to be called by different token contracts. -The `msg.sender` of the `tokensToSend` call is expected to be the address of the token contract. - -*[ERC-20] compatibility requirement*: -This hook takes precedence over [ERC-20] and MUST be called (if registered) -when calling [ERC-20]'s `transfer` and `transferFrom` event. -When called from a `transfer`, `operator` MUST be the same value as the `from`. -When called from a `transferFrom`, `operator` MUST be the address which issued the `transferFrom` call. - -#### **`ERC777TokensRecipient` And The `tokensReceived` Hook** - -The `tokensReceived` hook notifies of any increment of the balance (send and mint) for a given *recipient*. -Any address (regular or contract) wishing to be notified of token credits to their address -MAY register the address of a contract implementing the `ERC777TokensRecipient` interface described below via [ERC-1820]. - -> This is done by calling the `setInterfaceImplementer` function on the [ERC-1820] registry -> with the *recipient* address as the address, -> the `keccak256` hash of `ERC777TokensRecipient` -> (`0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b`) as the interface hash, -> and the address of the contract implementing the `ERC777TokensRecipient` as the implementer. - -``` solidity -interface ERC777TokensRecipient { - function tokensReceived( - address operator, - address from, - address to, - uint256 amount, - bytes calldata data, - bytes calldata operatorData - ) external; -} -``` - -If the *recipient* is a contract, which has not registered an `ERC777TokensRecipient` implementation; -then the token contract: - -- MUST `revert` if the `tokensReceived` hook is called from a mint or send call. - -- SHOULD continue processing the transaction - if the `tokensReceived` hook is called from an ERC20 `transfer` or `transferFrom` call. - -*NOTE*: A regular address MAY register a different address—the address of a contract—implementing -the interface on its behalf. -A contract MUST register either its address or the address of another contract -but said address MUST implement the interface on its behalf. - -**`tokensReceived`** - -``` solidity -function tokensReceived( - address operator, - address from, - address to, - uint256 amount, - bytes calldata data, - bytes calldata operatorData -) external -``` - -Notify a send or mint (if `from` is `0x0`) of `amount` tokens from the `from` address to the `to` address -by the `operator` address. - -*NOTE*: This function MUST NOT be called outside of a mint, send or [ERC-20] transfer process. - -> **identifier:** `0023de29` -> **parameters** -> `operator`: Address which triggered the balance increase (through sending or minting). -> `from`: *Holder* whose tokens were sent (or `0x0` for a mint). -> `to`: Recipient of the tokens. -> `amount`: Number of tokens the *recipient* balance is increased by. -> `data`: Information provided by the *holder*. -> `operatorData`: Information provided by the *operator*. - -The following rules apply when calling the `tokensReceived` hook: - -- The `tokensReceived` hook MUST be called for every send and mint processes. - -- The `tokensReceived` hook MUST be called *after* the state is updated—i.e. *after* the balance is incremented. - -- `operator` MUST be the address which triggered the send or mint process. - -- `from` MUST be the address of the *holder* whose tokens are sent for a send. - -- `from` MUST be `0x0` for a mint. - -- `to` MUST be the address of the *recipient* which receives the tokens. - -- `amount` MUST be the number of tokens the *recipient* sent or minted. - -- `data` MUST contain the extra information (if any) provided to the send or the mint process. - -- `operatorData` MUST contain the extra information provided by the address - which triggered the increase of the balance (if any). - -- The *holder* MAY block a send or mint process by `revert`ing. - (I.e., reject the reception of tokens.) - -*NOTE*: Multiple *holders* MAY use the same implementation of `ERC777TokensRecipient`. - -*NOTE*: An address can register at most one implementation at any given time for all [ERC-777] tokens. -Hence the `ERC777TokensRecipient` MUST expect to be called by different token contracts. -The `msg.sender` of the `tokensReceived` call is expected to be the address of the token contract. - -*[ERC-20] compatibility requirement*: -This hook takes precedence over [ERC-20] and MUST be called (if registered) -when calling [ERC-20]'s `transfer` and `transferFrom` event. -When called from a `transfer`, `operator` MUST be the same value as the `from`. -When called from a `transferFrom`, `operator` MUST be the address which issued the `transferFrom` call. - -#### **Note On Gas Consumption** - -Dapps and wallets SHOULD first estimate the gas required when sending, minting, or burning tokens—using -[`eth_estimateGas`][eth_estimateGas]—to avoid running out of gas during the transaction. - -### Logo - -| **Image** | ![beige logo] | ![white logo] | ![light grey logo] | ![dark grey logo] | ![black logo] | -|----------:|:-------------:|:-------------:|:------------------:|:-----------------:|:-------------:| -| **Color** | beige | white | light grey | dark grey | black | -| **Hex** | `#C99D66` | `#FFFFFF` | `#EBEFF0` | `#3C3C3D` | `#000000` | - -The logo MAY be used, modified and adapted to promote valid [ERC-777] token implementations -and [ERC-777] compliant technologies such as wallets and dapps. - -[ERC-777] token contract authors MAY create a specific logo for their token based on this logo. - -The logo MUST NOT be used to advertise, promote or associate in any way technology—such -as tokens—which is not [ERC-777] compliant. - -The logo for the standard can be found in the [`/assets/eip-777/logo`][logos] folder in `SVG` and `PNG` formats. -The `PNG` version of the logo offers a few sizes in pixels. -If needed, other sizes MAY be created by converting from `SVG` into `PNG`. - -## Rationale - -The principal intent for this standard is -to solve some of the shortcomings of [ERC-20] while maintaining backward compatibility with [ERC-20], -and avoiding the problems and vulnerabilities of [EIP-223]. - -Below are the rationales for the decisions regarding the main aspects of the standards. - -*NOTE*: Jacques Dafflon ([0xjac]), one of the authors of the standard, -conjointly wrote his [master thesis] on the standard, -which goes in more details than could reasonably fit directly within the standard, -and can provide further clarifications regarding certain aspects or decisions. - -### Lifecycle - -More than just sending tokens, [ERC-777] defines the entire lifecycle of a token, -starting with the minting process, followed by the sending process and terminating with the burn process. - -Having a lifecycle clearly defined is important for consistency and accuracy, -especially when value is derived from scarcity. -In contrast when looking at some [ERC-20] tokens, a discrepancy can be observed -between the value returned by the `totalSupply` and the actual circulating supply, -as the standard does not clearly define a process to create and destroy tokens. - -### Data - -The mint, send and burn processes can all make use of a `data` and `operatorData` fields -which are passed to any movement (mint, send or burn). -Those fields may be empty for simple use cases, -or they may contain valuable information related to the movement of tokens, -similar to information attached to a bank transfer by the sender or the bank itself. - -The use of a `data` field is equally present in other standard proposals such as [EIP-223], -and was requested by multiple members of the community who reviewed this standard. - -### Hooks - -In most cases, [ERC-20] requires two calls to safely transfer tokens to a contract without locking them. -A call from the sender, using the `approve` function -and a call from the recipient using `transferFrom`. -Furthermore, this requires extra communication between the parties which is not clearly defined. -Finally, holders can get confused between `transfer` and `approve`/`transferFrom`. -Using the former to transfer tokens to a contract will most likely result in locked tokens. - -Hooks allow streamlining of the sending process and offer a single way to send tokens to any recipient. -Thanks to the `tokensReceived` hook, contracts are able to react and prevent locking tokens upon reception. - -#### **Greater Control For Holders** - -The `tokensReceived` hook also allows holders to reject the reception of some tokens. -This gives greater control to holders who can accept or reject incoming tokens based on some parameters, -for example located in the `data` or `operatorData` fields. - -Following the same intentions and based on suggestions from the community, -the `tokensToSend` hook was added to give control over and prevent the movement of outgoing tokens. - -#### **[ERC-1820] Registry** - -The [ERC-1820] Registry allows holders to register their hooks. -Other alternatives were examined beforehand to link hooks and holders. - -The first was for hooks to be defined at the sender's or recipient's address. -This approach is similar to [EIP-223] which proposes a `tokenFallback` function on recipient contracts -to be called when receiving tokens, -but improves on it by relying on [ERC-165] for interface detection. -While straightforward to implement, this approach imposes several limitations. -In particular, the sender and recipient must be contracts in order to provide their implementation of the hooks. -Preventing externally owned addresses to benefit from hooks. -Existing contracts have a strong probability not to be compatible, -as they undoubtedly were unaware and do not define the new hooks. -Consequently existing smart contract infrastructure such as multisig wallets -which potentially hold large amounts of ether and tokens would need to be migrated to new updated contracts. - -The second approach considered was to use [ERC-672] which offered pseudo-introspection for addresses using reverse-ENS. -However, this approach relied heavily on ENS, on top of which reverse lookup would need to be implemented. -Analysis of this approach promptly revealed a certain degree of complexity and security concerns -which would transcend the benefits of approach. - -The third solution—used in this standard—is to rely on a unique registry -where any address can register the addresses of contracts implementing the hooks on its behalf. -This approach has the advantage that externally owned accounts and contracts can benefit from hooks, -including existing contracts which can rely on hooks deployed on proxy contracts. - -The decision was made to keep this registry in a separate EIP, -as to not over complicate this standard. -More importantly, the registry is designed in a flexible fashion, -such that other EIPs and smart contract infrastructures can benefit from it -for their own use cases, outside the realm of [ERC-777] and tokens. -The first proposal for this registry was [ERC-820]. -Unfortunately, issues emanating from upgrades in the Solidity language to versions 0.5 and above -resulted in a bug in a separated part of the registry, which required changes. -This was discovered right after the last call period. -Attempts made to avoid creating a separate EIP, such as [ERC820a], were rejected. -Hence the standard for the registry used for [ERC-777] became [ERC-1820]. -[ERC-1820] and [ERC-820] are functionally equivalent. [ERC-1820] simply contains the fix for newer versions of Solidity. - -### Operators - -The standard defines the concept of operators as any address which moves tokens. -While intuitively every address moves its own tokens, -separating the concepts of holder and operator allows for greater flexibility. -Primarily, this originates from the fact that the standard defines a mechanism for holders -to let other addresses become their operators. -Moreover, unlike the approve calls in [ERC-20] where the role of an approved address is not clearly defined, -[ERC-777] details the intent of and interactions with operators, -including an obligation for operators to be approved, -and an irrevocable right for any holder to revoke operators. - -#### **Default Operators** - -Default operators were added based on community demand for pre-approved operators. -That is operators which are approved for all holders by default. -For obvious security reasons, the list of default operators is defined at the token contract creation time, -and cannot be changed. -Any holder still has the right to revoke default operators. -One of the obvious advantages of default operators is to allow ether-less movements of tokens. -Default operators offer other usability advantages, -such as allowing token providers to offer functionality in a modular way, -and to reduce the complexity for holders to use features provided through operators. - -## Backward Compatibility - -This EIP does not introduce backward incompatibilities and is backward compatible with the older [ERC-20] token standard. - -This EIP does not use `transfer` and `transferFrom` and uses `send` and `operatorSend` -to avoid confusion and mistakes when deciphering which token standard is being used. - -This standard allows the implementation of [ERC-20] functions `transfer`, `transferFrom`, `approve` and `allowance` -alongside to make a token fully compatible with [ERC-20]. - -The token MAY implement `decimals()` for backward compatibility with [ERC-20]. -If implemented, it MUST always return `18`. - -Therefore a token contract MAY implement both [ERC-20] and [ERC-777] in parallel. -The specification of the `view` functions (such as `name`, `symbol`, `balanceOf`, `totalSupply`) and internal data -(such as the mapping of balances) overlap without problems. -Note however that the following functions are mandatory in [ERC-777] and MUST be implemented: -`name`, `symbol` `balanceOf` and `totalSupply` -(`decimals` is not part of the [ERC-777] standard). - -The state-modifying functions from both standards are decoupled and can operate independently from each other. -Note that [ERC-20] functions SHOULD be limited to only being called from old contracts. - -If the token implements [ERC-20], -it MUST register the `ERC20Token` interface with its own address via [ERC-1820]. -This is done by calling the `setInterfaceImplementer` function on the ERC1820 registry -with the token contract address as both the address and the implementer -and the `keccak256` hash of `ERC20Token` (`0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a`) -as the interface hash. - -If the contract has a switch to enable or disable ERC20 functions, every time the switch is triggered, -the token MUST register or unregister the `ERC20Token` interface for its own address accordingly via ERC1820. -Unregistering implies calling the `setInterfaceImplementer` with the token contract address as the address, -the `keccak256` hash of `ERC20Token` as the interface hash and `0x0` as the implementer. -(See [Set An Interface For An Address][erc1820-set] in [ERC-1820] for more details.) - -The difference for new contracts implementing [ERC-20] is that -`tokensToSend` and `tokensReceived` hooks take precedence over [ERC-20]. -Even with an [ERC-20] `transfer` and `transferFrom` call, the token contract MUST check via [ERC-1820] -if the `from` and the `to` address implement `tokensToSend` and `tokensReceived` hook respectively. -If any hook is implemented, it MUST be called. -Note that when calling [ERC-20] `transfer` on a contract, if the contract does not implement `tokensReceived`, -the `transfer` call SHOULD still be accepted even if this means the tokens will probably be locked. - -The table below summarizes the different actions the token contract MUST take -when sending, minting and transferring token via [ERC-777] and [ERC-20]: - - - - - - - - - - - - - - - - - - - - - - - - - - -
ERC1820to addressERC777 Sending And MintingERC20 transfer/transferFrom
- ERC777TokensRecipient
registered -
regular address - MUST call tokensReceived -
contract
- ERC777TokensRecipient
not registered -
regular addresscontinue
contractMUST revertSHOULD continue1
- -> 1. -> The transaction SHOULD continue for clarity as ERC20 is not aware of hooks. -> However, this can result in accidentally locked tokens. -> If avoiding accidentally locked tokens is paramount, the transaction MAY revert. - - -There is no particular action to take if `tokensToSend` is not implemented. -The movement MUST proceed and only be canceled if another condition is not respected -such as lack of funds or a `revert` in `tokensReceived` (if present). - -During a send, mint and burn, the respective `Sent`, `Minted` and `Burned` events MUST be emitted. -Furthermore, if the token contract declares that it implements `ERC20Token` via [ERC-1820], -the token contract SHOULD emit a `Transfer` event for minting and burning -and MUST emit a `Transfer` event for sending (as specified in the [ERC-20] standard). -During an [ERC-20]'s `transfer` or `transferFrom` functions, a valid `Sent` event MUST be emitted. - -Hence for any movement of tokens, two events MAY be emitted: -an [ERC-20] `Transfer` and an [ERC-777] `Sent`, `Minted` or `Burned` (depending on the type of movement). -Third-party developers MUST be careful not to consider both events as separate movements. -As a general rule, if an application considers the token as an ERC20 token, -then only the `Transfer` event MUST be taken into account. -If the application considers the token as an ERC777 token, -then only the `Sent`, `Minted` and `Burned` events MUST be considered. - -## Test Cases - -The [repository with the reference implementation][0xjac/ERC777] contains all the [tests][ref tests]. - -## Implementation - -The GitHub repository [0xjac/ERC777] contains the [reference implementation]. -The reference implementation is also available via [npm][npm/erc777] and can be installed with `npm install erc777`. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - -[operators]: #operators - -[ERC-20]: ./eip-20.md -[ERC-165]: ./eip-165.md -[ERC-672]: https://github.com/ethereum/EIPs/issues/672 -[ERC-777]: ./eip-777.md -[ERC-820]: ./eip-820.md -[ERC820a]: https://github.com/ethereum/EIPs/pull/1758 -[ERC-1820]: ./eip-1820.md -[erc1820-set]: ./eip-1820.md#set-an-interface-for-an-address -[0xjac]: https://github.com/0xjac -[0xjac/ERC777]: https://github.com/0xjac/ERC777 -[master thesis]: https://github.com/0xjac/master-thesis -[npm/erc777]: https://www.npmjs.com/package/erc777 -[ref tests]: https://github.com/0xjac/ERC777/blob/master/test/ReferenceToken.test.js -[reference implementation]: https://github.com/0xjac/ERC777/blob/master/contracts/examples/ReferenceToken.sol -[EIP-223]: https://github.com/ethereum/EIPs/issues/223 -[eth_estimateGas]: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas - -[authorizedoperator]: #authorizedoperator -[revokedoperator]: #revokedoperator -[isOperatorFor]: #isOperatorFor -[defaultOperators]: #defaultOperators -[sent]: #sent -[minted]: #minted -[burned]: #burned - -[logos]: https://github.com/ethereum/EIPs/tree/master/assets/eip-777/logo -[beige logo]: ../assets/eip-777/logo/png/ERC-777-logo-beige-48px.png -[white logo]: ../assets/eip-777/logo/png/ERC-777-logo-white-48px.png -[light grey logo]: ../assets/eip-777/logo/png/ERC-777-logo-light_grey-48px.png -[dark grey logo]: ../assets/eip-777/logo/png/ERC-777-logo-dark_grey-48px.png -[black logo]: ../assets/eip-777/logo/png/ERC-777-logo-black-48px.png +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-777.md diff --git a/EIPS/eip-801.md b/EIPS/eip-801.md index d0e979b27a9fc4..1a090874b3414b 100644 --- a/EIPS/eip-801.md +++ b/EIPS/eip-801.md @@ -1,78 +1,7 @@ --- eip: 801 -title: Canary Standard -author: ligi -type: Standards Track category: ERC -status: Stagnant -created: 2017-12-16 +status: Moved --- -## Simple Summary - -A standard interface for canary contracts. - -## Abstract - -The following standard allows the implementation of canaries within contracts. -This standard provides basic functionality to check if a canary is alive, keeping the canary alive and optionally manage feeders. - -## Motivation - -The canary can e.g. be used as a [warrant canary](https://en.wikipedia.org/wiki/Warrant_canary). -A standard interface allows other applications to easily interface with canaries on Ethereum - e.g. for visualizing the state, automated alarms, applications to feed the canary or contracts (e.g. insurance) that use the state. - -## Specification - -### Methods - -#### isAlive() - -Returns if the canary was fed properly to signal e.g. that no warrant was received. - -``` js -function isAlive() constant returns (bool alive) -``` - -#### getBlockOfDeath() - -Returns the block the canary died. -Throws if the canary is alive. - -``` js -function getBlockOfDeath() constant returns (uint256 block) -``` - -#### getType() - -Returns the type of the canary: - -* `1` = Simple (just the pure interface as defined in this ERC) -* `2` = Single feeder (as defined in ERC-TBD) -* `3` = Single feeder with bad food (as defined in ERC-TBD) -* `4` = Multiple feeders (as defined in ERC-TBD) -* `5` = Multiple mandatory feeders (as defined in ERC-TBD) -* `6` = IOT (as defined in ERC-TBD) - -`1` might also be used for a special purpose contract that does not need a special type but still wants to expose the functions and provide events as defined in this ERC. - -``` js -function getType() constant returns (uint8 type) -``` - -### Events - -#### RIP - -MUST trigger when the contract is called the first time after the canary died. - -``` js -event RIP() -``` - -## Implementation - -TODO - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-801.md diff --git a/EIPS/eip-820.md b/EIPS/eip-820.md index 2a4c69202ecf21..c1e16ee1ec4db7 100644 --- a/EIPS/eip-820.md +++ b/EIPS/eip-820.md @@ -1,902 +1,7 @@ --- eip: 820 -title: Pseudo-introspection Registry Contract -author: Jordi Baylina , Jacques Dafflon -discussions-to: https://github.com/ethereum/EIPs/issues/820 -status: Final -type: Standards Track category: ERC -requires: 165, 214 -created: 2018-01-05 +status: Moved --- -> :information_source: **[ERC-1820] has superseded [ERC-820].** :information_source: -> [ERC-1820] fixes the incompatibility in the [ERC-165] logic which was introduced by the Solidty 0.5 update. -> Have a look at the [official announcement][erc1820-annoucement], and the comments about the [bug][erc820-bug] and the [fix][erc820-fix]. -> Apart from this fix, [ERC-1820] is functionally equivalent to [ERC-820]. -> -> :warning: [ERC-1820] MUST be used in lieu of [ERC-820]. :warning: - - -## Simple Summary - -This standard defines a universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. - -This standard keeps backward compatibility with [ERC-165]. - -## Abstract - -This standard defines a registry where smart contracts and regular accounts can publish which functionalities they implement---either directly or through a proxy contract. - -Anyone can query this registry to ask if a specific address implements a given interface and which smart contract handles its implementation. - -This registry MAY be deployed on any chain and shares the same address on all chains. - -Interfaces with zeroes (`0`) as the last 28 bytes are considered [ERC-165] interfaces, and this registry SHALL forward the call to the contract to see if it implements the interface. - -This contract also acts as an [ERC-165] cache to reduce gas consumption. - -## Motivation - -There have been different approaches to define pseudo-introspection in Ethereum. The first is [ERC-165] which has the limitation that it cannot be used by regular accounts. The second attempt is [ERC-672] which uses reverse [ENS]. Using reverse [ENS] has two issues. First, it is unnecessarily complicated, and second, [ENS] is still a centralized contract controlled by a multisig. This multisig theoretically would be able to modify the system. - -This standard is much simpler than [ERC-672], and it is *fully* decentralized. - -This standard also provides a *unique* address for all chains. Thus solving the problem of resolving the correct registry address for different chains. - -## Specification - -### [ERC-820] Registry Smart Contract - -> This is an exact copy of the code of the [ERC820 registry smart contract]. - -``` solidity -/* ERC820 Pseudo-introspection Registry Contract - * This standard defines a universal registry smart contract where any address - * (contract or regular account) can register which interface it supports and - * which smart contract is responsible for its implementation. - * - * Written in 2018 by Jordi Baylina and Jacques Dafflon - * - * To the extent possible under law, the author(s) have dedicated all copyright - * and related and neighboring rights to this software to the public domain - * worldwide. This software is distributed without any warranty. - * - * You should have received a copy of the CC0 Public Domain Dedication along - * with this software. If not, see - * . - * - * ███████╗██████╗ ██████╗ █████╗ ██████╗ ██████╗ - * ██╔════╝██╔══██╗██╔════╝██╔══██╗╚════██╗██╔═████╗ - * █████╗ ██████╔╝██║ ╚█████╔╝ █████╔╝██║██╔██║ - * ██╔══╝ ██╔══██╗██║ ██╔══██╗██╔═══╝ ████╔╝██║ - * ███████╗██║ ██║╚██████╗╚█████╔╝███████╗╚██████╔╝ - * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ - * - * ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ - * ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝ - * ██████╔╝█████╗ ██║ ███╗██║███████╗ ██║ ██████╔╝ ╚████╔╝ - * ██╔══██╗██╔══╝ ██║ ██║██║╚════██║ ██║ ██╔══██╗ ╚██╔╝ - * ██║ ██║███████╗╚██████╔╝██║███████║ ██║ ██║ ██║ ██║ - * ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ - * - */ -pragma solidity 0.4.24; -// IV is value needed to have a vanity address starting with `0x820`. -// IV: 9513 - -/// @dev The interface a contract MUST implement if it is the implementer of -/// some (other) interface for any address other than itself. -interface ERC820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not. - /// @param interfaceHash keccak256 hash of the name of the interface - /// @param addr Address for which the contract will implement the interface - /// @return ERC820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32); -} - - -/// @title ERC820 Pseudo-introspection Registry Contract -/// @author Jordi Baylina and Jacques Dafflon -/// @notice This contract is the official implementation of the ERC820 Registry. -/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-820 -contract ERC820Registry { - /// @notice ERC165 Invalid ID. - bytes4 constant INVALID_ID = 0xffffffff; - /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`). - bytes4 constant ERC165ID = 0x01ffc9a7; - /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address. - bytes32 constant ERC820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC820_ACCEPT_MAGIC")); - - mapping (address => mapping(bytes32 => address)) interfaces; - mapping (address => address) managers; - mapping (address => mapping(bytes4 => bool)) erc165Cached; - - /// @notice Indicates a contract is the `implementer` of `interfaceHash` for `addr`. - event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer); - /// @notice Indicates `newManager` is the address of the new manager for `addr`. - event ManagerChanged(address indexed addr, address indexed newManager); - - /// @notice Query if an address implements an interface and through which contract. - /// @param _addr Address being queried for the implementer of an interface. - /// (If `_addr == 0` then `msg.sender` is assumed.) - /// @param _interfaceHash keccak256 hash of the name of the interface as a string. - /// E.g., `web3.utils.keccak256('ERC777Token')`. - /// @return The address of the contract which implements the interface `_interfaceHash` for `_addr` - /// or `0x0` if `_addr` did not register an implementer for this interface. - function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) { - address addr = _addr == 0 ? msg.sender : _addr; - if (isERC165Interface(_interfaceHash)) { - bytes4 erc165InterfaceHash = bytes4(_interfaceHash); - return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : 0; - } - return interfaces[addr][_interfaceHash]; - } - - /// @notice Sets the contract which implements a specific interface for an address. - /// Only the manager defined for that address can set it. - /// (Each address is the manager for itself until it sets a new manager.) - /// @param _addr Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.) - /// @param _interfaceHash keccak256 hash of the name of the interface as a string. - /// For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface. - /// @param _implementer Contract address implementing _interfaceHash for _addr. - function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external { - address addr = _addr == 0 ? msg.sender : _addr; - require(getManager(addr) == msg.sender, "Not the manager"); - - require(!isERC165Interface(_interfaceHash), "Must not be a ERC165 hash"); - if (_implementer != 0 && _implementer != msg.sender) { - require( - ERC820ImplementerInterface(_implementer) - .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC820_ACCEPT_MAGIC, - "Does not implement the interface" - ); - } - interfaces[addr][_interfaceHash] = _implementer; - emit InterfaceImplementerSet(addr, _interfaceHash, _implementer); - } - - /// @notice Sets the `_newManager` as manager for the `_addr` address. - /// The new manager will be able to call `setInterfaceImplementer` for `_addr`. - /// @param _addr Address for which to set the new manager. - /// @param _newManager Address of the new manager for `addr`. - function setManager(address _addr, address _newManager) external { - require(getManager(_addr) == msg.sender, "Not the manager"); - managers[_addr] = _newManager == _addr ? 0 : _newManager; - emit ManagerChanged(_addr, _newManager); - } - - /// @notice Get the manager of an address. - /// @param _addr Address for which to return the manager. - /// @return Address of the manager for a given address. - function getManager(address _addr) public view returns(address) { - // By default the manager of an address is the same address - if (managers[_addr] == 0) { - return _addr; - } else { - return managers[_addr]; - } - } - - /// @notice Compute the keccak256 hash of an interface given its name. - /// @param _interfaceName Name of the interface. - /// @return The keccak256 hash of an interface name. - function interfaceHash(string _interfaceName) external pure returns(bytes32) { - return keccak256(abi.encodePacked(_interfaceName)); - } - - /* --- ERC165 Related Functions --- */ - /* --- Developed in collaboration with William Entriken. --- */ - - /// @notice Updates the cache with whether the contract implements an ERC165 interface or not. - /// @param _contract Address of the contract for which to update the cache. - /// @param _interfaceId ERC165 interface for which to update the cache. - function updateERC165Cache(address _contract, bytes4 _interfaceId) external { - interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(_contract, _interfaceId) ? _contract : 0; - erc165Cached[_contract][_interfaceId] = true; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not. - /// The result may be cached, if not a direct lookup is performed. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return `true` if `_contract` implements `_interfaceId`, false otherwise. - function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) { - if (!erc165Cached[_contract][_interfaceId]) { - return implementsERC165InterfaceNoCache(_contract, _interfaceId); - } - return interfaces[_contract][_interfaceId] == _contract; - } - - /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. - /// @param _contract Address of the contract to check. - /// @param _interfaceId ERC165 interface to check. - /// @return `true` if `_contract` implements `_interfaceId`, false otherwise. - function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) { - uint256 success; - uint256 result; - - (success, result) = noThrowCall(_contract, ERC165ID); - if (success == 0 || result == 0) { - return false; - } - - (success, result) = noThrowCall(_contract, INVALID_ID); - if (success == 0 || result != 0) { - return false; - } - - (success, result) = noThrowCall(_contract, _interfaceId); - if (success == 1 && result == 1) { - return true; - } - return false; - } - - /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not. - /// @param _interfaceHash The hash to check. - /// @return `true` if the hash is a ERC165 interface (ending with 28 zeroes), `false` otherwise. - function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) { - return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0; - } - - /// @dev Make a call on a contract without throwing if the function does not exist. - function noThrowCall(address _contract, bytes4 _interfaceId) - internal view returns (uint256 success, uint256 result) - { - bytes4 erc165ID = ERC165ID; - - assembly { - let x := mload(0x40) // Find empty storage location using "free memory pointer" - mstore(x, erc165ID) // Place signature at beginning of empty storage - mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature - - success := staticcall( - 30000, // 30k gas - _contract, // To addr - x, // Inputs are stored at location x - 0x08, // Inputs are 8 bytes long - x, // Store output over input (saves space) - 0x20 // Outputs are 32 bytes long - ) - - result := mload(x) // Load the result - } - } -} - -``` - -### Deployment Transaction - -Below is the raw transaction which MUST be used to deploy the smart contract on any chain. - -``` -0xf90a2a8085174876e800830c35008080b909d7608060405234801561001057600080fd5b506109b7806100206000396000f30060806040526004361061008d5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166329965a1d81146100925780633d584063146100bf5780635df8122f146100fc57806365ba36c114610123578063a41e7d5114610155578063aabbb8ca14610183578063b7056765146101a7578063f712f3e8146101e9575b600080fd5b34801561009e57600080fd5b506100bd600160a060020a036004358116906024359060443516610217565b005b3480156100cb57600080fd5b506100e0600160a060020a0360043516610512565b60408051600160a060020a039092168252519081900360200190f35b34801561010857600080fd5b506100bd600160a060020a036004358116906024351661055e565b34801561012f57600080fd5b506101436004803560248101910135610655565b60408051918252519081900360200190f35b34801561016157600080fd5b506100bd600160a060020a0360043516600160e060020a0319602435166106e3565b34801561018f57600080fd5b506100e0600160a060020a036004351660243561076d565b3480156101b357600080fd5b506101d5600160a060020a0360043516600160e060020a0319602435166107e7565b604080519115158252519081900360200190f35b3480156101f557600080fd5b506101d5600160a060020a0360043516600160e060020a03196024351661089c565b6000600160a060020a0384161561022e5783610230565b335b90503361023c82610512565b600160a060020a03161461029a576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6102a38361091c565b156102f8576040805160e560020a62461bcd02815260206004820152601960248201527f4d757374206e6f74206265206120455243313635206861736800000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103195750600160a060020a0382163314155b156104a15760405160200180807f4552433832305f4143434550545f4d414749430000000000000000000000000081525060130190506040516020818303038152906040526040518082805190602001908083835b6020831061038d5780518252601f19909201916020918201910161036e565b51815160209384036101000a6000190180199092169116179052604080519290940182900382207f249cb3fa000000000000000000000000000000000000000000000000000000008352600483018a9052600160a060020a0388811660248501529451909650938816945063249cb3fa936044808401945091929091908290030181600087803b15801561042057600080fd5b505af1158015610434573d6000803e3d6000fd5b505050506040513d602081101561044a57600080fd5b5051146104a1576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03808216600090815260016020526040812054909116151561053c575080610559565b50600160a060020a03808216600090815260016020526040902054165b919050565b3361056883610512565b600160a060020a0316146105c6576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146105e557806105e8565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b60008282604051602001808383808284378201915050925050506040516020818303038152906040526040518082805190602001908083835b602083106106ad5780518252601f19909201916020918201910161068e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809103902090505b92915050565b6106ed82826107e7565b6106f85760006106fa565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b60008080600160a060020a038516156107865784610788565b335b91506107938461091c565b156107b85750826107a4828261089c565b6107af5760006107b1565b815b92506107df565b600160a060020a038083166000908152602081815260408083208884529091529020541692505b505092915050565b60008080610815857f01ffc9a70000000000000000000000000000000000000000000000000000000061093e565b9092509050811580610825575080155b1561083357600092506107df565b61084585600160e060020a031961093e565b909250905081158061085657508015155b1561086457600092506107df565b61086e858561093e565b90925090506001821480156108835750806001145b1561089157600192506107df565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108e4576108dd83836107e7565b90506106dd565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160088189617530fa9051909690955093505050505600a165627a7a723058204fc4461c9d5a247b0eafe0f9c508057bc0ad72bc24668cb2a35ea65850e10d3100291ba08208208208208208208208208208208208208208208208208208208208208200a00820820820820820820820820820820820820820820820820820820820820820 -``` - -The strings of `820`'s at the end of the transaction are the `r` and `s` of the signature. From this deterministic pattern (generated by a human), anyone can deduce that no one knows the private key for the deployment account. - -### Deployment Method - -This contract is going to be deployed using the keyless deployment method---also known as [Nick]'s method---which relies on a single-use address. (See [Nick's article] for more details). This method works as follows: - -1. Generate a transaction which deploys the contract from a new random account. - - This transaction MUST NOT use [EIP-155] in order to work on any chain. - - This transaction MUST have a relatively high gas price to be deployed on any chain. In this case, it is going to be 100 Gwei. - -2. Set the `v`, `r`, `s` of the transaction signature to the following values: - - ``` - v: 27 - r: 0x8208208208208208208208208208208208208208208208208208208208208200 - s: 0x0820820820820820820820820820820820820820820820820820820820820820 - ``` - - Those `r` and `s` values---made of a repeating pattern of `820`'s---are predictable "random numbers" generated deterministically by a human. - - > The values of `r` and `s` must be 32 bytes long each---or 64 characters in hexadecimal. Since `820` is 3 characters long and 3 is not a divisor of 64, but it is a divisor of 63, the `r` and `s` values are padded with one extra character. - > The `s` value is prefixed with a single zero (`0`). The `0` prefix also guarantees that `s < secp256k1n ÷ 2 + 1`. - > The `r` value, cannot be prefixed with a zero, as the transaction becomes invalid. Instead it is suffixed with a zero (`0`) which still respects the condition `s < secp256k1n`. - -3. We recover the sender of this transaction, i.e., the single-use deployment account. - - > Thus we obtain an account that can broadcast that transaction, but we also have the warranty that nobody knows the private key of that account. - -4. Send exactly 0.08 ethers to this single-use deployment account. - -5. Broadcast the deployment transaction. - -This operation can be done on any chain, guaranteeing that the contract address is always the same and nobody can use that address with a different contract. - - -### Single-use Registry Deployment Account - -``` -0xE6C244a1C10Aa0085b0cf92f04cdaD947C2988b8 -``` - -This account is generated by reverse engineering it from its signature for the transaction. This way no one knows the private key, but it is known that it is the valid signer of the deployment transaction. - -> To deploy the registry, 0.08 ethers MUST be sent to this account *first*. - -### Registry Contract Address - -``` -0x820b586C8C28125366C998641B09DCbE7d4cBF06 -``` - -The contract has the address above for every chain on which it is deployed. - -
-Raw metadata of ./contracts/ERC820Registry.sol -
-{
-  "compiler": {
-    "version": "0.4.24+commit.e67f0147"
-  },
-  "language": "Solidity",
-  "output": {
-    "abi": [
-      {
-        "constant": false,
-        "inputs": [
-          {
-            "name": "_addr",
-            "type": "address"
-          },
-          {
-            "name": "_interfaceHash",
-            "type": "bytes32"
-          },
-          {
-            "name": "_implementer",
-            "type": "address"
-          }
-        ],
-        "name": "setInterfaceImplementer",
-        "outputs": [],
-        "payable": false,
-        "stateMutability": "nonpayable",
-        "type": "function"
-      },
-      {
-        "constant": true,
-        "inputs": [
-          {
-            "name": "_addr",
-            "type": "address"
-          }
-        ],
-        "name": "getManager",
-        "outputs": [
-          {
-            "name": "",
-            "type": "address"
-          }
-        ],
-        "payable": false,
-        "stateMutability": "view",
-        "type": "function"
-      },
-      {
-        "constant": false,
-        "inputs": [
-          {
-            "name": "_addr",
-            "type": "address"
-          },
-          {
-            "name": "_newManager",
-            "type": "address"
-          }
-        ],
-        "name": "setManager",
-        "outputs": [],
-        "payable": false,
-        "stateMutability": "nonpayable",
-        "type": "function"
-      },
-      {
-        "constant": true,
-        "inputs": [
-          {
-            "name": "_interfaceName",
-            "type": "string"
-          }
-        ],
-        "name": "interfaceHash",
-        "outputs": [
-          {
-            "name": "",
-            "type": "bytes32"
-          }
-        ],
-        "payable": false,
-        "stateMutability": "pure",
-        "type": "function"
-      },
-      {
-        "constant": false,
-        "inputs": [
-          {
-            "name": "_contract",
-            "type": "address"
-          },
-          {
-            "name": "_interfaceId",
-            "type": "bytes4"
-          }
-        ],
-        "name": "updateERC165Cache",
-        "outputs": [],
-        "payable": false,
-        "stateMutability": "nonpayable",
-        "type": "function"
-      },
-      {
-        "constant": true,
-        "inputs": [
-          {
-            "name": "_addr",
-            "type": "address"
-          },
-          {
-            "name": "_interfaceHash",
-            "type": "bytes32"
-          }
-        ],
-        "name": "getInterfaceImplementer",
-        "outputs": [
-          {
-            "name": "",
-            "type": "address"
-          }
-        ],
-        "payable": false,
-        "stateMutability": "view",
-        "type": "function"
-      },
-      {
-        "constant": true,
-        "inputs": [
-          {
-            "name": "_contract",
-            "type": "address"
-          },
-          {
-            "name": "_interfaceId",
-            "type": "bytes4"
-          }
-        ],
-        "name": "implementsERC165InterfaceNoCache",
-        "outputs": [
-          {
-            "name": "",
-            "type": "bool"
-          }
-        ],
-        "payable": false,
-        "stateMutability": "view",
-        "type": "function"
-      },
-      {
-        "constant": true,
-        "inputs": [
-          {
-            "name": "_contract",
-            "type": "address"
-          },
-          {
-            "name": "_interfaceId",
-            "type": "bytes4"
-          }
-        ],
-        "name": "implementsERC165Interface",
-        "outputs": [
-          {
-            "name": "",
-            "type": "bool"
-          }
-        ],
-        "payable": false,
-        "stateMutability": "view",
-        "type": "function"
-      },
-      {
-        "anonymous": false,
-        "inputs": [
-          {
-            "indexed": true,
-            "name": "addr",
-            "type": "address"
-          },
-          {
-            "indexed": true,
-            "name": "interfaceHash",
-            "type": "bytes32"
-          },
-          {
-            "indexed": true,
-            "name": "implementer",
-            "type": "address"
-          }
-        ],
-        "name": "InterfaceImplementerSet",
-        "type": "event"
-      },
-      {
-        "anonymous": false,
-        "inputs": [
-          {
-            "indexed": true,
-            "name": "addr",
-            "type": "address"
-          },
-          {
-            "indexed": true,
-            "name": "newManager",
-            "type": "address"
-          }
-        ],
-        "name": "ManagerChanged",
-        "type": "event"
-      }
-    ],
-    "devdoc": {
-      "author": "Jordi Baylina and Jacques Dafflon",
-      "methods": {
-        "getInterfaceImplementer(address,bytes32)": {
-          "params": {
-            "_addr": "Address being queried for the implementer of an interface. (If `_addr == 0` then `msg.sender` is assumed.)",
-            "_interfaceHash": "keccak256 hash of the name of the interface as a string. E.g., `web3.utils.keccak256('ERC777Token')`."
-          },
-          "return": "The address of the contract which implements the interface `_interfaceHash` for `_addr` or `0x0` if `_addr` did not register an implementer for this interface."
-        },
-        "getManager(address)": {
-          "params": {
-            "_addr": "Address for which to return the manager."
-          },
-          "return": "Address of the manager for a given address."
-        },
-        "implementsERC165Interface(address,bytes4)": {
-          "params": {
-            "_contract": "Address of the contract to check.",
-            "_interfaceId": "ERC165 interface to check."
-          },
-          "return": "`true` if `_contract` implements `_interfaceId`, false otherwise."
-        },
-        "implementsERC165InterfaceNoCache(address,bytes4)": {
-          "params": {
-            "_contract": "Address of the contract to check.",
-            "_interfaceId": "ERC165 interface to check."
-          },
-          "return": "`true` if `_contract` implements `_interfaceId`, false otherwise."
-        },
-        "interfaceHash(string)": {
-          "params": {
-            "_interfaceName": "Name of the interface."
-          },
-          "return": "The keccak256 hash of an interface name."
-        },
-        "setInterfaceImplementer(address,bytes32,address)": {
-          "params": {
-            "_addr": "Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.)",
-            "_implementer": "Contract address implementing _interfaceHash for _addr.",
-            "_interfaceHash": "keccak256 hash of the name of the interface as a string. For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface."
-          }
-        },
-        "setManager(address,address)": {
-          "params": {
-            "_addr": "Address for which to set the new manager.",
-            "_newManager": "Address of the new manager for `addr`."
-          }
-        },
-        "updateERC165Cache(address,bytes4)": {
-          "params": {
-            "_contract": "Address of the contract for which to update the cache.",
-            "_interfaceId": "ERC165 interface for which to update the cache."
-          }
-        }
-      },
-      "title": "ERC820 Pseudo-introspection Registry Contract"
-    },
-    "userdoc": {
-      "methods": {
-        "getInterfaceImplementer(address,bytes32)": {
-          "notice": "Query if an address implements an interface and through which contract."
-        },
-        "getManager(address)": {
-          "notice": "Get the manager of an address."
-        },
-        "implementsERC165Interface(address,bytes4)": {
-          "notice": "Checks whether a contract implements an ERC165 interface or not. The result may be cached, if not a direct lookup is performed."
-        },
-        "implementsERC165InterfaceNoCache(address,bytes4)": {
-          "notice": "Checks whether a contract implements an ERC165 interface or not without using nor updating the cache."
-        },
-        "interfaceHash(string)": {
-          "notice": "Compute the keccak256 hash of an interface given its name."
-        },
-        "setInterfaceImplementer(address,bytes32,address)": {
-          "notice": "Sets the contract which implements a specific interface for an address. Only the manager defined for that address can set it. (Each address is the manager for itself until it sets a new manager.)"
-        },
-        "setManager(address,address)": {
-          "notice": "Sets the `_newManager` as manager for the `_addr` address. The new manager will be able to call `setInterfaceImplementer` for `_addr`."
-        },
-        "updateERC165Cache(address,bytes4)": {
-          "notice": "Updates the cache with whether the contract implements an ERC165 interface or not."
-        }
-      }
-    }
-  },
-  "settings": {
-    "compilationTarget": {
-      "./contracts/ERC820Registry.sol": "ERC820Registry"
-    },
-    "evmVersion": "byzantium",
-    "libraries": {},
-    "optimizer": {
-      "enabled": true,
-      "runs": 200
-    },
-    "remappings": []
-  },
-  "sources": {
-    "./contracts/ERC820Registry.sol": {
-      "content": "/* ERC820 Pseudo-introspection Registry Contract\n * This standard defines a universal registry smart contract where any address\n * (contract or regular account) can register which interface it supports and\n * which smart contract is responsible for its implementation.\n *\n * Written in 2018 by Jordi Baylina and Jacques Dafflon\n *\n * To the extent possible under law, the author(s) have dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide. This software is distributed without any warranty.\n *\n * You should have received a copy of the CC0 Public Domain Dedication along\n * with this software. If not, see\n * .\n *\n *    ███████╗██████╗  ██████╗ █████╗ ██████╗  ██████╗\n *    ██╔════╝██╔══██╗██╔════╝██╔══██╗╚════██╗██╔═████╗\n *    █████╗  ██████╔╝██║     ╚█████╔╝ █████╔╝██║██╔██║\n *    ██╔══╝  ██╔══██╗██║     ██╔══██╗██╔═══╝ ████╔╝██║\n *    ███████╗██║  ██║╚██████╗╚█████╔╝███████╗╚██████╔╝\n *    ╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝\n *\n *    ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗   ██╗\n *    ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝\n *    ██████╔╝█████╗  ██║  ███╗██║███████╗   ██║   ██████╔╝ ╚████╔╝\n *    ██╔══██╗██╔══╝  ██║   ██║██║╚════██║   ██║   ██╔══██╗  ╚██╔╝\n *    ██║  ██║███████╗╚██████╔╝██║███████║   ██║   ██║  ██║   ██║\n *    ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝\n *\n */\npragma solidity 0.4.24;\n// IV is value needed to have a vanity address starting with `0x820`.\n// IV: 9513\n\n/// @dev The interface a contract MUST implement if it is the implementer of\n/// some (other) interface for any address other than itself.\ninterface ERC820ImplementerInterface {\n    /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not.\n    /// @param interfaceHash keccak256 hash of the name of the interface\n    /// @param addr Address for which the contract will implement the interface\n    /// @return ERC820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`.\n    function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);\n}\n\n\n/// @title ERC820 Pseudo-introspection Registry Contract\n/// @author Jordi Baylina and Jacques Dafflon\n/// @notice This contract is the official implementation of the ERC820 Registry.\n/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-820\ncontract ERC820Registry {\n    /// @notice ERC165 Invalid ID.\n    bytes4 constant INVALID_ID = 0xffffffff;\n    /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).\n    bytes4 constant ERC165ID = 0x01ffc9a7;\n    /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.\n    bytes32 constant ERC820_ACCEPT_MAGIC = keccak256(abi.encodePacked(\"ERC820_ACCEPT_MAGIC\"));\n\n    mapping (address => mapping(bytes32 => address)) interfaces;\n    mapping (address => address) managers;\n    mapping (address => mapping(bytes4 => bool)) erc165Cached;\n\n    /// @notice Indicates a contract is the `implementer` of `interfaceHash` for `addr`.\n    event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);\n    /// @notice Indicates `newManager` is the address of the new manager for `addr`.\n    event ManagerChanged(address indexed addr, address indexed newManager);\n\n    /// @notice Query if an address implements an interface and through which contract.\n    /// @param _addr Address being queried for the implementer of an interface.\n    /// (If `_addr == 0` then `msg.sender` is assumed.)\n    /// @param _interfaceHash keccak256 hash of the name of the interface as a string.\n    /// E.g., `web3.utils.keccak256('ERC777Token')`.\n    /// @return The address of the contract which implements the interface `_interfaceHash` for `_addr`\n    /// or `0x0` if `_addr` did not register an implementer for this interface.\n    function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {\n        address addr = _addr == 0 ? msg.sender : _addr;\n        if (isERC165Interface(_interfaceHash)) {\n            bytes4 erc165InterfaceHash = bytes4(_interfaceHash);\n            return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : 0;\n        }\n        return interfaces[addr][_interfaceHash];\n    }\n\n    /// @notice Sets the contract which implements a specific interface for an address.\n    /// Only the manager defined for that address can set it.\n    /// (Each address is the manager for itself until it sets a new manager.)\n    /// @param _addr Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.)\n    /// @param _interfaceHash keccak256 hash of the name of the interface as a string.\n    /// For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface.\n    /// @param _implementer Contract address implementing _interfaceHash for _addr.\n    function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {\n        address addr = _addr == 0 ? msg.sender : _addr;\n        require(getManager(addr) == msg.sender, \"Not the manager\");\n\n        require(!isERC165Interface(_interfaceHash), \"Must not be a ERC165 hash\");\n        if (_implementer != 0 && _implementer != msg.sender) {\n            require(\n                ERC820ImplementerInterface(_implementer)\n                    .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC820_ACCEPT_MAGIC,\n                \"Does not implement the interface\"\n            );\n        }\n        interfaces[addr][_interfaceHash] = _implementer;\n        emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);\n    }\n\n    /// @notice Sets the `_newManager` as manager for the `_addr` address.\n    /// The new manager will be able to call `setInterfaceImplementer` for `_addr`.\n    /// @param _addr Address for which to set the new manager.\n    /// @param _newManager Address of the new manager for `addr`.\n    function setManager(address _addr, address _newManager) external {\n        require(getManager(_addr) == msg.sender, \"Not the manager\");\n        managers[_addr] = _newManager == _addr ? 0 : _newManager;\n        emit ManagerChanged(_addr, _newManager);\n    }\n\n    /// @notice Get the manager of an address.\n    /// @param _addr Address for which to return the manager.\n    /// @return Address of the manager for a given address.\n    function getManager(address _addr) public view returns(address) {\n        // By default the manager of an address is the same address\n        if (managers[_addr] == 0) {\n            return _addr;\n        } else {\n            return managers[_addr];\n        }\n    }\n\n    /// @notice Compute the keccak256 hash of an interface given its name.\n    /// @param _interfaceName Name of the interface.\n    /// @return The keccak256 hash of an interface name.\n    function interfaceHash(string _interfaceName) external pure returns(bytes32) {\n        return keccak256(abi.encodePacked(_interfaceName));\n    }\n\n    /* --- ERC165 Related Functions --- */\n    /* --- Developed in collaboration with William Entriken. --- */\n\n    /// @notice Updates the cache with whether the contract implements an ERC165 interface or not.\n    /// @param _contract Address of the contract for which to update the cache.\n    /// @param _interfaceId ERC165 interface for which to update the cache.\n    function updateERC165Cache(address _contract, bytes4 _interfaceId) external {\n        interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(_contract, _interfaceId) ? _contract : 0;\n        erc165Cached[_contract][_interfaceId] = true;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not.\n    /// The result may be cached, if not a direct lookup is performed.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.\n    function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        if (!erc165Cached[_contract][_interfaceId]) {\n            return implementsERC165InterfaceNoCache(_contract, _interfaceId);\n        }\n        return interfaces[_contract][_interfaceId] == _contract;\n    }\n\n    /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.\n    /// @param _contract Address of the contract to check.\n    /// @param _interfaceId ERC165 interface to check.\n    /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.\n    function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {\n        uint256 success;\n        uint256 result;\n\n        (success, result) = noThrowCall(_contract, ERC165ID);\n        if (success == 0 || result == 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, INVALID_ID);\n        if (success == 0 || result != 0) {\n            return false;\n        }\n\n        (success, result) = noThrowCall(_contract, _interfaceId);\n        if (success == 1 && result == 1) {\n            return true;\n        }\n        return false;\n    }\n\n    /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not.\n    /// @param _interfaceHash The hash to check.\n    /// @return `true` if the hash is a ERC165 interface (ending with 28 zeroes), `false` otherwise.\n    function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {\n        return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;\n    }\n\n    /// @dev Make a call on a contract without throwing if the function does not exist.\n    function noThrowCall(address _contract, bytes4 _interfaceId)\n        internal view returns (uint256 success, uint256 result)\n    {\n        bytes4 erc165ID = ERC165ID;\n\n        assembly {\n                let x := mload(0x40)               // Find empty storage location using \"free memory pointer\"\n                mstore(x, erc165ID)                // Place signature at beginning of empty storage\n                mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature\n\n                success := staticcall(\n                    30000,                         // 30k gas\n                    _contract,                     // To addr\n                    x,                             // Inputs are stored at location x\n                    0x08,                          // Inputs are 8 bytes long\n                    x,                             // Store output over input (saves space)\n                    0x20                           // Outputs are 32 bytes long\n                )\n\n                result := mload(x)                 // Load the result\n        }\n    }\n}\n",
-      "keccak256": "0x8eecce3912a15087b3f5845d5a74af7712c93d0a8fcd6f2d40f07ed5032022ab"
-    }
-  },
-  "version": 1
-}
-
-
- -### Interface Name - -Any interface name is hashed using `keccak256` and sent to `getInterfaceImplementer()`. - -If the interface is part of a standard, it is best practice to explicitly state the interface name and link to this published [ERC-820] such that other people don't have to come here to look up these rules. - -For convenience, the registry provides a function to compute the hash on-chain: - -``` solidity -function interfaceHash(string _interfaceName) public pure returns(bytes32) -``` - -Compute the keccak256 hash of an interface given its name. - -> **identifier:** `65ba36c1` -> **parameters** -> `_interfaceName`: Name of the interface. -> **returns:** The `keccak256` hash of an interface name. - -#### **Approved ERCs** - -If the interface is part of an approved ERC, it MUST be named `ERC###XXXXX` where `###` is the number of the ERC and XXXXX should be the name of the interface in CamelCase. The meaning of this interface SHOULD be defined in the specified ERC. - -Examples: - -- `keccak256("ERC20Token")` -- `keccak256("ERC777Token")` -- `keccak256("ERC777TokensSender")` -- `keccak256("ERC777TokensRecipient")` - -#### **[ERC-165] Compatible Interfaces** - -> The compatibility with [ERC-165], including the [ERC165 Cache], has been designed and developed with [William Entriken]. - -Any interface where the last 28 bytes are zeroes (`0`) SHALL be considered an [ERC-165] interface. - -**[ERC-165] Lookup** - -Anyone can explicitly check if a contract implements an [ERC-165] interface using the registry by calling one of the two functions below: - -``` solidity -function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC-165] interface or not. - -*NOTE*: The result is cached. If the cache is out of date, it MUST be updated by calling `updateERC165Cache`. (See [ERC165 Cache] for more details.) - -> **identifier:** `f712f3e8` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC-165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, false otherwise. - -``` solidity -function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) -``` - -Checks whether a contract implements an [ERC-165] interface or not without using nor updating the cache. - -> **identifier:** `b7056765` -> **parameters** -> `_contract`: Address of the contract to check. -> `_interfaceId`: [ERC-165] interface to check. -> **returns:** `true` if `_contract` implements `_interfaceId`, false otherwise. - -**[ERC-165] Cache** - -Whether a contract implements an [ERC-165] interface or not can be cached manually to save gas. - -If a contract dynamically changes its interface and relies on the [ERC-165] cache of the [ERC-820] registry, the cache MUST be updated manually---there is no automatic cache invalidation or cache update. Ideally the contract SHOULD automatically update the cache when changing its interface. However anyone MAY update the cache on the contract's behalf. - -The cache update MUST be done using the `updateERC165Cache` function: - -``` solidity -function updateERC165Cache(address _contract, bytes4 _interfaceId) public -``` - -> **identifier:** `a41e7d51` -> **parameters** -> `_contract`: Address of the contract for which to update the cache. -> `_interfaceId`: [ERC-165] interface for which to update the cache. - -#### **Private User-defined Interfaces** - -This scheme is extensible. You MAY make up your own interface name and raise awareness to get other people to implement it and then check for those implementations. Have fun but please, you MUST not conflict with the reserved designations above. - -### Set An Interface For An Address - -For any address to set a contract as the interface implementation, it must call the following function of the [ERC-820] registry: - -``` solidity -function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) public -``` - -Sets the contract which implements a specific interface for an address. - -Only the `manager` defined for that address can set it. (Each address is the manager for itself, see the [manager] section for more details.) - -*NOTE*: If `_addr` and `_implementer` are two different addresses, then: - -- The `_implementer` MUST implement the `ERC820ImplementerInterface` (detailed below). -- Calling `canImplementInterfaceForAddress` on `_implementer` with the given `_addr` and `_interfaceHash` MUST return the `ERC820_ACCEPT_MAGIC` value. - -*NOTE*: The `_interfaceHash` MUST NOT be an [ERC-165] interface---it MUST NOT end with 28 zeroes (`0`). - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. This default value simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `29965a1d` -> **parameters** -> `_addr`: Address to define the interface for (if `_addr == 0` them `msg.sender`: is assumed) -> `_interfaceHash`: `keccak256` hash of the name of the interface as a string, for example `web3.utils.keccak256('ERC777TokensRecipient')` for the ERC777TokensRecipient interface. -> `_implementer`: Contract implementing `_interfaceHash` for `_addr`. - -### Get An Implementation Of An Interface For An Address - -Anyone MAY query the [ERC-820] Registry to obtain the address of a contract implementing an interface on behalf of some address using the `getInterfaceImplementer` function. - -``` solidity -function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) public view returns (address) -``` - -Query if an address implements an interface and through which contract. - -*NOTE*: If the last 28 bytes of the `_interfaceHash` are zeroes (`0`), then the first 4 bytes are considered an [ERC-165] interface and the registry SHALL forward the call to the contract at `_addr` to see if it implements the [ERC-165] interface (the first 4 bytes of `_interfaceHash`). The registry SHALL also cache [ERC-165] queries to reduce gas consumption. Anyone MAY call the `erc165UpdateCache` function to update whether a contract implements an interface or not. - -*NOTE*: The `_addr` MAY be `0`, then `msg.sender` is assumed. This default value is consistent with the behavior of the `setInterfaceImplementer` function and simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance. - -> **identifier:** `aabbb8ca` -> **parameters** -> `_addr`: Address being queried for the implementer of an interface. (If `_addr == 0` them `msg.sender` is assumed.) -> `_interfaceHash`: keccak256 hash of the name of the interface as a string. E.g. `web3.utils.keccak256('ERC777Token')` -> **returns:** The address of the contract which implements the interface `_interfaceHash` for `_addr` or `0x0` if `_addr` did not register an implementer for this interface. - - -### Interface Implementation (`ERC820ImplementerInterface`) - -``` solidity -interface ERC820ImplementerInterface { - /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr`. - /// @param addr Address for which the contract will implement the interface - /// @param interfaceHash keccak256 hash of the name of the interface - /// @return ERC820_ACCEPT_MAGIC only if the contract implements `ìnterfaceHash` for the address `addr`. - function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) public view returns(bytes32); -} -``` - -Any contract being registered as the implementation of an interface for a given address MUST implement said interface. In addition if it implements an interface on behalf of a different address, the contract MUST implement the `ERC820ImplementerInterface` shown above. - -``` solidity -function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) view public returns(bytes32); -``` - -Indicates whether a contract implements an interface (`interfaceHash`) for a given address (`addr`). - -If a contract implements the interface (`interfaceHash`) for a given address (`addr`), it MUST return `ERC820_ACCEPT_MAGIC` when called with the `addr` and the `interfaceHash`. If it does not implement the `interfaceHash` for a given address (`addr`), it MUST NOT return `ERC820_ACCEPT_MAGIC`. - -> **identifier:** `f0083250` -> **parameters** -> `interfaceHash`: Hash of the interface which is implemented -> `addr`: Address for which the interface is implemented -> **returns:** `ERC820_ACCEPT_MAGIC` only if the contract implements `ìnterfaceHash` for the address `addr`. - -The special value `ERC820_ACCEPT_MAGIC` is defined as the `keccka256` hash of the string `"ERC820_ACCEPT_MAGIC"`. - -``` solidity -bytes32 constant ERC820_ACCEPT_MAGIC = keccak256("ERC820_ACCEPT_MAGIC"); -``` - -> The reason to return `ERC820_ACCEPT_MAGIC` instead of a boolean is to prevent cases where a contract fails to implement the `canImplementInterfaceForAddress` but implements a fallback function which does not throw. In this case, since `canImplementInterfaceForAddress` does not exist, the fallback function is called instead, executed without throwing and returns `1`. Thus making it appear as if `canImplementInterfaceForAddress` returned `true`. - -### Manager - -The manager of an address (regular account or a contract) is the only entity allowed to register implementations of interfaces for the address. By default, any address is its own manager. - -The manager can transfer its role to another address by calling `setManager` on the registry contract with the address for which to transfer the manager and the address of the new manager. - -**`setManager` Function** - -``` solidity -function setManager(address _addr, address _newManager) public -``` - -Sets the `_newManager` as manager for the `_addr` address. - -The new manager will be able to call `setInterfaceImplementer` for `_addr`. - -If `_newManager` is `0x0`, the manager is reset to `_addr` itself as the manager. - -> **identifier:** `5df8122f` -> **parameters** -> `_addr`: Address for which to set the new manager. -> `_newManager`: The address of the new manager for `_addr`. (Pass `0x0` to reset the manager to `_addr`.) - -**`getManager` Function** - -``` solidity -function getManager(address _addr) public view returns(address) -``` - -Get the manager of an address. - -> **identifier:** `3d584063` -> **parameters** -> `_addr`: Address for which to return the manager. -> **returns:** Address of the manager for a given address. - -## Rationale - -This standards offers a way for any type of address (externally owned and contracts) to implement an interface and potentially delegate the implementation of the interface to a proxy contract. This delegation to a proxy contract is necessary for externally owned accounts and useful to avoid redeploying existing contracts such as multisigs and DAOs. - -The registry can also act as a [ERC-165] cache in order to save gas when looking up if a contract implements a specific [ERC-165] interface. This cache is intentionally kept simple, without automatic cache update or invalidation. Anyone can easily and safely update the cache for any interface and any contract by calling the `updateERC165Cache` function. - -The registry is deployed using a keyless deployment method relying on a single-use deployment address to ensure no one controls the registry, thereby ensuring trust. - -## Backward Compatibility - -This standard is backward compatible with [ERC-165], as both methods MAY be implemented without conflicting with each other. - -## Test Cases - -Please check the [jbaylina/ERC820] repository for the full test suite. - -## Implementation - -The implementation is available in the repo: [jbaylina/ERC820]. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). - -[EIP-155]: ./eip-155.md -[ERC-165]: ./eip-165.md -[ERC-672]: https://github.com/ethereum/EIPs/issues/672 -[ERC-820]: ./eip-820.md -[ERC820 registry smart contract]: https://github.com/jbaylina/ERC820/blob/master/contracts/ERC820Registry.sol -[manager]: #manager -[lookup]: #get-an-implementation-of-an-interface-for-an-address -[ERC165 Cache]: #erc165-cache -[Nick's article]: https://medium.com/@weka/how-to-send-ether-to-11-440-people-187e332566b7 -[jbaylina/ERC820]: https://github.com/jbaylina/ERC820 -[Nick]: https://github.com/Arachnid/ -[William Entriken]: https://github.com/fulldecent -[ENS]: https://ens.domains/ -[ERC-1820]: ./eip-1820.md -[erc1820-annoucement]: https://github.com/ethereum/EIPs/issues/820#issuecomment-464109166 -[erc820-bug]: https://github.com/ethereum/EIPs/issues/820#issuecomment-452465748 -[erc820-fix]: https://github.com/ethereum/EIPs/issues/820#issuecomment-454021564 +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-820.md diff --git a/EIPS/eip-823.md b/EIPS/eip-823.md index 825a184d28641e..3132a2a5579271 100644 --- a/EIPS/eip-823.md +++ b/EIPS/eip-823.md @@ -1,214 +1,7 @@ --- eip: 823 -title: Token Exchange Standard -author: Kashish Khullar -type: Standards Track category: ERC -status: Stagnant -created: 2018-01-06 -requires: 20 +status: Moved --- -## Simple Summary -A standard for token contracts, providing token exchange services thereby facilitating cross token payments. - -## Abstract -The following standard provides functionally to make payments in the form of any other registered tokens, as well as allow token contracts to store any other tokens in an existing token contract. This standard allows ERC20 token holders to exchange their token with another ERC20 token and use the exchanged tokens to make payments. After a successful payment, the former specified ERC20 tokens, will be stored within the ERC20 token contract they are exchanged with. This proposal uses the term target contract which is used to denote the contract to the token with whom we want to exchange our tokens. - -## Motivation -Existing token standards do not provide functionality to exchange tokens. Existing token converters reduce the total supply of an existing token, which in the sense destroys the currency. Token converters do not solve this problem and hence discourages creation of new tokens. This solution does not destroy the existing token but in essence preserve them in the token contract that they are exchanged with, which in turn increases the market value of the latter. - -## Specification -### Sender Interface -This interface must be inherited by a ERC20 token contract that wants to exchange its tokens with another token. - -#### Storage Variables -##### exchnagedWith -This mapping stores the number of tokens exchanged with another token, along with the latter’s address. Every time more tokens are exchanged the integer value is incremented consequently. This mapping acts as a record to denote which target contract holds our tokens. - -```solidity -mapping ( address => uint ) private exchangedWith; -``` -##### exchangedBy -This mapping stores the address of the person who initiated the exchange and the amount of tokens exchanged. - -```solidity -mapping ( address => uint ) private exhangedBy; -``` - -#### Methods - -NOTE: Callers MUST handle false from returns (bool success). Callers MUST NOT assume that false is never returned! - -##### exchangeToken -This function calls the intermediate exchange service contract that handles the exchanges. This function takes the address of the target contract and the amount we want to exchange as parameters and returns boolean `success` and `creditedAmount`. - -```solidity -function exchangeToken(address _targetContract, uint _amount) public returns(bool success, uint creditedAmount) -``` - -##### exchangeAndSpend -This function calls an intermediate exchange service contract that handles exchange and expenditure. This function takes the address of the target contract, the amount we want to spend in terms of target contract tokens and address of the receiver as parameters and returns boolean `success`. - -```solidity -function exchangeAndSpend(address _targetContract, uint _amount,address _to) public returns(bool success) -``` - -##### __exchangerCallback -This function is called by the exchange service contract to our token contract to deduct calculated amount from our balance. It takes the address of the targert contract , the address of the person who exchanged the tokens and amount to be deducted from exchangers account as parameters and returns boolean `success`. - -NOTE: It is required that only the exchange service contract has the authority to call this function. - -```solidity -function __exchangerCallback(address _targetContract,address _exchanger, uint _amount) public returns(bool success) -``` - -#### Events - -##### Exchange -This event logs any new exchanges that have taken place. - -```solidity -event Exchange(address _from, address _ targetContract, uint _amount) -``` - -##### ExchangeSpent -This event logs any new exchange that have taken place and have been spent immediately. - -```solidity -event ExchangeSpent(address _from, address _targetContract, address _to, uint _amount) -``` - -### Receiver Interface -This interface must be inherited by a ERC20 token contract that wants to receive exchanged tokens. - -#### Storage Variables -##### exchangesRecieved -This mapping stores the number of tokens received in terms of another token, along with its address. Every time more tokens are exchanged the integer value is incremented consequently. This mapping acts as a record to denote which tokens do this contract holds apart from its own. - -```solidity -mapping ( address => uint ) private exchnagesReceived; -``` -#### Methods - -NOTE: Callers MUST handle false from returns (bool success). Callers MUST NOT assume that false is never returned! - -##### __targetExchangeCallback -This function is called by the intermediate exchange service contract. This function should add `_amount` tokens of the target contract to the exchangers address for exchange to be completed successfully. - -NOTE: It is required that only the exchange service contract has the authority to call this function. - -```solidity -function __targetExchangeCallback (uint _to, uint _amount) public returns(bool success) -``` - -##### __targetExchangeAndSpendCallback -This function is called by the intermediate exchange service contract. This function should add `_amount` tokens of the target contract to the exchangers address and transfer it to the `_to` address for the exchange and expenditure to be completed successfully. - -NOTE: It is required that only the exchange service contract has the authority to call this function. - -```solidity -function __targetExchangeAndSpendCallback (address _from, address _to, uint _amount) public returns(bool success) -``` - -#### Events -##### Exchange -This event logs any new exchanges that have taken place. - -```solidity -event Exchange(address _from, address _with, uint _amount) -``` - -##### ExchangeSpent -This event logs any new exchange that have taken place and have been spent immediately. -```solidity -event ExchangeSpent(address _from, address _ targetContract, address _to, uint _amount) -``` - -### Exchange Service Contract - -This is an intermediate contract that provides a gateway for exchanges and expenditure. This contract uses oracles to get the authenticated exchange rates. - -#### Storage Variables - -##### registeredTokens - -This array stores all the tokens that are registered for exchange. Only register tokens can participate in exchanges. - -```solidity -address[] private registeredTokens; -``` - -#### Methods - -##### registerToken - -This function is called by the owner of the token contract to get it’s tokens registered. It takes the address of the token as the parameter and return boolean `success`. - -NOTE: Before any exchange it must be ensured that the token is registered. - -```solidity -function registerToken(address _token) public returns(bool success) -``` - -##### exchangeToken - -This function is called by the token holder who wants to exchange his token with the `_targetContract` tokens. This function queries the exchange rate, calculates the converted amount, calls `__exchangerCallback` and calls the `__targetExchangeCallback`. It takes address of the target contract and amount to exchange as parameter and returns boolean `success` and amount credited. - -```solidity -function exchangeToken(address _targetContract, uint _amount, address _from) public returns(bool success, uint creditedAmount) -``` - -##### exchangeAndSpend - -This function is called by the token holder who wants to exchange his token with the `_targetContract` tokens. This function queries the exchange rate, calculates the converted amount, calls `__exchangerCallback` and calls the `__targetExchangeAndSpendCallback`. It takes address of the target contract and amount to exchange as parameter and returns boolean `success` and amount credited. - -```solidity -function exchangeAndSpend(address _targetContract, uint _amount, address _from, address _to) public returns(bool success) -``` - -#### Events - -##### Exchanges - -This event logs any new exchanges that have taken place. - -```solidity -event Exchange( address _from, address _by, uint _value ,address _target ) -``` -##### ExchangeAndSpent - -This event logs any new exchange that have taken place and have been spent immediately. - -```solidity -event ExchangeAndSpent ( address _from, address _by, uint _value ,address _target ,address _to) -``` - -### Diagramatic Explanation - -#### Exchanging Tokens -![token-exchange-standard-visual-representation-1](../assets/eip-823/eip-823-token-exchange-standard-visual-representation-1.png) - -NOTE: After the successful exchange the contract on right owns some tokens of the contract on the left. - -#### Exchanging And Spending Tokens - -![token-exchange-standard-visual-representation-2](../assets/eip-823/eip-823-token-exchange-standard-visual-representation-2.png) - -NOTE: After the successful exchange the contract on right owns some tokens of the contract on the left. - -## Rationale - -Such a design provides a consistent exchange standard -applicable to all ERC20 tokens that follow it. -The primary advantage for of this strategy is that the exchanged tokens will not be lost. They can either be spent or preserved. -Token convert face a major drawback of destroying tokens after conversion. This mechanism treats tokens like conventional currency where tokens are not destroyed but are stored. - -## Backward Compatibility - -This proposal is fully backward compatible. Tokens extended by this proposal should also be following ERC20 standard. The functionality of ERC20 standard should not be affected by this proposal but will provide additional functionality to it. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-823.md diff --git a/EIPS/eip-831.md b/EIPS/eip-831.md index 7813d21de26f56..47ef13e93bedfc 100644 --- a/EIPS/eip-831.md +++ b/EIPS/eip-831.md @@ -1,44 +1,7 @@ --- eip: 831 -title: URI Format for Ethereum -description: A way of creating Ethereum URIs for various use-cases. -author: ligi (@ligi) -discussions-to: https://ethereum-magicians.org/t/eip-831-uri-format-for-ethereum/10105 -status: Review -type: Standards Track category: ERC -created: 2018-01-15 -requires: 67, 681 +status: Moved --- -## Abstract - -URIs embedded in QR-codes, hyperlinks in web-pages, emails or chat messages provide for robust cross-application signaling between very loosely coupled applications. A standardized URI format allows for instant invocation of the user's preferred wallet application. - -## Specification - -### Syntax - -Ethereum URIs contain "ethereum" or "eth" in their schema (protocol) part and are constructed as follows: - - request = "eth" [ "ereum" ] ":" [ prefix "-" ] payload - prefix = STRING - payload = STRING - -### Semantics - -`prefix` is optional and defines the use-case for this URI. If no prefix is given: "pay-" is assumed to be concise and ensure backward compatibility to [EIP-67](./eip-67.md). When the prefix is omitted, the payload must start with `0x`. Also prefixes must not start with `0x`. So starting with `0x` can be used as a clear signal that there is no prefix. - -`payload` is mandatory and the content depends on the prefix. Structuring of the content is defined in the ERC for the specific use-case and not in the scope of this document. One example is [EIP-681](./eip-681) for the pay- prefix. - -## Rationale - -The need for this ERC emerged when refining EIP-681. We need a container that does not carry the weight of the use-cases. EIP-67 was the first attempt on defining Ethereum-URIs. This ERC tries to keep backward compatibility and not break existing things. This means EIP-67 URIs should still be valid and readable. Only if the prefix feature is used, EIP-67 parsers might break. No way was seen to avoid this and innovate on the same time. This is also the reason this open prefix approach was chosen to being able to adopt to future use-cases and not block the whole "ethereum:" scheme for a limited set of use-cases that existed at the time of writing this. - -## Security Considerations - -There are no known security considerations at this time. - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-831.md diff --git a/EIPS/eip-875.md b/EIPS/eip-875.md index 9ac2c225923dd7..e3968d9679546d 100644 --- a/EIPS/eip-875.md +++ b/EIPS/eip-875.md @@ -1,105 +1,7 @@ --- eip: 875 -title: Simpler NFT standard with batching and native atomic swaps -author: Weiwu Zhang , James Sangalli -discussions-to: https://github.com/ethereum/EIPs/issues/875 -status: Withdrawn -type: Standards Track category: ERC -created: 2018-02-08 +status: Moved --- -## Summary -A simple non fungible token standard that allows batching tokens into lots and settling p2p atomic transfers in one transaction. You can test out an example implementation on rinkeby here: https://rinkeby.etherscan.io/address/0xffab5ce7c012bc942f5ca0cd42c3c2e1ae5f0005 and view the repo here: https://github.com/alpha-wallet/ERC-Example - -## Purpose -While other standards allow the user to transfer a non-fungible token, they require one transaction per token, this is heavy on gas and partially responsible for clogging the ethereum network. There are also few definitions for how to do a simple atomic swap. - -## Rinkeby example -This standard has been implemented in an example contract on rinkeby: https://rinkeby.etherscan.io/address/0xffab5ce7c012bc942f5ca0cd42c3c2e1ae5f0005 - -## Specification - -### function name() constant returns (string name) - -returns the name of the contract e.g. CarLotContract - -### function symbol() constant returns (string symbol) - -Returns a short string of the symbol of the in-fungible token, this should be short and generic as each token is non-fungible. - -### function balanceOf(address _owner) public view returns (uint256[] balance) - -Returns an array of the users balance. - -### function transfer(address _to, uint256[] _tokens) public; - -Transfer your unique tokens to an address by adding an array of the token indices. This compares favourable to ERC721 as you can transfer a bulk of tokens in one go rather than one at a time. This has a big gas saving as well as being more convenient. - -### function transferFrom(address _from, address _to, uint256[] _tokens) public; - -Transfer a variable amount of tokens from one user to another. This can be done from an authorised party with a specified key e.g. contract owner. - -## Optional functions - -### function totalSupply() constant returns (uint256 totalSupply); - -Returns the total amount of tokens in the given contract, this should be optional as assets might be allocated and issued on the fly. This means that supply is not always fixed. - -### function ownerOf(uint256 _tokenId) public view returns (address _owner); - -Returns the owner of a particular token, I think this should be optional as not every token contract will need to track the owner of a unique token and it costs gas to loop and map the token id owners each time the balances change. - -### function trade(uint256 expiryTimeStamp, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s) public payable - -A function which allows a user to sell a batch of non-fungible tokens without paying for the gas fee (only the buyer has to) in a p2p atomic swap. This is achieved by signing an attestation containing the amount of tokens to sell, the contract address, an expiry timestamp, the price and a prefix containing the ERC spec name and chain id. A buyer can then pay for the deal in one transaction by attaching the appropriate ether to satisfy the deal. - -This design is also more efficient as it allows orders to be done offline until settlement as opposed to creating orders in a smart contract and updating them. The expiry timestamp protects the seller against people using old orders. - -This opens up the gates for a p2p atomic swap but should be optional to this standard as some may not have use for it. - -Some protections need to be added to the message such as encoding the chain id, contract address and the ERC spec name to prevent replays and spoofing people into signing message that allow a trade. - -## Interface - -```solidity -contract ERC165 -{ - /// @notice Query if a contract implements an interface - /// @param interfaceID The interface identifier, as specified in ERC-165 - /// @dev Interface identification is specified in ERC-165. This function - /// uses less than 30,000 gas. - /// @return `true` if the contract implements `interfaceID` and - /// `interfaceID` is not 0xffffffff, `false` otherwise - function supportsInterface(bytes4 interfaceID) external view returns (bool); -} - -interface ERC875 /* is ERC165 */ -{ - event Transfer(address indexed _from, address indexed _to, uint256[] tokenIndices); - - function name() constant public returns (string name); - function symbol() constant public returns (string symbol); - function balanceOf(address _owner) public view returns (uint256[] _balances); - function transfer(address _to, uint256[] _tokens) public; - function transferFrom(address _from, address _to, uint256[] _tokens) public; -} - -//If you want the standard functions with atomic swap trading added -interface ERC875WithAtomicSwapTrading is ERC875 { - function trade( - uint256 expiryTimeStamp, - uint256[] tokenIndices, - uint8 v, - bytes32 r, - bytes32 s - ) public payable; -} -``` - -## Example implementation - -Please visit this [repo](https://github.com/alpha-wallet/ERC875) to see an example implementation - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-875.md diff --git a/EIPS/eip-884.md b/EIPS/eip-884.md index c2bb76c72ccc19..35152fb1daae42 100644 --- a/EIPS/eip-884.md +++ b/EIPS/eip-884.md @@ -1,322 +1,7 @@ --- eip: 884 -title: DGCL Token -author: Dave Sag -type: Standards Track category: ERC -status: Stagnant -created: 2018-02-14 +status: Moved --- -# Delaware General Corporations Law (DGCL) compatible share token - -Ref: [proposing-an-eip-for-DGCL-tokens](https://forum.ethereum.org/discussion/17200/proposing-an-eip-for-regulation-a-Tokens) - -## Simple Summary - -An `ERC-20` compatible token that conforms to [Delaware State Senate, 149th General Assembly, Senate Bill No. 69: An act to Amend Title 8 of the Delaware Code Relating to the General Corporation Law](https://legis.delaware.gov/json/BillDetail/GenerateHtmlDocument?legislationId=25730&legislationTypeId=1&docTypeId=2&legislationName=SB69), henceforth referred to as 'The Act'. - -## Abstract - -The recently amended 'Title 8 of the Delaware Code Relating to the General Corporation Law' now explicitly allows for the use of blockchains to maintain corporate share registries. This means it is now possible to create a tradable `ERC-20` token where each token represents a share issued by a Delaware corporation. Such a token must conform to the following principles over and above the `ERC-20` standard. - -1. Token owners must have their identity verified. -2. The token contract must provide the following three functions of a `Corporations Stock ledger` (Ref: Section 224 of The Act): - - 1. Reporting: - - It must enable the corporation to prepare the list of shareholders specified in Sections 219 and 220 of The Act. - - 2. It must record the information specified in Sections 156, 159, 217(a) and 218 of The Act: - - - Partly paid shares - - Total amount paid - - Total amount to be paid - - 3. Transfers of shares as per section 159 of The Act: - - It must record transfers of shares as governed by Article 8 of subtitle I of Title 6. - -3. Each token MUST correspond to a single share, each of which would be paid for in full, so there is no need to record information concerning partly paid shares, and there are no partial tokens. - -4. There must be a mechanism to allow a shareholder who has lost their private key, or otherwise lost access to their tokens to have their address `cancelled` and the tokens re-issued to a new address. - -## Motivation - -1. Delaware General Corporation Law requires that shares issued by a Delaware corporation be recorded in a share registry. -2. The share registry can be represented by an `ERC-20` token contract that is compliant with Delaware General Corporation Law. -3. This standard can cover equity issued by any Delaware corporation, whether private or public. - -By using a `DGCL` compatible token, a firm may be able to raise funds via IPO, conforming to Delaware Corporations Law, but bypassing the need for involvement of a traditional Stock Exchange. - -There are currently no token standards that conform to the `DGCL` rules. `ERC-20` tokens do not support KYC/AML rules required by the General Corporation Law, and do not provide facilities for the exporting of lists of shareholders. - -### What about ERC-721? - -The proposed standard could easily be used to enhance `ERC-721`, adding features for associating tokens with assets such as share certificates. - -While the `ERC-721` token proposal allows for some association of metadata with an Ethereum address, its uses are _not completely aligned_ with The Act, and it is not, in its current form, fully `ERC-20` compatible. - -## Specification - -The `ERC-20` token provides the following basic features: - - contract ERC20 { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); - event Transfer(address indexed from, address indexed to, uint256 value); - } - -This will be extended as follows: - - /** - * An `ERC20` compatible token that conforms to Delaware State Senate, - * 149th General Assembly, Senate Bill No. 69: An act to Amend Title 8 - * of the Delaware Code Relating to the General Corporation Law. - * - * Implementation Details. - * - * An implementation of this token standard SHOULD provide the following: - * - * `name` - for use by wallets and exchanges. - * `symbol` - for use by wallets and exchanges. - * - * The implementation MUST take care not to allow unauthorised access to - * share-transfer functions. - * - * In addition to the above the following optional `ERC20` function MUST be defined. - * - * `decimals` — MUST return `0` as each token represents a single share and shares are non-divisible. - * - * @dev Ref https://github.com/ethereum/EIPs/pull/884 - */ - contract ERC884 is ERC20 { - - /** - * This event is emitted when a verified address and associated identity hash are - * added to the contract. - * @param addr The address that was added. - * @param hash The identity hash associated with the address. - * @param sender The address that caused the address to be added. - */ - event VerifiedAddressAdded( - address indexed addr, - bytes32 hash, - address indexed sender - ); - - /** - * This event is emitted when a verified address and associated identity hash are - * removed from the contract. - * @param addr The address that was removed. - * @param sender The address that caused the address to be removed. - */ - event VerifiedAddressRemoved(address indexed addr, address indexed sender); - - /** - * This event is emitted when the identity hash associated with a verified address is updated. - * @param addr The address whose hash was updated. - * @param oldHash The identity hash that was associated with the address. - * @param hash The hash now associated with the address. - * @param sender The address that caused the hash to be updated. - */ - event VerifiedAddressUpdated( - address indexed addr, - bytes32 oldHash, - bytes32 hash, - address indexed sender - ); - - /** - * This event is emitted when an address is cancelled and replaced with - * a new address. This happens in the case where a shareholder has - * lost access to their original address and needs to have their share - * reissued to a new address. This is the equivalent of issuing replacement - * share certificates. - * @param original The address being superseded. - * @param replacement The new address. - * @param sender The address that caused the address to be superseded. - */ - event VerifiedAddressSuperseded( - address indexed original, - address indexed replacement, - address indexed sender - ); - - /** - * Add a verified address, along with an associated verification hash to the contract. - * Upon successful addition of a verified address, the contract must emit - * `VerifiedAddressAdded(addr, hash, msg.sender)`. - * It MUST throw if the supplied address or hash are zero, or if the address has already been supplied. - * @param addr The address of the person represented by the supplied hash. - * @param hash A cryptographic hash of the address holder's verified information. - */ - function addVerified(address addr, bytes32 hash) public; - - /** - * Remove a verified address, and the associated verification hash. If the address is - * unknown to the contract then this does nothing. If the address is successfully removed, this - * function must emit `VerifiedAddressRemoved(addr, msg.sender)`. - * It MUST throw if an attempt is made to remove a verifiedAddress that owns tokens. - * @param addr The verified address to be removed. - */ - function removeVerified(address addr) public; - - /** - * Update the hash for a verified address known to the contract. - * Upon successful update of a verified address the contract must emit - * `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`. - * If the hash is the same as the value already stored then - * no `VerifiedAddressUpdated` event is to be emitted. - * It MUST throw if the hash is zero, or if the address is unverified. - * @param addr The verified address of the person represented by the supplied hash. - * @param hash A new cryptographic hash of the address holder's updated verified information. - */ - function updateVerified(address addr, bytes32 hash) public; - - /** - * Cancel the original address and reissue the tokens to the replacement address. - * Access to this function MUST be strictly controlled. - * The `original` address MUST be removed from the set of verified addresses. - * Throw if the `original` address supplied is not a shareholder. - * Throw if the `replacement` address is not a verified address. - * Throw if the `replacement` address already holds tokens. - * This function MUST emit the `VerifiedAddressSuperseded` event. - * @param original The address to be superseded. This address MUST NOT be reused. - */ - function cancelAndReissue(address original, address replacement) public; - - /** - * The `transfer` function MUST NOT allow transfers to addresses that - * have not been verified and added to the contract. - * If the `to` address is not currently a shareholder then it MUST become one. - * If the transfer will reduce `msg.sender`'s balance to 0 then that address - * MUST be removed from the list of shareholders. - */ - function transfer(address to, uint256 value) public returns (bool); - - /** - * The `transferFrom` function MUST NOT allow transfers to addresses that - * have not been verified and added to the contract. - * If the `to` address is not currently a shareholder then it MUST become one. - * If the transfer will reduce `from`'s balance to 0 then that address - * MUST be removed from the list of shareholders. - */ - function transferFrom(address from, address to, uint256 value) public returns (bool); - - /** - * Tests that the supplied address is known to the contract. - * @param addr The address to test. - * @return true if the address is known to the contract. - */ - function isVerified(address addr) public view returns (bool); - - /** - * Checks to see if the supplied address is a shareholder. - * @param addr The address to check. - * @return true if the supplied address owns a token. - */ - function isHolder(address addr) public view returns (bool); - - /** - * Checks that the supplied hash is associated with the given address. - * @param addr The address to test. - * @param hash The hash to test. - * @return true if the hash matches the one supplied with the address in `addVerified`, or `updateVerified`. - */ - function hasHash(address addr, bytes32 hash) public view returns (bool); - - /** - * The number of addresses that hold tokens. - * @return the number of unique addresses that hold tokens. - */ - function holderCount() public view returns (uint); - - /** - * By counting the number of token holders using `holderCount` - * you can retrieve the complete list of token holders, one at a time. - * It MUST throw if `index >= holderCount()`. - * @param index The zero-based index of the holder. - * @return the address of the token holder with the given index. - */ - function holderAt(uint256 index) public view returns (address); - - /** - * Checks to see if the supplied address was superseded. - * @param addr The address to check. - * @return true if the supplied address was superseded by another address. - */ - function isSuperseded(address addr) public view returns (bool); - - /** - * Gets the most recent address, given a superseded one. - * Addresses may be superseded multiple times, so this function needs to - * follow the chain of addresses until it reaches the final, verified address. - * @param addr The superseded address. - * @return the verified address that ultimately holds the share. - */ - function getCurrentFor(address addr) public view returns (address); - } - -### Securities Exchange Commission Requirements - -The Securities Exchange Commission (SEC) has additional requirements as to how a crowdsale ought to be run and what information must be made available to the general public. This information is however out of scope from this standard, though the standard does support the requirements. - -For example: The SEC requires a crowdsale's website display the amount of money raised in US Dollars. To support this a crowdsale contract minting these tokens must maintain a USD to ETH conversion rate (via Oracle or some other mechanism) and must record the conversion rate used at time of minting. - -Also, depending on the type of raise, the SEC (or other statutory body) can apply limits to the number of shareholders allowed. To support this the standard provides the `holderCount` and `isHolder` functions which a crowdsale can invoke to check that limits have not been exceeded. - -### Use of the Identity `hash` value - -Implementers of a crowdsale, in order to comply with The Act, must be able to produce an up-to-date list of the names and addresses of all shareholders. It is not desirable to include those details in a public blockchain, both for reasons of privacy, and also for reasons of economy. Storing arbitrary string data on the blockchain is strongly discouraged. - -Implementers should maintain an off-chain private database that records the owner's name, residential address, and Ethereum address. The implementer must then be able to extract the name and address for any address, and hash the name + address data and compare that hash to the hash recorded in the contract using the `hasHash` function. The specific details of this system are left to the implementer. - -It is also desirable that the implementers offer a REST API endpoint along the lines of - - GET https:////:ethereumAddress -> [true|false] - -to enable third party auditors to verify that a given Ethereum address is known to the implementers as a verified address. - -How the implementers verify a person's identity is up to them and beyond the scope of this standard. - -### Handling users who have lost access to their addresses - -A traditional share register is typically managed by a Transfer Agent who is authorised to maintain the register accurately, and to handle shareholder enquiries. A common request is for share certificates to be reissued in the case where the shareholder has lost or destroyed their original. - -Token implementers can handle that via the `cancelAndReissue` function, which must perform the various changes to ensure that the old address now points to the new one, and that cancelled addresses are not then reused. - -### Permissions management - -It is not desirable that anyone can add, remove, update, or supersede verified addresses. How access to these functions is controlled is outside of the scope of this standard. - -## Rationale - -The proposed standard offers as minimal an extension as possible over the existing `ERC-20` standard in order to conform to the requirements of The Act. Rather than return a `bool` for successful or unsuccessful completion of state-changing functions such as `addVerified`, `removeVerified`, and `updateVerified`, we have opted to require that implementations `throw` (preferably by using the [forthcoming `require(condition, 'fail message')` syntax](https://github.com/ethereum/solidity/issues/1686#issuecomment-328181514)). - -## Backwards Compatibility - -The proposed standard is designed to maintain compatibility with `ERC-20` tokens with the following provisos: - -1. The `decimals` function MUST return `0` as the tokens MUST NOT be divisible, -2. The `transfer` and `transferFrom` functions MUST NOT allow transfers to non-verified addresses, and MUST maintain a list of shareholders. -3. Shareholders who transfer away their remaining tokens must be pruned from the list of shareholders. - -Proviso 1 will not break compatibility with modern wallets or exchanges as they all appear to use that information if available. - -Proviso 2 will cause transfers to fail if an attempt is made to transfer tokens to a non-verified address. This is implicit in the design and implementers are encouraged to make this abundantly clear to market participants. We appreciate that this will make the standard unpalatable to some exchanges, but it is an SEC requirement that shareholders of a corporation provide verified names and addresses. - -Proviso 3 is an implementation detail. - -## Test Cases and Reference Implementation - -Test cases and a reference implementation are available at [github.com/davesag/ERC884-reference-implementation](https://github.com/davesag/ERC884-reference-implementation). - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-884.md diff --git a/EIPS/eip-897.md b/EIPS/eip-897.md index c5bb3c05a77d61..6068c1a9dca7d1 100644 --- a/EIPS/eip-897.md +++ b/EIPS/eip-897.md @@ -1,73 +1,7 @@ --- eip: 897 -title: DelegateProxy -author: Jorge Izquierdo , Manuel Araoz -type: Standards Track category: ERC -status: Stagnant -created: 2018-02-21 -discussions-to: https://github.com/ethereum/EIPs/pull/897 +status: Moved --- -## Simple Summary -Proxy contracts are being increasingly used as both as an upgradeability mechanism -and a way to save gas when deploying many instances of a particular contract. This -standard proposes a set of interfaces for proxies to signal how they work and what -their main implementation is. - -## Abstract -Using proxies that delegate their own logic to another contract is becoming an -increasingly popular technique for both smart contract upgradeability and creating -cheap clone contracts. - -We don't believe there is value in standardizing any particular implementation -of a DelegateProxy, given its simplicity, but we believe there is a lot of value -in agreeing on an interface all proxies use that allows for a standard way to -operate with proxies. - -## Implementations - -- **aragonOS**: [AppProxyUpgradeable](https://github.com/aragon/aragonOS/blob/master/contracts/apps/AppProxyUpgradeable.sol), [AppProxyPinned](https://github.com/aragon/aragonOS/blob/master/contracts/apps/AppProxyPinned.sol) and [KernelProxy](https://github.com/aragon/aragonOS/blob/master/contracts/kernel/KernelProxy.sol) - -- **zeppelinOS**: [Proxy](https://github.com/zeppelinos/labs/blob/2da9e859db81a61f2449d188e7193788ca721c65/upgradeability_ownership/contracts/Proxy.sol) - -## Standardized interface - -```solidity -interface ERCProxy { - function proxyType() public pure returns (uint256 proxyTypeId); - function implementation() public view returns (address codeAddr); -} -``` - -### Code address (`implementation()`) -The returned code address is the address the proxy would delegate calls to at that -moment in time, for that message. - -### Proxy Type (`proxyType()`) - -Checking the proxy type is the way to check whether a contract is a proxy at all. -When a contract fails to return to this method or it returns 0, it can be assumed -that the contract is not a proxy. - -It also allows for communicating a bit more of information about how the proxy -operates. It is a pure function, therefore making it effectively constant as -it cannot return a different value depending on state changes. - -- **Forwarding proxy** (`id = 1`): The proxy will always forward to the same code -address. The following invariant should always be true: once the proxy returns -a non-zero code address, that code address should never change. - -- **Upgradeable proxy** (`id = 2`): The proxy code address can be changed depending -on some arbitrary logic implemented either at the proxy level or in its forwarded -logic. - -## Benefits - -- **Source code verification**: right now when checking the code of a proxy in explorers -like Etherscan, it just shows the code in the proxy itself but not the actual -code of the contract. By standardizing this construct, they will be able to show -both the actual ABI and code for the contract. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-897.md diff --git a/EIPS/eip-900.md b/EIPS/eip-900.md index 4333f2161229e6..199f5f472c2d40 100644 --- a/EIPS/eip-900.md +++ b/EIPS/eip-900.md @@ -1,109 +1,7 @@ --- eip: 900 -title: Simple Staking Interface -author: Dean Eigenmann , Jorge Izquierdo -type: Standards Track category: ERC -status: Stagnant -created: 2018-02-22 -discussions-to: https://github.com/ethereum/EIPs/issues/900 +status: Moved --- -## Abstract - -The following standard describes a common staking interface allowing for easy to use staking systems. The interface is kept simple allowing for various use cases to be implemented. This standard describes the common functionality for staking as well as providing information on stakes. - -## Motivation - -As we move to more token models, having a common staking interface which is familiar to users can be useful. The common interface can be used by a variety of applications, this common interface could be beneficial especially to things like Token curated registries which have recently gained popularity. - -## Specification - -```solidity -interface Staking { - - event Staked(address indexed user, uint256 amount, uint256 total, bytes data); - event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); - - function stake(uint256 amount, bytes data) public; - function stakeFor(address user, uint256 amount, bytes data) public; - function unstake(uint256 amount, bytes data) public; - function totalStakedFor(address addr) public view returns (uint256); - function totalStaked() public view returns (uint256); - function token() public view returns (address); - function supportsHistory() public pure returns (bool); - - // optional - function lastStakedFor(address addr) public view returns (uint256); - function totalStakedForAt(address addr, uint256 blockNumber) public view returns (uint256); - function totalStakedAt(uint256 blockNumber) public view returns (uint256); -} -``` - -### stake - -Stakes a certain amount of tokens, this MUST transfer the given amount from the user. - -*The data field can be used to add signalling information in more complex staking applications* - -MUST trigger ```Staked``` event. - -### stakeFor - -Stakes a certain amount of tokens, this MUST transfer the given amount from the caller. - -*The data field can be used to add signalling information in more complex staking applications* - -MUST trigger ```Staked``` event. - -### unstake - -Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert. - -*The data field can be used to remove signalling information in more complex staking applications* - -MUST trigger ```Unstaked``` event. - -### totalStakedFor - -Returns the current total of tokens staked for an address. - -### totalStaked - -Returns the current total of tokens staked. - -### token - -Address of the token being used by the staking interface. - -### supportsHistory - -MUST return true if the optional history functions are implemented, otherwise false. - -### lastStakedFor - -***OPTIONAL:** As not all staking systems require a complete history, this function is optional.* - -Returns last block address staked at. - -### totalStakedForAt - -***OPTIONAL:** As not all staking systems require a complete history, this function is optional.* - -Returns total amount of tokens staked at block for address. - -### totalStakedAt - -***OPTIONAL:** As not all staking systems require a complete history, this function is optional.* - -Returns the total tokens staked at block. - -## Implementation - -- [Stakebank](https://github.com/HarbourProject/stakebank) -- [Aragon](https://github.com/aragon/aragon-apps/pull/101) -- [PoS Staking](https://github.com/maticnetwork/contracts/blob/master/contracts/StakeManager.sol) -- [BasicStakeContract](https://github.com/codex-protocol/contract.erc-900) - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-900.md diff --git a/EIPS/eip-902.md b/EIPS/eip-902.md index c7b67b4cc921ad..e7bae5b19d9858 100644 --- a/EIPS/eip-902.md +++ b/EIPS/eip-902.md @@ -1,153 +1,7 @@ --- eip: 902 -title: Token Validation -author: Brooklyn Zelenka (@expede), Tom Carchrae (@carchrae), Gleb Naumenko (@naumenkogs) -discussions-to: https://ethereum-magicians.org/t/update-on-erc902-validated-token/1639 -type: Standards Track category: ERC -status: Stagnant -created: 2018-02-14 -requires: 1066 +status: Moved --- -# Simple Summary -A protocol for services providing token ownership and transfer validation. - -# Abstract -This standard provides a registry contract method for authorizing token transfers. By nature, this covers both initially issuing tokens to users (ie: transfer from contract to owner), transferring tokens between users, and token spends. - -# Motivation -The tokenization of assets has wide application, not least of which is financial instruments such as securities and security tokens. Most jurisdictions have placed legal constraints on what may be traded, and who can hold such tokens which are regarded as securities. Broadly this includes KYC and AML validation, but may also include time-based spend limits, total volume of transactions, and so on. - -Regulators and sanctioned third-party compliance agencies need some way to link off-chain compliance information such as identity and residency to an on-chain service. The application of this design is broader than legal regulation, encompassing all manner of business logic permissions for the creation, management, and trading of tokens. - -Rather than each token maintaining its own whitelist (or other mechanism), it is preferable to share on-chain resources, rules, lists, and so on. There is also a desire to aggregate data and rules spread across multiple validators, or to apply complex behaviours (ex. switching logic, gates, state machines) to apply distributed data to an application. - -# Specification - -## `TokenValidator` - -```solidity -interface TokenValidator { - function check( - address _token, - address _subject - ) public returns(byte statusCode) - - function check( - address _token, - address _from, - address _to, - uint256 _amount - ) public returns (byte statusCode) -} -``` - -### Methods - -#### `check`/2 - -`function check(address _token, address _subject) public returns (byte _resultCode)` - -> parameters -> * `_token`: the token under review -> * `_subject`: the user or contract to check -> -> *returns* an ERC1066 status code - -#### `check`/4 - -`function check(address token, address from, address to, uint256 amount) public returns (byte resultCode)` - -> parameters -> * `_token`: the token under review -> * `_from`: in the case of a transfer, who is relinquishing token ownership -> * `_to`: in the case of a transfer, who is accepting token ownership -> * `_amount`: The number of tokens being transferred -> -> *returns* an ERC1066 status code - -## `ValidatedToken` - -```solidity -interface ValidatedToken { - event Validation( - address indexed subject, - byte indexed result - ) - - event Validation( - address indexed from, - address indexed to, - uint256 value, - byte indexed statusCode - ) -} -``` - -### Events - -#### `Validation`/2 - -`event Validation(address indexed subject, byte indexed resultCode)` - -This event MUST be fired on return from a call to a `TokenValidator.check/2`. - -> parameters -> * `subject`: the user or contract that was checked -> * `statusCode`: an ERC1066 status code - - -#### `Validation`/4 - -```solidity -event Validation( - address indexed from, - address indexed to, - uint256 amount, - byte indexed statusCode -) -``` - -This event MUST be fired on return from a call to a `TokenValidator.check/4`. - -> parameters -> * `from`: in the case of a transfer, who is relinquishing token ownership -> * `to`: in the case of a transfer, who is accepting token ownership -> * `amount`: The number of tokens being transferred -> * `statusCode`: an ERC1066 status code - -# Rationale - -This proposal includes a financial permissions system on top of any financial token. This design is not a general roles/permission system. In any system, the more you know about the context where a function will be called, the more powerful your function can be. By restricting ourselves to token transfers (ex. ERC20 or EIP-777), we can make assumptions about the use cases our validators will need to handle, and can make the API both small, useful, and extensible. - -The events are fired by the calling token. Since `Validator`s may aggregate or delegate to other `Validator`s, it would generate a lot of useless events were it the -`Validator`'s responsibility. This is also the reason why we include the `token` in the `call/4` arguments: a `Validator` cannot rely on `msg.sender` to determine the token that the call is concerning. - -We have also seen a similar design from [R-Token](https://github.com/harborhq/r-token) that uses an additional field: `spender`. While there are potential use cases for this, it's not widely used enough to justify passing a dummy value along with every call. Instead, such a call would look more like this: - -```solidity -function approve(address spender, uint amount) public returns (bool success) { - if (validator.check(this, msg.sender, spender, amount) == okStatusCode) { - allowed[msg.sender][spender] = amount; - Approval(msg.sender, spender, amount); - return true; - } else { - return false; - } -} -``` - -A second `check/2` function is also required, that is more general-purpose, and does not specify a transfer amount or recipient. This is intended for general checks, such as checking roles (admin, owner, &c), or if a user is on a simple whitelist. - -We have left the decision to make associated `Validator` addresses public, private, or hardcoded up to the implementer. The proposed design does not include a centralized registry. It also does not include an interface for a `Validated` contract. A token may require one or many `Validator`s for different purposes, requiring different validations for different, or just a single `Validator`. The potential use cases are too varied to provide a single unified set of methods. We have provided a set of example contracts [here](https://github.com/Finhaven/ValidatedToken/) that may be inherited from for common use cases. - -The status codes in the `byte` returns are unspecified. Any status code scheme may be used, though a general status code proposal is fortcoming. - -By only defining the validation check, this standard is widely compatible with ERC-20, EIP-721, EIP-777, future token standards, centralized and decentralized exchanges, and so on. - -# Implementation -[Reference implementation](https://github.com/expede/validated-token/) - -# Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-902.md diff --git a/EIPS/eip-908.md b/EIPS/eip-908.md index 67725b7f818c56..a019b67bd84e29 100644 --- a/EIPS/eip-908.md +++ b/EIPS/eip-908.md @@ -91,7 +91,7 @@ Now, as to the ratio of rewards to the client vs the full node, as an initial gu However, on further analysis, clients would also get the benefit of a large volume of rewards from every full node running the client, so to incentivise full node operation further, the ratio could change to say, 4:1, or even 1:1, and of course could be adjusted with even further actual data analysis, rather than speculation. -Providing rewards to full node validators and to clients would increase the issuance. In order to maintain the issuance at current levels, this EIP could also reduce the mining reward (despite being reduced previously with the Byzantium release in October 2017 from 5 ETH to 3 ETH), but that would generate more controversy and discusssion. +Providing rewards to full node validators and to clients would increase the issuance. In order to maintain the issuance at current levels, this EIP could also reduce the mining reward (despite being reduced previously with the Byzantium release in October 2017 from 5 ETH to 3 ETH), but that would generate more controversy and discussion. Another potential point of controversy with rewarding clients and full nodes is that the work previously done by them has not been paid for until now (except of course by the Ethereum Foundation or Parity VCs funding the work), so existing clients may say that this EIP gives an advantage to new entrants. However, this doesn't hold up well, because existing clients have the first mover advantage, with much development to create useful and well-used products. diff --git a/EIPS/eip-918.md b/EIPS/eip-918.md index cc6e0d0aaad016..066bbdff48b4bc 100644 --- a/EIPS/eip-918.md +++ b/EIPS/eip-918.md @@ -1,479 +1,7 @@ --- eip: 918 -title: Mineable Token Standard -author: Jay Logelin , Infernal_toast , Michael Seiler , Brandon Grill -type: Standards Track category: ERC -status: Stagnant -created: 2018-03-07 +status: Moved --- - -### Simple Summary - -A specification for a standardized Mineable Token that uses a Proof of Work algorithm for distribution. - -### Abstract - -This specification describes a method for initially locking tokens within a token contract and slowly dispensing them with a mint() function which acts like a faucet. This mint() function uses a Proof of Work algorithm in order to minimize gas fees and control the distribution rate. Additionally, standardization of mineable tokens will give rise to standardized CPU and GPU token mining software, token mining pools and other external tools in the token mining ecosystem. - -### Motivation - -Token distribution via the ICO model and its derivatives is susceptible to illicit behavior by human actors. Furthermore, new token projects are centralized because a single entity must handle and control all of the initial coins and all of the raised ICO money. By distributing tokens via an 'Initial Mining Offering' (or IMO), the ownership of the token contract no longer belongs with the deployer at all and the deployer is 'just another user.' As a result, investor risk exposure utilizing a mined token distribution model is significantly diminished. This standard is intended to be standalone, allowing maximum interoperability with ERC20, ERC721, and others. - -### Specification - -#### Interface -The general behavioral specification includes a primary function that defines the token minting operation, an optional merged minting operation for issuing multiple tokens, getters for challenge number, mining difficulty, mining target and current reward, and finally a Mint event, to be emitted upon successful solution validation and token issuance. At a minimum, contracts must adhere to this interface (save the optional merge operation). It is recommended that contracts interface with the more behaviorally defined Abstract Contract described below, in order to leverage a more defined construct, allowing for easier external implementations via overridden phased functions. (see 'Abstract Contract' below) - -``` solidity -interface ERC918 { - - function mint(uint256 nonce) public returns (bool success); - - function getAdjustmentInterval() public view returns (uint); - - function getChallengeNumber() public view returns (bytes32); - - function getMiningDifficulty() public view returns (uint); - - function getMiningTarget() public view returns (uint); - - function getMiningReward() public view returns (uint); - - function decimals() public view returns (uint8); - - event Mint(address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallengeNumber); -} -``` - -#### Abstract Contract (Optional) - -The Abstract Contract adheres to the EIP918 Interface and extends behavioral definition through the introduction of 4 internal phases of token mining and minting: hash, reward, epoch and adjust difficulty, all called during the mint() operation. This construct provides a balance between being too general for use while providing ample room for multiple mined implementation types. - -### Fields - -#### adjustmentInterval -The amount of time between difficulty adjustments in seconds. - -``` solidity -bytes32 public adjustmentInterval; -``` - -#### challengeNumber -The current challenge number. It is expected that a new challenge number is generated after a new reward is minted. - -``` solidity -bytes32 public challengeNumber; -``` - -#### difficulty -The current mining difficulty which should be adjusted via the \_adjustDifficulty minting phase - -``` solidity -uint public difficulty; -``` - -#### tokensMinted -Cumulative counter of the total minted tokens, usually modified during the \_reward phase - -``` solidity -uint public tokensMinted; -``` - -#### epochCount -Number of 'blocks' mined - -``` solidity -uint public epochCount; -``` - -### Mining Operations - -#### mint - -Returns a flag indicating a successful hash digest verification, and reward allocation to msg.sender. In order to prevent MiTM attacks, it is recommended that the digest include a recent Ethereum block hash and msg.sender's address. Once verified, the mint function calculates and delivers a mining reward to the sender and performs internal accounting operations on the contract's supply. - -The mint operation exists as a public function that invokes 4 separate phases, represented as functions hash, \_reward, \_newEpoch, and \_adjustDifficulty. In order to create the most flexible implementation while adhering to a necessary contract protocol, it is recommended that token implementors override the internal methods, allowing the base contract to handle their execution via mint. - -This externally facing function is called by miners to validate challenge digests, calculate reward, -populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, -a Mint event is emitted before returning a boolean success flag. - -``` solidity -contract AbstractERC918 is EIP918Interface { - - // the amount of time between difficulty adjustments - uint public adjustmentInterval; - - // generate a new challenge number after a new reward is minted - bytes32 public challengeNumber; - - // the current mining target - uint public miningTarget; - - // cumulative counter of the total minted tokens - uint public tokensMinted; - - // number of blocks per difficulty readjustment - uint public blocksPerReadjustment; - - //number of 'blocks' mined - uint public epochCount; - - /* - * Externally facing mint function that is called by miners to validate challenge digests, calculate reward, - * populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, - * a Mint event is emitted before returning a success indicator. - **/ - function mint(uint256 nonce) public returns (bool success) { - require(msg.sender != address(0)); - - // perform the hash function validation - hash(nonce); - - // calculate the current reward - uint rewardAmount = _reward(); - - // increment the minted tokens amount - tokensMinted += rewardAmount; - - epochCount = _epoch(); - - //every so often, readjust difficulty. Don't readjust when deploying - if(epochCount % blocksPerReadjustment == 0){ - _adjustDifficulty(); - } - - // send Mint event indicating a successful implementation - emit Mint(msg.sender, rewardAmount, epochCount, challengeNumber); - - return true; - } -} -``` - -##### *Mint Event* - -Upon successful verification and reward the mint method dispatches a Mint Event indicating the reward address, the reward amount, the epoch count and newest challenge number. - -``` solidity -event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); -``` - -#### hash - -Public interface function hash, meant to be overridden in implementation to define hashing algorithm and validation. Returns the validated digest - -``` solidity -function hash(uint256 nonce) public returns (bytes32 digest); -``` - -#### \_reward - -Internal interface function \_reward, meant to be overridden in implementation to calculate and allocate the reward amount. The reward amount must be returned by this method. - -``` solidity -function _reward() internal returns (uint); -``` - -#### \_newEpoch - -Internal interface function \_newEpoch, meant to be overridden in implementation to define a cutpoint for mutating mining variables in preparation for the next phase of mine. - -``` solidity -function _newEpoch(uint256 nonce) internal returns (uint); -``` - -#### \_adjustDifficulty - -Internal interface function \_adjustDifficulty, meant to be overridden in implementation to adjust the difficulty (via field difficulty) of the mining as required - -``` solidity -function _adjustDifficulty() internal returns (uint); -``` - -#### getAdjustmentInterval - -The amount of time, in seconds, between difficulty adjustment operations. - -``` solidity -function getAdjustmentInterval() public view returns (uint); -``` - -#### getChallengeNumber - -Recent ethereum block hash, used to prevent pre-mining future blocks. - -``` solidity -function getChallengeNumber() public view returns (bytes32); -``` - -#### getMiningDifficulty - -The number of digits that the digest of the PoW solution requires which typically auto adjusts during reward generation. - -``` solidity -function getMiningDifficulty() public view returns (uint) -``` - -#### getMiningReward - -Return the current reward amount. Depending on the algorithm, typically rewards are divided every reward era as tokens are mined to provide scarcity. - -``` solidity -function getMiningReward() public view returns (uint) -``` - -### Example mining function -A general mining function written in python for finding a valid nonce for keccak256 mined token, is as follows: -``` python -def generate_nonce(): - myhex = b'%064x' % getrandbits(32*8) - return codecs.decode(myhex, 'hex_codec') - -def mine(challenge, public_address, difficulty): - while True: - nonce = generate_nonce() - hash1 = int(sha3.keccak_256(challenge+public_address+nonce).hexdigest(), 16) - if hash1 < difficulty: - return nonce, hash1 -``` - -Once the nonce and hash1 are found, these are used to call the mint() function of the smart contract to receive a reward of tokens. - -### Merged Mining Extension (Optional) -In order to provide support for merge mining multiple tokens, an optional merged mining extension can be implemented as part of the ERC918 standard. It is important to note that the following function will only properly work if the base contracts use tx.origin instead of msg.sender when applying rewards. If not the rewarded tokens will be sent to the calling contract and not the end user. - -``` solidity -/** - * @title ERC-918 Mineable Token Standard, optional merged mining functionality - * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-918.md - * - */ -contract ERC918Merged is AbstractERC918 { - /* - * @notice Externally facing merge function that is called by miners to validate challenge digests, calculate reward, - * populate statistics, mutate state variables and adjust the solution difficulty as required. Additionally, the - * merge function takes an array of target token addresses to be used in merged rewards. Once complete, - * a Mint event is emitted before returning a success indicator. - * - * @param _nonce the solution nonce - **/ - function merge(uint256 _nonce, address[] _mineTokens) public returns (bool) { - for (uint i = 0; i < _mineTokens.length; i++) { - address tokenAddress = _mineTokens[i]; - ERC918Interface(tokenAddress).mint(_nonce); - } - } - - /* - * @notice Externally facing merge function kept for backwards compatibility with previous definition - * - * @param _nonce the solution nonce - * @param _challenge_digest the keccak256 encoded challenge number + message sender + solution nonce - **/ - function merge(uint256 _nonce, bytes32 _challenge_digest, address[] _mineTokens) public returns (bool) { - //the challenge digest must match the expected - bytes32 digest = keccak256( abi.encodePacked(challengeNumber, msg.sender, _nonce) ); - require(digest == _challenge_digest, "Challenge digest does not match expected digest on token contract [ ERC918Merged.mint() ]"); - return merge(_nonce, _mineTokens); - } -} -``` - -### Delegated Minting Extension (Optional) -In order to facilitate a third party minting submission paradigm, such as the case of miners submitting solutions to a pool operator and/or system, a delegated minting extension can be used to allow pool accounts submit solutions on the behalf of a user, so the miner can avoid directly paying Ethereum transaction costs. This is performed by an off chain mining account packaging and signing a standardized mint solution packet and sending it to a pool or 3rd party to be submitted. - -The ERC918 Mineable Mint Packet Metadata should be prepared using following schema: -``` solidity -{ - "title": "Mineable Mint Packet Metadata", - "type": "object", - "properties": { - "nonce": { - "type": "string", - "description": "Identifies the target solution nonce", - }, - "origin": { - "type": "string", - "description": "Identifies the original user that mined the solution nonce", - }, - "signature": { - "type": "string", - "description": "The signed hash of tightly packed variables sha3('delegatedMintHashing(uint256,address)')+nonce+origin_account", - } - } -} -``` -The preparation of a mineable mint packet on a JavaScript client would appear as follows: - -``` solidity -function prepareDelegatedMintTxn(nonce, account) { - var functionSig = web3.utils.sha3("delegatedMintHashing(uint256,address)").substring(0,10) - var data = web3.utils.soliditySha3( functionSig, nonce, account.address ) - var sig = web3.eth.accounts.sign(web3.utils.toHex(data), account.privateKey ) - // prepare the mint packet - var packet = {} - packet.nonce = nonce - packet.origin = account.address - packet.signature = sig.signature - // deliver resulting JSON packet to pool or third party - var mineableMintPacket = JSON.stringify(packet, null, 4) - /* todo: send mineableMintPacket to submitter */ - ... -} -``` -Once the packet is prepared and formatted it can then be routed to a third party that will submit the transaction to the contract's delegatedMint() function, thereby paying for the transaction gas and receiving the resulting tokens. The pool/third party must then manually payback the minted tokens minus fees to the original minter. - -The following code sample exemplifies third party packet relaying: -``` solidity -//received by minter -var mineableMintPacket = ... -var packet = JSON.parse(mineableMintPacket) -erc918MineableToken.delegatedMint(packet.nonce, packet.origin, packet.signature) -``` -The Delegated Mint Extension expands upon ERC918 realized as a sub-contract: -``` js -import 'openzeppelin-solidity/contracts/contracts/cryptography/ECDSA.sol'; - -contract ERC918DelegatedMint is AbstractERC918, ECDSA { - /** - * @notice Hash (keccak256) of the payload used by delegatedMint - * @param _nonce the golden nonce - * @param _origin the original minter - * @param _signature the original minter's elliptical curve signature - */ - function delegatedMint(uint256 _nonce, address _origin, bytes _signature) public returns (bool success) { - bytes32 hashedTx = delegatedMintHashing(_nonce, _origin); - address minter = recover(hashedTx, _signature); - require(minter == _origin, "Origin minter address does not match recovered signature address [ AbstractERC918.delegatedMint() ]"); - require(minter != address(0), "Invalid minter address recovered from signature [ ERC918DelegatedMint.delegatedMint() ]"); - success = mintInternal(_nonce, minter); - } - - /** - * @notice Hash (keccak256) of the payload used by delegatedMint - * @param _nonce the golden nonce - * @param _origin the original minter - */ - function delegatedMintHashing(uint256 _nonce, address _origin) public pure returns (bytes32) { - /* "0x7b36737a": delegatedMintHashing(uint256,address) */ - return toEthSignedMessageHash(keccak256(abi.encodePacked( bytes4(0x7b36737a), _nonce, _origin))); - } -} -``` - -### Mineable Token Metadata (Optional) -In order to provide for richer and potentially mutable metadata for a particular Mineable Token, it is more viable to offer an off-chain reference to said data. This requires the implementation of a single interface method 'metadataURI()' that returns a JSON string encoded with the string fields symbol, name, description, website, image, and type. - -Solidity interface for Mineable Token Metadata: -``` solidity -/** - * @title ERC-918 Mineable Token Standard, optional metadata extension - * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-918.md - * - */ -interface ERC918Metadata is AbstractERC918 { - /** - * @notice A distinct Uniform Resource Identifier (URI) for a mineable asset. - */ - function metadataURI() external view returns (string); -} -``` - -Mineable Token Metadata JSON schema definition: -``` solidity -{ - "title": "Mineable Token Metadata", - "type": "object", - "properties": { - "symbol": { - "type": "string", - "description": "Identifies the Mineable Token's symbol", - }, - "name": { - "type": "string", - "description": "Identifies the Mineable Token's name", - }, - "description": { - "type": "string", - "description": "Identifies the Mineable Token's long description", - }, - "website": { - "type": "string", - "description": "Identifies the Mineable Token's homepage URI", - }, - "image": { - "type": "string", - "description": "Identifies the Mineable Token's image URI", - }, - "type": { - "type": "string", - "description": "Identifies the Mineable Token's hash algorithm ( ie.keccak256 ) used to encode the solution", - } - } -} -``` - -### Rationale - -The solidity keccak256 algorithm does not have to be used, but it is recommended since it is a cost effective one-way algorithm to perform in the EVM and simple to perform in solidity. The nonce is the solution that miners try to find and so it is part of the hashing algorithm. A challengeNumber is also part of the hash so that future blocks cannot be mined since it acts like a random piece of data that is not revealed until a mining round starts. The msg.sender address is part of the hash so that a nonce solution is valid only for a particular Ethereum account and so the solution is not susceptible to man-in-the-middle attacks. This also allows pools to operate without being easily cheated by the miners since pools can force miners to mine using the pool's address in the hash algorithm. - -The economics of transferring electricity and hardware into mined token assets offers a flourishing community of decentralized miners the option to be involved in the Ethereum token economy directly. By voting with hash power, an economically pegged asset to real-world resources, miners are incentivized to participate in early token trade to revamp initial costs, providing a bootstrapped stimulus mechanism between miners and early investors. - -One community concern for mined tokens has been around energy use without a function for securing a network. Although token mining does not secure a network, it serves the function of securing a community from corruption as it offers an alternative to centralized ICOs. Furthermore, an initial mining offering may last as little as a week, a day, or an hour at which point all of the tokens would have been minted. - - -### Backwards Compatibility -Earlier versions of this standard incorporated a redundant 'challenge_digest' parameter on the mint() function that hash-encoded the packed variables challengeNumber, msg.sender and nonce. It was decided that this could be removed from the standard to help minimize processing and thereby gas usage during mint operations. However, in the name of interoperability with existing mining programs and pool software the following contract can be added to the inheritance tree: - -``` solidity -/** - * @title ERC-918 Mineable Token Standard, optional backwards compatibility function - * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-918.md - * - */ -contract ERC918BackwardsCompatible is AbstractERC918 { - - /* - * @notice Externally facing mint function kept for backwards compatibility with previous mint() definition - * @param _nonce the solution nonce - * @param _challenge_digest the keccak256 encoded challenge number + message sender + solution nonce - **/ - function mint(uint256 _nonce, bytes32 _challenge_digest) public returns (bool success) { - //the challenge digest must match the expected - bytes32 digest = keccak256( abi.encodePacked(challengeNumber, msg.sender, _nonce) ); - require(digest == _challenge_digest, "Challenge digest does not match expected digest on token contract [ AbstractERC918.mint() ]"); - success = mint(_nonce); - } -} -``` - -### Test Cases -(Test cases for an implementation are mandatory for EIPs that are affecting consensus changes. Other EIPs can choose to include links to test cases if applicable.) - - -### Implementation - -Simple Example: -https://github.com/0xbitcoin/EIP918-Mineable-Token/blob/master/contracts/SimpleERC918.sol - -Complex Examples: - -https://github.com/0xbitcoin/EIP918-Mineable-Token/blob/master/contracts/0xdogeExample.sol -https://github.com/0xbitcoin/EIP918-Mineable-Token/blob/master/contracts/0xdogeExample2.sol -https://github.com/0xbitcoin/EIP918-Mineable-Token/blob/master/contracts/0xBitcoinBase.sol - -0xBitcoin Token Contract: -https://etherscan.io/address/0xb6ed7644c69416d67b522e20bc294a9a9b405b31 - -MVI OpenCL Token Miner -https://github.com/mining-visualizer/MVis-tokenminer/releases - -PoWAdv Token Contract: -https://etherscan.io/address/0x1a136ae98b49b92841562b6574d1f3f5b0044e4c - - -### Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-918.md diff --git a/EIPS/eip-926.md b/EIPS/eip-926.md index f5f25087577ecc..f7d48b174b68aa 100644 --- a/EIPS/eip-926.md +++ b/EIPS/eip-926.md @@ -1,73 +1,7 @@ --- eip: 926 -title: Address metadata registry -author: Nick Johnson -type: Standards Track category: ERC -status: Stagnant -created: 2018-03-12 -requires: 165 +status: Moved --- -## Abstract -This EIP specifies a registry for address metadata, permitting both contracts and external accounts to supply metadata about themselves to onchain and offchain callers. This permits use-cases such as generalised authorisations, providing token acceptance settings, and claims registries. - -## Motivation -An increasing set of use cases require storage of metadata associated with an address; see for instance EIP 777 and EIP 780, and the ENS reverse registry in EIP 181. Presently each use-case defines its own specialised registry. To prevent a proliferation of special-purpose registry contracts, we instead propose a single standardised registry using an extendable architecture that allows future standards to implement their own metadata standards. - -## Specification -The metadata registry has the following interface: -```solidity -interface AddressMetadataRegistry { - function provider(address target) view returns(address); - function setProvider(address _provider); -} -``` - -`setProvider` specifies the metadata registry to be associated with the caller's address, while `provider` returns the address of the metadata registry for the supplied address. - -The metadata registry will be compiled with an agreed-upon version of Solidity and deployed using the trustless deployment mechanism to a fixed address that can be replicated across all chains. - -## Provider specification - -Providers may implement any subset of the metadata record types specified here. Where a record types specification requires a provider to provide multiple functions, the provider MUST implement either all or none of them. Providers MUST throw if called with an unsupported function ID. - -Providers have one mandatory function: - -```solidity -function supportsInterface(bytes4 interfaceID) constant returns (bool) -``` - -The `supportsInterface` function is documented in [EIP-165](./eip-165.md), and returns true if the provider implements the interface specified by the provided 4 byte identifier. An interface identifier consists of the XOR of the function signature hashes of the functions provided by that interface; in the degenerate case of single-function interfaces, it is simply equal to the signature hash of that function. If a provider returns `true` for `supportsInterface()`, it must implement the functions specified in that interface. - -`supportsInterface` must always return true for `0x01ffc9a7`, which is the interface ID of `supportsInterface` itself. - -The first argument to all provider functions MUST be the address being queried; this facilitates the creation of multi-user provider contracts. - -Currently standardised provider interfaces are specified in the table below. - -| Interface name | Interface hash | Specification | -| --- | --- | --- | - -EIPs may define new interfaces to be added to this registry. - -## Rationale -There are two obvious approaches for a generic metadata registry: the indirection approach employed here, or a generalised key/value store. While indirection incurs the cost of an additional contract call, and requires providers to change over time, it also provides for significantly enhanced flexibility over a key/value store; for that reason we selected this approach. - -## Backwards Compatibility -There are no backwards compatibility concerns. - -## Implementation -The canonical implementation of the metadata registry is as follows: -```solidity -contract AddressMetadataRegistry { - mapping(address=>address) public provider; - - function setProvider(address _provider) { - provider[msg.sender] = _provider; - } -} -``` - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-926.md diff --git a/EIPS/eip-927.md b/EIPS/eip-927.md index 5cd5674c74eeba..7644c223d4d4f9 100644 --- a/EIPS/eip-927.md +++ b/EIPS/eip-927.md @@ -1,58 +1,7 @@ --- eip: 927 -title: Generalised authorisations -author: Nick Johnson -type: Standards Track category: ERC -status: Stagnant -created: 2018-03-12 -requires: 926 +status: Moved --- - -## Abstract -This EIP specifies a generic authorisation mechanism, which can be used to implement a variety of authorisation patterns, replacing approvals in ERC20, operators in ERC777, and bespoke authorisation patterns in a variety of other types of contract. -## Motivation -Smart contracts commonly need to provide an interface that allows a third-party caller to perform actions on behalf of a user. The most common example of this is token authorisations/operators, but other similar situations exist throughout the ecosystem, including for instance authorising operations on ENS domains. Typically each standard reinvents this system for themselves, leading to a large number of incompatible implementations of the same basic pattern. Here, we propose a generic method usable by all such contracts. - -The pattern implemented here is inspired by [ds-auth](https://github.com/dapphub/ds-auth) and by OAuth. - -## Specification -The generalised authorisation interface is implemented as a metadata provider, as specified in EIP 926. The following mandatory function is implemented: - -```solidity -function canCall(address owner, address caller, address callee, bytes4 func) view returns(bool); -``` - -Where: - - `owner` is the owner of the resource. If approved the function call is treated as being made by this address. - - `caller` is the address making the present call. - - `callee` is the address of the contract being called. - - `func` is the 4-byte signature of the function being called. - -For example, suppose Alice authorises Bob to transfer tokens on her behalf. When Bob does so, Alice is the `owner`, Bob is the `caller`, the token contract is the `callee`, and the function signature for the transfer function is `func`. - -As this standard uses EIP 926, the authorisation flow is as follows: - - 1. The callee contract fetches the provider for the `owner` address from the metadata registry contract, which resides at a well-known address. - 2. The callee contract calls `canCall()` with the parameters described above. If the function returns false, the callee reverts execution. - -Commonly, providers will wish to supply a standardised interface for users to set and unset their own authorisations. They SHOULD implement the following interface: - -```solidity -function authoriseCaller(address owner, address caller, address callee, bytes4 func); -function revokeCaller(address owner, address caller, address callee, bytes4 func); -``` - -Arguments have the same meaning as in `canCall`. Implementing contracts MUST ensure that `msg.sender` is authorised to call `authoriseCaller` or `revokeCaller` on behalf of `owner`; this MUST always be true if `owner == msg.sender`. Implementing contracts SHOULD use the standard specified here to determine if other callers may provide authorisations as well. - -Implementing contracts SHOULD treat a `func` of 0 as authorising calls to all functions on `callee`. If `authorised` is `false` and `func` is 0, contracts need only clear any blanket authorisation; individual authorisations may remain in effect. - -## Backwards Compatibility -There are no backwards compatibility concerns. - -## Implementation -Example implementation TBD. - -## Copyright -Copyright and related rights waived via [CC0](../LICENSE.md). +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-927.md diff --git a/EIPS/eip-998.md b/EIPS/eip-998.md index b50c26153148c9..f8138629824a35 100644 --- a/EIPS/eip-998.md +++ b/EIPS/eip-998.md @@ -1,1378 +1,7 @@ --- eip: 998 -title: Composable Non-Fungible Token -description: Extends a ERC-721 to own other ERC-721 and ERC-20 tokens. -author: Matt Lockyer , Nick Mudge , Jordan Schalm , sebastian echeverry , Zainan Victor Zhou (@xinbenlv) -discussions-to: https://ethereum-magicians.org/t/erc-998-composable-non-fungible-tokens-cnfts/387 -status: Draft -type: Standards Track category: ERC -created: 2018-07-07 -requires: 20, 165, 721 +status: Moved --- -## Abstract - -An extension of the [ERC-721 standard](./eip-721.md) to enable ERC-721 tokens to own other ERC-721 tokens and [ERC-20](./eip-20.md) tokens. - -An extension of the [ERC-20](./eip-20.md) and `ERC-223 https://github.com/ethereum/EIPs/issues/223` standards to enable ERC-20 and `ERC-223` tokens to be owned by ERC-721 tokens. - -This specification covers four different kinds of composable tokens: - -1. [`ERC998ERC721` top-down composable tokens that receive, hold and transfer ERC-721 tokens](#erc-721-top-down-composable) -2. [`ERC998ERC20` top-down composable tokens that receive, hold and transfer ERC-20 tokens](#erc-20-top-down-composable) -3. [`ERC998ERC721` bottom-up composable tokens that attach themselves to other ERC-721 tokens.](#erc-721-bottom-up-composable) -4. [`ERC998ERC20` bottom-up composable tokens that attach themselves to ERC-721 tokens.](#erc-20-bottom-up-composable) - -which map to - -1. An `ERC998ERC721` top-down composable is an ERC-721 token with additional functionality for owning other ERC-721 tokens. -2. An `ERC998ERC20` top-down composable is an ERC-721 token with additional functionality for owning ERC-20 tokens. -3. An `ERC998ERC721` bottom-up composable is an ERC-721 token with additional functionality for being owned by an ERC-721 token. -4. An `ERC998ERC20` bottom-up composable is an ERC-20 token with additional functionality for being owned by an ERC-721 token. - -A top-down composable contract stores and keeps track of child tokens for each of its tokens. - -A bottom-up composable contract stores and keeps track of a parent token for each its tokens. - -With composable tokens it is possible to compose lists or trees of ERC-721 and ERC-20 tokens connected by ownership. Any such structure will have a single owner address at the root of the structure that is the owner of the entire composition. The entire composition can be transferred with one transaction by changing the root owner. - -Different composables, top-down and bottom-up, have their advantages and disadvantages which are explained in the [Rational section](#rationale). It is possible for a token to be one or more kinds of composable token. - -A non-fungible token is compliant and Composable of this EIP if it implements one or more of the following interfaces: - -* `ERC998ERC721TopDown` -* `ERC998ERC20TopDown` -* `ERC998ERC721BottomUp` -* `ERC998ERC20BottomUp` - -## Specification - -### ERC-721 - -`ERC998ERC721` top-down, `ERC998ERC20` top-down, and `ERC998ERC721` bottom-up composable contracts must implement the [ERC-721 interface](./eip-721.md). - -### ERC-20 - -`ERC998ERC20` bottom-up composable contracts must implement the [ERC-20 interface](./eip-20.md). - -### [ERC-165](./eip-165.md) - -The [ERC-165 standard](./eip-165.md) must be applied to each [ERC-998](./eip-998.md) interface that is used. - -### Authentication - -Authenticating whether a user or contract can execute some action works the same for both `ERC998ERC721` top-down and `ERC998ERC721` bottom-up composables. - -A `rootOwner` refers to the owner address at the top of a tree of composables and ERC-721 tokens. - -Authentication within any composable is done by finding the rootOwner and comparing it to `msg.sender`, the return result of `getApproved(tokenId)` and the return result of `isApprovedForAll(rootOwner, msg.sender)`. If a match is found then authentication passes, otherwise authentication fails and the contract throws. - -Here is an example of authentication code: - -```solidity -address rootOwner = address(rootOwnerOf(_tokenId)); -require(rootOwner == msg.sender || - isApprovedForAll(rootOwner,msg.sender) || - getApproved(tokenId) == msg.sender; -``` - -The `approve(address _approved, uint256 _tokenId)` and `getApproved(uint256 _tokenId)` ERC-721 functions are implemented specifically for the rootOwner. This enables a tree of composables to be transferred to a new rootOwner without worrying about which addresses have been approved in child composables, because any prior approves can only be used by the prior rootOwner. - -Here are example implementations: - -```solidity -function approve(address _approved, uint256 _tokenId) external { - address rootOwner = address(rootOwnerOf(_tokenId)); - require(rootOwner == msg.sender || isApprovedForAll(rootOwner,msg.sender)); - - rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved; - emit Approval(rootOwner, _approved, _tokenId); -} - -function getApproved(uint256 _tokenId) public view returns (address) { - address rootOwner = address(rootOwnerOf(_tokenId)); - return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; -} -``` - -### Traversal - -The rootOwner of a composable is gotten by calling `rootOwnerOf(uint256 _tokenId)` or `rootOwnerOfChild(address _childContract, uint256 _childTokenId)`. These functions are used by top-down and bottom-up composables to traverse up the tree of composables and ERC-721 tokens to find the rootOwner. - -`ERC998ERC721` top-down and bottom-up composables are interoperable with each other. It is possible for a top-down composable to own a bottom-up composable or for a top-down composable to own an ERC-721 token that owns a bottom-up token. In any configuration calling `rootOwnerOf(uint256 _tokenID)` on a composable will return the root owner address at the top of the ownership tree. - -It is important to get the traversal logic of `rootOwnerOf` right. The logic for `rootOwnerOf` is the same whether or not a composable is bottom-up or top-down or both. -Here is the logic: - -``` -Logic for rootOwnerOf(uint256 _tokenId) - -If the token is a bottom-up composable and has a parent token then call rootOwnerOf for the parent token. - If the call was successful then the returned address is the rootOwner. - Otherwise call rootOwnerOfChild for the parent token. - If the call was successful then the returned address is the rootOwner. - Otherwise get the owner address of the token and that is the rootOwner. -Otherwise call rootOwnerOfChild for the token - If the call was successful then the returned address is the rootOwner. - Otherwise get the owner address of the token and that is the rootOwner. -``` - -Calling `rootOwnerOfChild` for a token means the following logic: - -```solidity -// Logic for calling rootOwnerOfChild for a tokenId -address tokenOwner = ownerOf(tokenId); -address childContract = address(this); -bytes32 rootOwner = ERC998ERC721(tokenOwner).rootOwnerOfChild(childContract, tokenId); -``` - -But understand that the real call to `rootOwnerOfChild` should be made with assembly so that the code can check if the call failed and so that the `staticcall` opcode is used to ensure that no state is modified. - -Tokens/contracts that implement the above authentication and traversal functionality are "composable aware". - -### Composable Transfer Function Parameter Format - -Composable functions that make transfers follow the same parameter format: **from:to:what**. - -For example the `getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId)` composable function transfers an ERC-721 token from an address to a top-down composable. The `_from` parameter is the **from**, the `_tokenId` parameter is the **to** and the `address _childContract, uint256 _childTokenId` parameters are the **what**. - -Another example is the `safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId)` function. The `_fromTokenId` is the **from**, the `_to` is the **to** and the `address _childContract, address _childTokenId` parameters are the **what**. - -### transferFrom/safeTransferFrom Functions Do Not Transfer Tokens Owned By Tokens - -In bottom-up and top-down composable contracts the `transferFrom` and `safeTransferFrom` functions must throw if they are called directly to transfer a token that is owned by another token. - -The reason for this is that these functions do not explicitly specify which token owns a token to be transferred. [See the rational section for more information about this.](#explicit-transfer-parameters) - -`transferFrom/safeTransferFrom` functions must be used to transfer tokens that are owned by an address. - - -### ERC-721 Top-Down Composable - -ERC-721 top-down composables act as containers for ERC-721 tokens. - -ERC-721 top-down composables are ERC-721 tokens that can receive, hold and transfer ERC-721 tokens. - -There are two ways to transfer a ERC-721 token to a top-down composable: - -1. Use the `function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)` function. The `_to` argument is the top-down composable contract address. The `bytes data` argument holds the integer value of the top-down composable tokenId that the ERC-721 token is transferred to. -2. Call `approve` in the ERC-721 token contract for the top-down composable contract. Then call `getChild` in the composable contract. - -The first ways is for ERC-721 contracts that have a `safeTransferFrom` function. The second way is for contracts that do not have this function such as cryptokitties. - -Here is an example of transferring ERC-721 token 3 from an address to top-down composable token 6: - -```solidity -uint256 tokenId = 6; -bytes memory tokenIdBytes = new bytes(32); -assembly { mstore(add(tokenIdBytes, 32), tokenId) } -ERC721(contractAddress).safeTransferFrom(userAddress, composableAddress, 3, tokenIdBytes); -``` - -Every ERC-721 top-down composable compliant contract must implement the `ERC998ERC721TopDown` interface. - -The `ERC998ERC721TopDownEnumerable` and `ERC998ERC20TopDownEnumerable` interfaces are optional. - -```solidity -pragma solidity ^0.4.24; - -/// @title `ERC998ERC721` Top-Down Composable Non-Fungible Token -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md -/// Note: the ERC-165 identifier for this interface is 0xcde244d9 -interface ERC998ERC721TopDown { - - /// @dev This emits when a token receives a child token. - /// @param _from The prior owner of the token. - /// @param _toTokenId The token that receives the child token. - event ReceivedChild( - address indexed _from, - uint256 indexed _toTokenId, - address indexed _childContract, - uint256 _childTokenId - ); - - /// @dev This emits when a child token is transferred from a token to an address. - /// @param _fromTokenId The parent token that the child token is being transferred from. - /// @param _to The new owner address of the child token. - event TransferChild( - uint256 indexed _fromTokenId, - address indexed _to, - address indexed _childContract, - uint256 _childTokenId - ); - - /// @notice Get the root owner of tokenId. - /// @param _tokenId The token to query for a root owner address - /// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. - function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner); - - /// @notice Get the root owner of a child token. - /// @param _childContract The contract address of the child token. - /// @param _childTokenId The tokenId of the child. - /// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. - function rootOwnerOfChild( - address _childContract, - uint256 _childTokenId - ) - public - view - returns (bytes32 rootOwner); - - /// @notice Get the parent tokenId of a child token. - /// @param _childContract The contract address of the child token. - /// @param _childTokenId The tokenId of the child. - /// @return parentTokenOwner The parent address of the parent token and ERC-998 magic value - /// @return parentTokenId The parent tokenId of _tokenId - function ownerOfChild( - address _childContract, - uint256 _childTokenId - ) - external - view - returns ( - bytes32 parentTokenOwner, - uint256 parentTokenId - ); - - /// @notice A token receives a child token - /// @param _operator The address that caused the transfer. - /// @param _from The owner of the child token. - /// @param _childTokenId The token that is being transferred to the parent. - /// @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId. - function onERC721Received( - address _operator, - address _from, - uint256 _childTokenId, - bytes _data - ) - external - returns(bytes4); - - /// @notice Transfer child token from top-down composable to address. - /// @param _fromTokenId The owning token to transfer from. - /// @param _to The address that receives the child token - /// @param _childContract The ERC-721 contract of the child token. - /// @param _childTokenId The tokenId of the token that is being transferred. - function transferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId - ) - external; - - /// @notice Transfer child token from top-down composable to address. - /// @param _fromTokenId The owning token to transfer from. - /// @param _to The address that receives the child token - /// @param _childContract The ERC-721 contract of the child token. - /// @param _childTokenId The tokenId of the token that is being transferred. - function safeTransferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId - ) - external; - - /// @notice Transfer child token from top-down composable to address. - /// @param _fromTokenId The owning token to transfer from. - /// @param _to The address that receives the child token - /// @param _childContract The ERC-721 contract of the child token. - /// @param _childTokenId The tokenId of the token that is being transferred. - /// @param _data Additional data with no specified format - function safeTransferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId, - bytes _data - ) - external; - - /// @notice Transfer bottom-up composable child token from top-down composable to other ERC-721 token. - /// @param _fromTokenId The owning token to transfer from. - /// @param _toContract The ERC-721 contract of the receiving token - /// @param _toTokenId The receiving token - /// @param _childContract The bottom-up composable contract of the child token. - /// @param _childTokenId The token that is being transferred. - /// @param _data Additional data with no specified format - function transferChildToParent( - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - address _childContract, - uint256 _childTokenId, - bytes _data - ) - external; - - /// @notice Get a child token from an ERC-721 contract. - /// @param _from The address that owns the child token. - /// @param _tokenId The token that becomes the parent owner - /// @param _childContract The ERC-721 contract of the child token - /// @param _childTokenId The tokenId of the child token - function getChild( - address _from, - uint256 _tokenId, - address _childContract, - uint256 _childTokenId - ) - external; -} -``` - -#### `rootOwnerOf` 1 - -```solidity -/// @notice Get the root owner of tokenId. -/// @param _tokenId The token to query for a root owner address -/// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. -function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner); -``` - -This function traverses token owners until the the root owner address of `_tokenId` is found. - -The first 4 bytes of rootOwner contain the ERC-998 magic value `0xcd740db5`. The last 20 bytes contain the root owner address. - -The magic value is returned because this function may be called on contracts when it is unknown if the contracts have a `rootOwnerOf` function. The magic value is used in such calls to ensure a valid return value is received. - -If it is unknown whether a contract has the `rootOwnerOf` function then the first four bytes of the `rootOwner` return value must be compared to `0xcd740db5`. - -`0xcd740db5` is equal to: - -```solidity -this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ -this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; -``` - -Here is an example of a value returned by `rootOwnerOf`. -`0xcd740db50000000000000000e5240103e1ff986a2c8ae6b6728ffe0d9a395c59` - -#### rootOwnerOfChild - -```solidity -/// @notice Get the root owner of a child token. -/// @param _childContract The contract address of the child token. -/// @param _childTokenId The tokenId of the child. -/// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. -function rootOwnerOfChild( - address _childContract, - uint256 _childTokenId -) - public - view - returns (bytes32 rootOwner); -``` - -This function traverses token owners until the the root owner address of the supplied child token is found. - -The first 4 bytes of rootOwner contain the ERC-998 magic value `0xcd740db5`. The last 20 bytes contain the root owner address. - -The magic value is returned because this function may be called on contracts when it is unknown if the contracts have a `rootOwnerOf` function. The magic value is used in such calls to ensure a valid return value is received. - -If it is unknown whether a contract has the `rootOwnerOfChild` function then the first four bytes of the `rootOwner` return value must be compared to `0xcd740db5`. - -#### ownerOfChild - -```solidity -/// @notice Get the parent tokenId of a child token. -/// @param _childContract The contract address of the child token. -/// @param _childTokenId The tokenId of the child. -/// @return parentTokenOwner The parent address of the parent token and ERC-998 magic value -/// @return parentTokenId The parent tokenId of _tokenId -function ownerOfChild( - address _childContract, - uint256 _childTokenId -) - external - view - returns ( - address parentTokenOwner, - uint256 parentTokenId - ); -``` - -This function is used to get the parent tokenId of a child token and get the owner address of the parent token. - -The first 4 bytes of parentTokenOwner contain the ERC-998 magic value `0xcd740db5`. The last 20 bytes contain the parent token owner address. - -The magic value is returned because this function may be called on contracts when it is unknown if the contracts have a `ownerOfChild` function. The magic value is used in such calls to ensure a valid return value is received. - -If it is unknown whether a contract has the `ownerOfChild` function then the first four bytes of the `parentTokenOwner` return value must be compared to `0xcd740db5`. - -#### `onERC721Received` - -```solidity -/// @notice A token receives a child token -/// @param _operator The address that caused the transfer. -/// @param _from The prior owner of the child token. -/// @param _childTokenId The token that is being transferred to the parent. -/// @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId. -function onERC721Received( - address _operator, - address _from, - uint256 _childTokenId, - bytes _data -) - external - returns(bytes4); -``` - -This is a function defined in the ERC-721 standard. This function is called in an ERC-721 contract when `safeTransferFrom` is called. The `bytes _data` argument contains an integer value from 1 to 32 bytes long that is the parent tokenId that an ERC-721 token is transferred to. - -The `onERC721Received` function is how a top-down composable contract is notified that an ERC-721 token has been transferred to it and what tokenId in the top-down composable is the parent tokenId. - -The return value for `onERC721Received` is the magic value `0x150b7a02` which is equal to `bytes4(keccak256(abi.encodePacked("onERC721Received(address,address,uint256,bytes)")))`. - -#### transferChild - -```solidity -/// @notice Transfer child token from top-down composable to address. -/// @param _fromTokenId The owning token to transfer from. -/// @param _to The address that receives the child token -/// @param _childContract The ERC-721 contract of the child token. -/// @param _childTokenId The tokenId of the token that is being transferred. -function transferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId -) - external; -``` - -This function authenticates `msg.sender` and transfers a child token from a top-down composable to a different address. - -This function makes this call within it: - -```solidity -ERC721(_childContract).transferFrom(this, _to, _childTokenId); -``` - -#### safeTransferChild 1 - -```solidity -/// @notice Transfer child token from top-down composable to address. -/// @param _fromTokenId The owning token to transfer from. -/// @param _to The address that receives the child token -/// @param _childContract The ERC-721 contract of the child token. -/// @param _childTokenId The tokenId of the token that is being transferred. -function safeTransferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId -) - external; -``` - -This function authenticates `msg.sender` and transfers a child token from a top-down composable to a different address. - -This function makes this call within it: - -```solidity -ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId); -``` - -#### safeTransferChild 2 - -```solidity -/// @notice Transfer child token from top-down composable to address or other top-down composable. -/// @param _fromTokenId The owning token to transfer from. -/// @param _to The address that receives the child token -/// @param _childContract The ERC721 contract of the child token. -/// @param _childTokenId The tokenId of the token that is being transferred. -/// @param _data Additional data with no specified format, can be used to specify tokenId to transfer to -function safeTransferChild( - uint256 _fromTokenId, - address _to, - address _childContract, - uint256 _childTokenId, - bytes _data -) - external; -``` - -This function authenticates `msg.sender` and transfers a child token from a top-down composable to a different address or to a different top-down composable. - -A child token is transferred to a different top-down composable if the `_to` address is a top-down composable contract and `bytes _data` is supplied an integer representing the parent tokenId. - -This function makes this call within it: - -```solidity -ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId, _data); -``` - -#### transferChildToParent - -```solidity -/// @notice Transfer bottom-up composable child token from top-down composable to other ERC-721 token. -/// @param _fromTokenId The owning token to transfer from. -/// @param _toContract The ERC-721 contract of the receiving token -/// @param _toToken The receiving token -/// @param _childContract The bottom-up composable contract of the child token. -/// @param _childTokenId The token that is being transferred. -/// @param _data Additional data with no specified format -function transferChildToParent( - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - address _childContract, - uint256 _childTokenId, - bytes _data -) - external -``` - -This function authenticates `msg.sender` and transfers a child bottom-up composable token from a top-down composable to a different ERC-721 token. This function can only be used when the child token is a bottom-up composable token. It is designed to transfer a bottom-up composable token from a top-down composable to an ERC-721 token (bottom-up style) in one transaction. - -This function makes this call within it: - -```solidity -ERC998ERC721BottomUp(_childContract).transferToParent( - address(this), - _toContract, - _toTokenId, - _childTokenId, - _data -); -``` - -#### getChild - -```solidity -/// @notice Get a child token from an ERC-721 contract. -/// @param _from The address that owns the child token. -/// @param _tokenId The token that becomes the parent owner -/// @param _childContract The ERC-721 contract of the child token -/// @param _childTokenId The tokenId of the child token -function getChild( - address _from, - uint256 _tokenId, - address _childContract, - uint256 _childTokenId -) - external; -``` - -This function is used to transfer an ERC-721 token when its contract does not have a `safeTransferChild(uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes _data)` function. - -A transfer with this function is done in two steps: - -1. The owner of the ERC-721 token calls `approve` or `setApprovalForAll` in the ERC-721 contract for the top-down composable contract. -2. The owner of the ERC-721 token calls `getChild` in the top-down composable contract for the ERC-721 token. - -The `getChild` function must authenticate that `msg.sender` is the owner of the ERC-721 token in the ERC-721 contract or is approved or an operator of the ERC-721 token in the ERC-721 contract. - -#### ERC-721 Top-Down Composable Enumeration - -Optional interface for top-down composable enumeration: - -```solidity -/// @dev The ERC-165 identifier for this interface is 0xa344afe4 -interface ERC998ERC721TopDownEnumerable { - - /// @notice Get the total number of child contracts with tokens that are owned by tokenId. - /// @param _tokenId The parent token of child tokens in child contracts - /// @return uint256 The total number of child contracts with tokens owned by tokenId. - function totalChildContracts(uint256 _tokenId) external view returns(uint256); - - /// @notice Get child contract by tokenId and index - /// @param _tokenId The parent token of child tokens in child contract - /// @param _index The index position of the child contract - /// @return childContract The contract found at the tokenId and index. - function childContractByIndex( - uint256 _tokenId, - uint256 _index - ) - external - view - returns (address childContract); - - /// @notice Get the total number of child tokens owned by tokenId that exist in a child contract. - /// @param _tokenId The parent token of child tokens - /// @param _childContract The child contract containing the child tokens - /// @return uint256 The total number of child tokens found in child contract that are owned by tokenId. - function totalChildTokens( - uint256 _tokenId, - address _childContract - ) - external - view - returns(uint256); - - /// @notice Get child token owned by tokenId, in child contract, at index position - /// @param _tokenId The parent token of the child token - /// @param _childContract The child contract of the child token - /// @param _index The index position of the child token. - /// @return childTokenId The child tokenId for the parent token, child token and index - function childTokenByIndex( - uint256 _tokenId, - address _childContract, - uint256 _index - ) - external - view - returns (uint256 childTokenId); -} -``` - -### ERC-20 Top-Down Composable - -ERC-20 top-down composables act as containers for ERC-20 tokens. - -ERC-20 top-down composables are ERC-721 tokens that can receive, hold and transfer ERC-20 tokens. - -There are two ways to transfer ERC-20 tokens to an ERC-20 Top-Down Composable: - -1. Use the `transfer(address _to, uint256 _value, bytes _data);` function from the `ERC-223` contract. The `_to` argument is the ERC-20 top-down composable contract address. The `_value` argument is how many ERC-20 tokens to transfer. The `bytes` argument holds the integer value of the top-down composable tokenId that receives the ERC-20 tokens. -2. Call `approve` in the ERC-20 contract for the ERC-20 top-down composable contract. Then call `getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value)` from the ERC-20 top-down composable contract. - -The first way is for ERC-20 contracts that support the `ERC-223` standard. The second way is for contracts that do not. - -ERC-20 top-down composables implement the following interface: - -```solidity -/// @title `ERC998ERC20` Top-Down Composable Non-Fungible Token -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md -/// Note: the ERC-165 identifier for this interface is 0x7294ffed -interface ERC998ERC20TopDown { - - /// @dev This emits when a token receives ERC-20 tokens. - /// @param _from The prior owner of the token. - /// @param _toTokenId The token that receives the ERC-20 tokens. - /// @param _erc20Contract The ERC-20 contract. - /// @param _value The number of ERC-20 tokens received. - event ReceivedERC20( - address indexed _from, - uint256 indexed _toTokenId, - address indexed _erc20Contract, - uint256 _value - ); - - /// @dev This emits when a token transfers ERC-20 tokens. - /// @param _tokenId The token that owned the ERC-20 tokens. - /// @param _to The address that receives the ERC-20 tokens. - /// @param _erc20Contract The ERC-20 contract. - /// @param _value The number of ERC-20 tokens transferred. - event TransferERC20( - uint256 indexed _fromTokenId, - address indexed _to, - address indexed _erc20Contract, - uint256 _value - ); - - /// @notice A token receives ERC-20 tokens - /// @param _from The prior owner of the ERC-20 tokens - /// @param _value The number of ERC-20 tokens received - /// @param _data Up to the first 32 bytes contains an integer which is the receiving tokenId. - function tokenFallback(address _from, uint256 _value, bytes _data) external; - - /// @notice Look up the balance of ERC-20 tokens for a specific token and ERC-20 contract - /// @param _tokenId The token that owns the ERC-20 tokens - /// @param _erc20Contract The ERC-20 contract - /// @return The number of ERC-20 tokens owned by a token from an ERC-20 contract - function balanceOfERC20( - uint256 _tokenId, - address _erc20Contract - ) - external - view - returns(uint256); - - /// @notice Transfer ERC-20 tokens to address - /// @param _tokenId The token to transfer from - /// @param _value The address to send the ERC-20 tokens to - /// @param _erc20Contract The ERC-20 contract - /// @param _value The number of ERC-20 tokens to transfer - function transferERC20( - uint256 _tokenId, - address _to, - address _erc20Contract, - uint256 _value - ) - external; - - /// @notice Transfer ERC-20 tokens to address or ERC-20 top-down composable - /// @param _tokenId The token to transfer from - /// @param _value The address to send the ERC-20 tokens to - /// @param _erc223Contract The `ERC-223` token contract - /// @param _value The number of ERC-20 tokens to transfer - /// @param _data Additional data with no specified format, can be used to specify tokenId to transfer to - function transferERC223( - uint256 _tokenId, - address _to, - address _erc223Contract, - uint256 _value, - bytes _data - ) - external; - - /// @notice Get ERC-20 tokens from ERC-20 contract. - /// @param _from The current owner address of the ERC-20 tokens that are being transferred. - /// @param _tokenId The token to transfer the ERC-20 tokens to. - /// @param _erc20Contract The ERC-20 token contract - /// @param _value The number of ERC-20 tokens to transfer - function getERC20( - address _from, - uint256 _tokenId, - address _erc20Contract, - uint256 _value - ) - external; -} -``` - -#### tokenFallback - -```solidity -/// @notice A token receives ERC-20 tokens -/// @param _from The prior owner of the ERC-20 tokens -/// @param _value The number of ERC-20 tokens received -/// @param _data Up to the first 32 bytes contains an integer which is the receiving tokenId. -function tokenFallback(address _from, uint256 _value, bytes _data) external; -``` - -This function comes from the `ERC-223` which is an extension of the ERC-20 standard. This function is called on the receiving contract from the sending contract when ERC-20 tokens are transferred. This function is how the ERC-20 top-down composable contract gets notified that one of its tokens received ERC-20 tokens. Which token received ERC-20 tokens is specified in the `_data` parameter. - -#### `balanceOfERC20` - -```solidity -/// @notice Look up the balance of ERC-20 tokens for a specific token and ERC-20 contract -/// @param _tokenId The token that owns the ERC-20 tokens -/// @param _erc20Contract The ERC-20 contract -/// @return The number of ERC-20 tokens owned by a token from an ERC-20 contract -function balanceOfERC20( - uint256 _tokenId, - address _erc20Contract -) - external - view - returns(uint256); -``` - -Gets the balance of ERC-20 tokens owned by a token from a specific ERC-20 contract. - -#### `transferERC20` - -```solidity -/// @notice Transfer ERC-20 tokens to address -/// @param _tokenId The token to transfer from -/// @param _value The address to send the ERC-20 tokens to -/// @param _erc20Contract The ERC-20 contract -/// @param _value The number of ERC-20 tokens to transfer -function transferERC20( - uint256 _tokenId, - address _to, - address _erc20Contract, - uint256 _value -) - external; -``` - -This is used to transfer ERC-20 tokens from a token to an address. This function calls `ERC20(_erc20Contract).transfer(_to, _value)`; - -This function must authenticate `msg.sender`. - -#### `transferERC223` - -```solidity - /// @notice Transfer ERC-20 tokens to address or ERC-20 top-down composable - /// @param _tokenId The token to transfer from - /// @param _value The address to send the ERC-20 tokens to - /// @param _erc223Contract The `ERC-223` token contract - /// @param _value The number of ERC-20 tokens to transfer - /// @param _data Additional data with no specified format, can be used to specify tokenId to transfer to - function transferERC223( - uint256 _tokenId, - address _to, - address _erc223Contract, - uint256 _value, - bytes _data - ) - external; -``` - -This function is from the `ERC-223`. It is used to transfer ERC-20 tokens from a token to an address or to another token by putting an integer token value in the `_data` argument. - -This function must authenticate `msg.sender`. - -#### `getERC20` - -```solidity -/// @notice Get ERC-20 tokens from ERC-20 contract. -/// @param _from The current owner address of the ERC-20 tokens that are being transferred. -/// @param _tokenId The token to transfer the ERC-20 tokens to. -/// @param _erc20Contract The ERC-20 token contract -/// @param _value The number of ERC-20 tokens to transfer -function getERC20( - address _from, - uint256 _tokenId, - address _erc20Contract, - uint256 _value -) - external; -``` - -This function is used to transfer ERC-20 tokens to an ERC-20 top-down composable when an ERC-20 contract does not have a `transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data)` function. - -Before this function can be used the ERC-20 top-down composable contract address must be approved in the ERC-20 contract to transfer the ERC-20 tokens. - -This function must authenticate that `msg.sender` equals `_from` or has been approved in the ERC-20 contract. - -#### ERC-20 Top-Down Composable Enumeration - -Optional interface for top-down composable enumeration: - -```solidity -/// @dev The ERC-165 identifier for this interface is 0xc5fd96cd -interface ERC998ERC20TopDownEnumerable { - - /// @notice Get the number of ERC-20 contracts that token owns ERC-20 tokens from - /// @param _tokenId The token that owns ERC-20 tokens. - /// @return uint256 The number of ERC-20 contracts - function totalERC20Contracts(uint256 _tokenId) external view returns(uint256); - - /// @notice Get an ERC-20 contract that token owns ERC-20 tokens from by index - /// @param _tokenId The token that owns ERC-20 tokens. - /// @param _index The index position of the ERC-20 contract. - /// @return address The ERC-20 contract - function erc20ContractByIndex( - uint256 _tokenId, - uint256 _index - ) - external - view - returns(address); -} -``` - -### ERC-721 Bottom-Up Composable - -ERC-721 bottom-up composables are ERC-721 tokens that attach themselves to other ERC-721 tokens. - -ERC-721 bottom-up composable contracts store the owning address of a token and the parent tokenId if any. - -```solidity -/// @title `ERC998ERC721` Bottom-Up Composable Non-Fungible Token -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md -/// Note: the ERC-165 identifier for this interface is 0xa1b23002 -interface ERC998ERC721BottomUp { - - /// @dev This emits when a token is transferred to an ERC-721 token - /// @param _toContract The contract the token is transferred to - /// @param _toTokenId The token the token is transferred to - /// @param _tokenId The token that is transferred - event TransferToParent( - address indexed _toContract, - uint256 indexed _toTokenId, - uint256 _tokenId - ); - - /// @dev This emits when a token is transferred from an ERC-721 token - /// @param _fromContract The contract the token is transferred from - /// @param _fromTokenId The token the token is transferred from - /// @param _tokenId The token that is transferred - event TransferFromParent( - address indexed _fromContract, - uint256 indexed _fromTokenId, - uint256 _tokenId - ); - - /// @notice Get the root owner of tokenId. - /// @param _tokenId The token to query for a root owner address - /// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. - function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner); - - /// @notice Get the owner address and parent token (if there is one) of a token - /// @param _tokenId The tokenId to query. - /// @return tokenOwner The owner address of the token - /// @return parentTokenId The parent owner of the token and ERC-998 magic value - /// @return isParent True if parentTokenId is a valid parent tokenId and false if there is no parent tokenId - function tokenOwnerOf( - uint256 _tokenId - ) - external - view - returns ( - bytes32 tokenOwner, - uint256 parentTokenId, - bool isParent - ); - - /// @notice Transfer token from owner address to a token - /// @param _from The owner address - /// @param _toContract The ERC-721 contract of the receiving token - /// @param _toToken The receiving token - /// @param _data Additional data with no specified format - function transferToParent( - address _from, - address _toContract, - uint256 _toTokenId, - uint256 _tokenId, - bytes _data - ) - external; - - /// @notice Transfer token from a token to an address - /// @param _fromContract The address of the owning contract - /// @param _fromTokenId The owning token - /// @param _to The address the token is transferred to. - /// @param _tokenId The token that is transferred - /// @param _data Additional data with no specified format - function transferFromParent( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _tokenId, - bytes _data - ) - external; - - /// @notice Transfer a token from a token to another token - /// @param _fromContract The address of the owning contract - /// @param _fromTokenId The owning token - /// @param _toContract The ERC-721 contract of the receiving token - /// @param _toToken The receiving token - /// @param _tokenId The token that is transferred - /// @param _data Additional data with no specified format - function transferAsChild( - address _fromContract, - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - uint256 _tokenId, - bytes _data - ) - external; -} -``` - -#### `rootOwnerOf` - -```solidity -/// @notice Get the root owner of tokenId. -/// @param _tokenId The token to query for a root owner address -/// @return rootOwner The root owner at the top of tree of tokens and ERC-998 magic value. -function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner); -``` - -This function traverses token owners until the the root owner address of `_tokenId` is found. - -The first 4 bytes of rootOwner contain the ERC-998 magic value `0xcd740db5`. The last 20 bytes contain the root owner address. - -The magic value is returned because this function may be called on contracts when it is unknown if the contracts have a `rootOwnerOf` function. The magic value is used in such calls to ensure a valid return value is received. - -If it is unknown whether a contract has the `rootOwnerOf` function then the first four bytes of the `rootOwner` return value must be compared to `0xcd740db5`. - -`0xcd740db5` is equal to: - -```solidity -this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^ -this.tokenOwnerOf.selector ^ this.ownerOfChild.selector; -``` - -Here is an example of a value returned by `rootOwnerOf`. -`0xcd740db50000000000000000e5240103e1ff986a2c8ae6b6728ffe0d9a395c59` - -#### tokenOwnerOf - -```solidity -/// @notice Get the owner address and parent token (if there is one) of a token -/// @param _tokenId The tokenId to query. -/// @return tokenOwner The owner address of the token and ERC-998 magic value. -/// @return parentTokenId The parent owner of the token -/// @return isParent True if parentTokenId is a valid parent tokenId and false if there is no parent tokenId -function tokenOwnerOf( - uint256 _tokenId -) - external - view - returns ( - bytes32 tokenOwner, - uint256 parentTokenId, - bool isParent - ); -``` - -This function is used to get the owning address and parent tokenId of a token if there is one stored in the contract. - -If `isParent` is true then `tokenOwner` is the owning ERC-721 contract address and `parentTokenId` is a valid parent tokenId. If `isParent` is false then `tokenOwner` is a user address and `parentTokenId` does not contain a valid parent tokenId and must be ignored. - -The first 4 bytes of `tokenOwner` contain the ERC-998 magic value `0xcd740db5`. The last 20 bytes contain the token owner address. - -The magic value is returned because this function may be called on contracts when it is unknown if the contracts have a `tokenOwnerOf` function. The magic value is used in such calls to ensure a valid return value is received. - -If it is unknown whether a contract has the `rootOwnerOf` function then the first four bytes of the `tokenOwner` return value must be compared to `0xcd740db5`. - -#### transferToParent - -```solidity -/// @notice Transfer token from owner address to a token -/// @param _from The owner address -/// @param _toContract The ERC-721 contract of the receiving token -/// @param _toToken The receiving token -/// @param _data Additional data with no specified format -function transferToParent( - address _from, - address _toContract, - uint256 _toTokenId, - uint256 _tokenId, - bytes _data -) - external; -``` - -This function is used to transfer a token from an address to a token. `msg.sender` must be authenticated. - -This function must check that `_toToken` exists in `_toContract` and throw if not. - -#### transferFromParent - -```solidity -/// @notice Transfer token from a token to an address -/// @param _fromContract The address of the owning contract -/// @param _fromTokenId The owning token -/// @param _to The address the token is transferred to. -/// @param _tokenId The token that is transferred -/// @param _data Additional data with no specified format -function transferFromParent( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _tokenId, - bytes _data -) - external; -``` - -This function is used to transfer a token from a token to an address. `msg.sender` must be authenticated. - -This function must check that `_fromContract` and `_fromTokenId` own `_tokenId` and throw not. - -#### transferAsChild - -```solidity -/// @notice Transfer a token from a token to another token -/// @param _fromContract The address of the owning contract -/// @param _fromTokenId The owning token -/// @param _toContract The ERC-721 contract of the receiving token -/// @param _toToken The receiving token -/// @param _tokenId The token that is transferred -/// @param _data Additional data with no specified format -function transferAsChild( - address _fromContract, - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - uint256 _tokenId, - bytes _data -) - external; -``` - -This function is used to transfer a token from a token to another token. `msg.sender` must be authenticated. - -This function must check that `_toToken` exists in `_toContract` and throw if not. - -This function must check that `_fromContract` and `_fromTokenId` own `_tokenId` and throw if not. - -#### ERC-721 Bottom-Up Composable Enumeration - -Optional interface for bottom-up composable enumeration: - -```solidity -/// @dev The ERC-165 identifier for this interface is 0x8318b539 -interface ERC998ERC721BottomUpEnumerable { - - /// @notice Get the number of ERC-721 tokens owned by parent token. - /// @param _parentContract The contract the parent ERC-721 token is from. - /// @param _parentTokenId The parent tokenId that owns tokens - // @return uint256 The number of ERC-721 tokens owned by parent token. - function totalChildTokens( - address _parentContract, - uint256 _parentTokenId - ) - external - view - returns (uint256); - - /// @notice Get a child token by index - /// @param _parentContract The contract the parent ERC-721 token is from. - /// @param _parentTokenId The parent tokenId that owns the token - /// @param _index The index position of the child token - /// @return uint256 The child tokenId owned by the parent token - function childTokenByIndex( - address _parentContract, - uint256 _parentTokenId, - uint256 _index - ) - external - view - returns (uint256); -} -``` - -### ERC-20 Bottom-Up Composable - -ERC-20 bottom-up composables are ERC-20 tokens that attach themselves to ERC-721 tokens, or are owned by a user address like standard ERC-20 tokens. - -When owned by an ERC-721 token, ERC-20 bottom-up composable contracts store the owning address of a token and the parent tokenId. ERC-20 bottom-up composables add several methods to the ERC-20 and `ERC-223` interfaces allowing for querying the balance of parent tokens, and transferring tokens to, from, and between parent tokens. - -This functionality can be implemented by adding one additional mapping to track balances of tokens, in addition to the standard mapping for tracking user address balances. - -```solidity -/// @dev This mapping tracks standard ERC20/`ERC-223` ownership, where an address owns -/// a particular amount of tokens. -mapping(address => uint) userBalances; - -/// @dev This additional mapping tracks ERC-998 ownership, where an ERC-721 token owns -/// a particular amount of tokens. This tracks contractAddres => tokenId => balance -mapping(address => mapping(uint => uint)) nftBalances; -``` - -The complete interface is below. - -```solidity -/// @title `ERC998ERC20` Bottom-Up Composable Fungible Token -/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md -/// Note: The ERC-165 identifier for this interface is 0xffafa991 -interface ERC998ERC20BottomUp { - - /// @dev This emits when a token is transferred to an ERC-721 token - /// @param _toContract The contract the token is transferred to - /// @param _toTokenId The token the token is transferred to - /// @param _amount The amount of tokens transferred - event TransferToParent( - address indexed _toContract, - uint256 indexed _toTokenId, - uint256 _amount - ); - - /// @dev This emits when a token is transferred from an ERC-721 token - /// @param _fromContract The contract the token is transferred from - /// @param _fromTokenId The token the token is transferred from - /// @param _amount The amount of tokens transferred - event TransferFromParent( - address indexed _fromContract, - uint256 indexed _fromTokenId, - uint256 _amount - ); - - /// @notice Get the balance of a non-fungible parent token - /// @param _tokenContract The contract tracking the parent token - /// @param _tokenId The ID of the parent token - /// @return amount The balance of the token - function balanceOfToken( - address _tokenContract, - uint256 _tokenId - ) - external - view - returns (uint256 amount); - - /// @notice Transfer tokens from owner address to a token - /// @param _from The owner address - /// @param _toContract The ERC-721 contract of the receiving token - /// @param _toToken The receiving token - /// @param _amount The amount of tokens to transfer - function transferToParent( - address _from, - address _toContract, - uint256 _toTokenId, - uint256 _amount - ) - external; - - /// @notice Transfer token from a token to an address - /// @param _fromContract The address of the owning contract - /// @param _fromTokenId The owning token - /// @param _to The address the token is transferred to - /// @param _amount The amount of tokens to transfer - function transferFromParent( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _amount - ) - external; - - /// @notice Transfer token from a token to an address, using `ERC-223` semantics - /// @param _fromContract The address of the owning contract - /// @param _fromTokenId The owning token - /// @param _to The address the token is transferred to - /// @param _amount The amount of tokens to transfer - /// @param _data Additional data with no specified format, can be used to specify the sender tokenId - function transferFromParentERC223( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _amount, - bytes _data - ) - external; - - /// @notice Transfer a token from a token to another token - /// @param _fromContract The address of the owning contract - /// @param _fromTokenId The owning token - /// @param _toContract The ERC-721 contract of the receiving token - /// @param _toToken The receiving token - /// @param _amount The amount tokens to transfer - function transferAsChild( - address _fromContract, - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - uint256 _amount - ) - external; -} -``` - -#### balanceOfToken - -```solidity -/// @notice Get the balance of a non-fungible parent token -/// @param _tokenContract The contract tracking the parent token -/// @param _tokenId The ID of the parent token -/// @return amount The balance of the token -function balanceOfToken( - address _tokenContract, - uint256 _tokenId -) - external - view - returns (uint256 amount); -``` - -This function returns the balance of a non-fungible token. It mirrors the standard ERC-20 method `balanceOf`, but accepts the address of the parent token's contract, and the parent token's ID. This method behaves identically to `balanceOf`, but checks for ownership by ERC-721 tokens rather than user addresses. - -#### `transferToParent` - -```solidity -/// @notice Transfer tokens from owner address to a token -/// @param _from The owner address -/// @param _toContract The ERC-721 contract of the receiving token -/// @param _toToken The receiving token -/// @param _amount The amount of tokens to transfer -function transferToParent( - address _from, - address _toContract, - uint256 _toTokenId, - uint256 _amount -) - external; -``` - -This function transfers an amount of tokens from a user address to an ERC-721 token. This function MUST ensure that the recipient contract implements ERC-721 using the ERC-165 `supportsInterface` function. This function SHOULD ensure that the recipient token actually exists, by calling `ownerOf` on the recipient token's contract, and ensuring it neither throws nor returns the zero address. This function MUST emit the `TransferToParent` event upon a successful transfer (in addition to the standard ERC-20 `Transfer` event!). This function MUST throw if the `_from` account balance does not have enough tokens to spend. - -#### `transferFromParent` - -```solidity -/// @notice Transfer token from a token to an address -/// @param _fromContract The address of the owning contract -/// @param _fromTokenId The owning token -/// @param _to The address the token is transferred to -/// @param _amount The amount of tokens to transfer -function transferFromParent( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _amount -) - external; -``` - -This function transfers an amount of tokens from an ERC-721 token to an address. This function MUST emit the `TransferFromParent` event upon a successful transfer (in addition to the standard ERC-20 `Transfer` event!). This function MUST throw if the balance of the sender ERC-721 token is less than the `_amount` specified. This function MUST verify that the `msg.sender` owns the sender ERC-721 token, and MUST throw otherwise. - -#### `transferFromParentERC223` - -```solidity -/// @notice Transfer token from a token to an address, using `ERC-223` semantics -/// @param _fromContract The address of the owning contract -/// @param _fromTokenId The owning token -/// @param _to The address the token is transferred to -/// @param _amount The amount of tokens to transfer -/// @param _data Additional data with no specified format, can be used to specify the sender tokenId -function transferFromParentERC223( - address _fromContract, - uint256 _fromTokenId, - address _to, - uint256 _amount, - bytes _data -) - external; -``` - -This function transfers an amount of tokens from an ERC-721 token to an address. This function has identical requirements to `transferFromParent`, except that it additionally MUST invoke `tokenFallback` on the recipient address, if the address is a contract, as specified by `ERC-223`. - -#### transferAsChild 1 - -```solidity -/// @notice Transfer a token from a token to another token -/// @param _fromContract The address of the owning contract -/// @param _fromTokenId The owning token -/// @param _toContract The ERC-721 contract of the receiving token -/// @param _toToken The receiving token -/// @param _amount The amount tokens to transfer -function transferAsChild( - address _fromContract, - uint256 _fromTokenId, - address _toContract, - uint256 _toTokenId, - uint256 _amount -) - external; -``` - -This function transfers an amount of tokens from an ERC-721 token to another ERC-721 token. This function MUST emit BOTH the `TransferFromParent` and `TransferToParent` events (in addition to the standard ERC-20 `Transfer` event!). This function MUST throw if the balance of the sender ERC-721 token is less than the `_amount` specified. This function MUST verify that the `msg.sender` owns the sender ERC-721 token, and MUST throw otherwise. This function MUST ensure that the recipient contract implements ERC-721 using the ERC-165 `supportsInterface` function. This function SHOULD ensure that the recipient token actually exists, by calling `ownerOf` on the recipient token's contract, and ensuring it neither throws nor returns the zero address. - -### Notes - -For backwards-compatibility, implementations MUST emit the standard ERC-20 `Transfer` event when a transfer occurs, regardless of whether the sender and recipient are addresses or ERC-721 tokens. In the case that either sender or recipient are tokens, the corresponding parameter in the `Transfer` event SHOULD be the contract address of the token. - -Implementations MUST implement all ERC-20 and `ERC-223` functions in addition to the functions specified in this interface. - -## Rationale - -Two different kinds of composable (top-down and bottom-up) exist to handle different use cases. A regular ERC-721 token cannot own a top-down composable, but it can own a bottom-up composable. A bottom-up composable cannot own a regular ERC-721 but a top-down composable can own a regular ERC-721 token. Having multiple kinds of composables enable different token ownership possibilities. - -### Which Kind of Composable To Use? - -If you want to transfer regular ERC-721 tokens to non-fungible tokens, then use top-down composables. - -If you want to transfer non-fungible tokens to regular ERC-721 tokens then use bottom-up composables. - -### Explicit Transfer Parameters - -Every ERC-998 transfer function includes explicit parameters to specify the prior owner and the new owner of a token. Explicitly providing **from** and **to** is done intentionally to avoid situations where tokens are transferred in unintended ways. - -Here is an example of what could occur if **from** was not explicitly provided in transfer functions: -> An exchange contract is an approved operator in a specific composable contract for user A, user B and user C. -> -> User A transfers token 1 to user B. At the same time the exchange contract transfers token 1 to user C (with the implicit intention to transfer from user A). User B gets token 1 for a minute before it gets incorrectly transferred to user C. The second transfer should have failed but it didn't because no explicit **from** was provided to ensure that token 1 came from user A. - -## Backwards Compatibility - -Composables are designed to work with ERC-721, `ERC-223` and ERC-20 tokens. - -Some older ERC-721 contracts do not have a `safeTransferFrom` function. The `getChild` function can still be used to transfer a token to an ERC-721 top-down composable. - -If an ERC-20 contract does not have the `ERC-223` function `transfer(address _to, uint _value, bytes _data)` then the `getERC20` function can still be used to transfer ERC-20 tokens to an ERC-20 top-down composable. - -## Reference Implementation - -An implementation can be found here: `https://github.com/mattlockyer/composables-998` - -## Security Considerations - -Needs discussion. - - -## Copyright - -Copyright and related rights waived via [CC0](../LICENSE.md). - - - +This file was moved to https://github.com/ethereum/ercs/blob/master/ERCS/erc-998.md diff --git a/Gemfile b/Gemfile index 486d604c589a33..b69ec372167c63 100644 --- a/Gemfile +++ b/Gemfile @@ -12,16 +12,17 @@ gem "minima", "~> 2.0" # If you have any plugins, put them here! group :jekyll_plugins do - gem "jekyll-feed", "~> 0.11" - gem "github-pages", "206" + gem "github-pages", "228" end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby] # Performance-booster for watching directories on Windows -gem "wdm", "~> 0.1.0" if Gem.win_platform? +gem "wdm", "~> 0.1.1" if Gem.win_platform? -gem "html-proofer", '>=3.3.1' +gem "html-proofer", '>=5.0.7' gem "eip_validator", ">=0.8.2" + +gem "webrick", "~> 1.8" # needed for macOS builds diff --git a/Gemfile.lock b/Gemfile.lock index 407e2c391d1ebe..21a6074d83a08a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,113 +1,127 @@ GEM remote: https://rubygems.org/ specs: - activemodel (6.0.3.1) - activesupport (= 6.0.3.1) - activesupport (6.0.3.1) + Ascii85 (1.1.0) + activemodel (7.0.7.2) + activesupport (= 7.0.7.2) + activesupport (7.0.7.2) concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 0.7, < 2) - minitest (~> 5.1) - tzinfo (~> 1.1) - zeitwerk (~> 2.2, >= 2.2.2) - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.4) + public_suffix (>= 2.0.2, < 6.0) + afm (0.2.2) + async (2.5.0) + console (~> 1.10) + io-event (~> 1.1) + timers (~> 4.1) coffee-script (2.4.1) coffee-script-source execjs coffee-script-source (1.11.1) colorator (1.1.0) - commonmarker (0.17.13) - ruby-enum (~> 0.5) - concurrent-ruby (1.1.6) - dnsruby (1.61.3) - addressable (~> 2.5) + commonmarker (0.23.10) + concurrent-ruby (1.2.2) + console (1.16.2) + fiber-local + dnsruby (1.70.0) + simpleidn (~> 0.2.1) eip_validator (0.8.2) activemodel front_matter_parser (~> 0.1.1) - em-websocket (0.5.1) + em-websocket (0.5.3) eventmachine (>= 0.12.9) - http_parser.rb (~> 0.6.0) - ethon (0.12.0) - ffi (>= 1.3.0) + http_parser.rb (~> 0) + ethon (0.16.0) + ffi (>= 1.15.0) eventmachine (1.2.7) - execjs (2.7.0) - faraday (1.0.1) - multipart-post (>= 1.2, < 3) - ffi (1.12.2) + execjs (2.8.1) + faraday (2.7.4) + faraday-net_http (>= 2.0, < 3.1) + ruby2_keywords (>= 0.0.4) + faraday-net_http (3.0.2) + ffi (1.15.5) + fiber-local (1.0.0) forwardable-extended (2.6.0) front_matter_parser (0.1.1) gemoji (3.0.1) - github-pages (206) - github-pages-health-check (= 1.16.1) - jekyll (= 3.8.7) + github-pages (228) + github-pages-health-check (= 1.17.9) + jekyll (= 3.9.3) jekyll-avatar (= 0.7.0) jekyll-coffeescript (= 1.1.1) - jekyll-commonmark-ghpages (= 0.1.6) + jekyll-commonmark-ghpages (= 0.4.0) jekyll-default-layout (= 0.1.4) - jekyll-feed (= 0.13.0) + jekyll-feed (= 0.15.1) jekyll-gist (= 1.5.0) jekyll-github-metadata (= 2.13.0) - jekyll-mentions (= 1.5.1) + jekyll-include-cache (= 0.2.1) + jekyll-mentions (= 1.6.0) jekyll-optional-front-matter (= 0.3.2) jekyll-paginate (= 1.1.0) jekyll-readme-index (= 0.3.0) - jekyll-redirect-from (= 0.15.0) + jekyll-redirect-from (= 0.16.0) jekyll-relative-links (= 0.6.1) - jekyll-remote-theme (= 0.4.1) + jekyll-remote-theme (= 0.4.3) jekyll-sass-converter (= 1.5.2) - jekyll-seo-tag (= 2.6.1) + jekyll-seo-tag (= 2.8.0) jekyll-sitemap (= 1.4.0) jekyll-swiss (= 1.0.0) - jekyll-theme-architect (= 0.1.1) - jekyll-theme-cayman (= 0.1.1) - jekyll-theme-dinky (= 0.1.1) - jekyll-theme-hacker (= 0.1.1) - jekyll-theme-leap-day (= 0.1.1) - jekyll-theme-merlot (= 0.1.1) - jekyll-theme-midnight (= 0.1.1) - jekyll-theme-minimal (= 0.1.1) - jekyll-theme-modernist (= 0.1.1) - jekyll-theme-primer (= 0.5.4) - jekyll-theme-slate (= 0.1.1) - jekyll-theme-tactile (= 0.1.1) - jekyll-theme-time-machine (= 0.1.1) + jekyll-theme-architect (= 0.2.0) + jekyll-theme-cayman (= 0.2.0) + jekyll-theme-dinky (= 0.2.0) + jekyll-theme-hacker (= 0.2.0) + jekyll-theme-leap-day (= 0.2.0) + jekyll-theme-merlot (= 0.2.0) + jekyll-theme-midnight (= 0.2.0) + jekyll-theme-minimal (= 0.2.0) + jekyll-theme-modernist (= 0.2.0) + jekyll-theme-primer (= 0.6.0) + jekyll-theme-slate (= 0.2.0) + jekyll-theme-tactile (= 0.2.0) + jekyll-theme-time-machine (= 0.2.0) jekyll-titles-from-headings (= 0.5.3) - jemoji (= 0.11.1) - kramdown (= 1.17.0) - liquid (= 4.0.3) + jemoji (= 0.12.0) + kramdown (= 2.3.2) + kramdown-parser-gfm (= 1.1.0) + liquid (= 4.0.4) mercenary (~> 0.3) minima (= 2.5.1) - nokogiri (>= 1.10.4, < 2.0) - rouge (= 3.19.0) + nokogiri (>= 1.13.6, < 2.0) + rouge (= 3.26.0) terminal-table (~> 1.4) - github-pages-health-check (1.16.1) + github-pages-health-check (1.17.9) addressable (~> 2.3) dnsruby (~> 1.60) octokit (~> 4.0) - public_suffix (~> 3.0) + public_suffix (>= 3.0, < 5.0) typhoeus (~> 1.3) - html-pipeline (2.13.0) + hashery (2.1.2) + html-pipeline (2.14.3) activesupport (>= 2) nokogiri (>= 1.4) - html-proofer (3.15.3) + html-proofer (5.0.7) addressable (~> 2.3) - mercenary (~> 0.3) - nokogumbo (~> 2.0) - parallel (~> 1.3) + async (~> 2.1) + nokogiri (~> 1.13) + pdf-reader (~> 2.11) rainbow (~> 3.0) typhoeus (~> 1.3) yell (~> 2.0) - http_parser.rb (0.6.0) - i18n (0.9.5) + zeitwerk (~> 2.5) + http_parser.rb (0.8.0) + i18n (1.14.1) concurrent-ruby (~> 1.0) - jekyll (3.8.7) + io-event (1.1.7) + jekyll (3.9.3) addressable (~> 2.4) colorator (~> 1.0) em-websocket (~> 0.5) - i18n (~> 0.7) + i18n (>= 0.7, < 2) jekyll-sass-converter (~> 1.0) jekyll-watch (~> 2.0) - kramdown (~> 1.14) + kramdown (>= 1.17, < 3) liquid (~> 4.0) mercenary (~> 0.3.3) pathutil (~> 0.9) @@ -118,23 +132,25 @@ GEM jekyll-coffeescript (1.1.1) coffee-script (~> 2.2) coffee-script-source (~> 1.11.1) - jekyll-commonmark (1.3.1) - commonmarker (~> 0.14) - jekyll (>= 3.7, < 5.0) - jekyll-commonmark-ghpages (0.1.6) - commonmarker (~> 0.17.6) - jekyll-commonmark (~> 1.2) - rouge (>= 2.0, < 4.0) + jekyll-commonmark (1.4.0) + commonmarker (~> 0.22) + jekyll-commonmark-ghpages (0.4.0) + commonmarker (~> 0.23.7) + jekyll (~> 3.9.0) + jekyll-commonmark (~> 1.4.0) + rouge (>= 2.0, < 5.0) jekyll-default-layout (0.1.4) jekyll (~> 3.0) - jekyll-feed (0.13.0) + jekyll-feed (0.15.1) jekyll (>= 3.7, < 5.0) jekyll-gist (1.5.0) octokit (~> 4.2) jekyll-github-metadata (2.13.0) jekyll (>= 3.4, < 5.0) octokit (~> 4.0, != 4.4.0) - jekyll-mentions (1.5.1) + jekyll-include-cache (0.2.1) + jekyll (>= 3.7, < 5.0) + jekyll-mentions (1.6.0) html-pipeline (~> 2.3) jekyll (>= 3.7, < 5.0) jekyll-optional-front-matter (0.3.2) @@ -142,133 +158,148 @@ GEM jekyll-paginate (1.1.0) jekyll-readme-index (0.3.0) jekyll (>= 3.0, < 5.0) - jekyll-redirect-from (0.15.0) + jekyll-redirect-from (0.16.0) jekyll (>= 3.3, < 5.0) jekyll-relative-links (0.6.1) jekyll (>= 3.3, < 5.0) - jekyll-remote-theme (0.4.1) + jekyll-remote-theme (0.4.3) addressable (~> 2.0) jekyll (>= 3.5, < 5.0) - rubyzip (>= 1.3.0) + jekyll-sass-converter (>= 1.0, <= 3.0.0, != 2.0.0) + rubyzip (>= 1.3.0, < 3.0) jekyll-sass-converter (1.5.2) sass (~> 3.4) - jekyll-seo-tag (2.6.1) - jekyll (>= 3.3, < 5.0) + jekyll-seo-tag (2.8.0) + jekyll (>= 3.8, < 5.0) jekyll-sitemap (1.4.0) jekyll (>= 3.7, < 5.0) jekyll-swiss (1.0.0) - jekyll-theme-architect (0.1.1) - jekyll (~> 3.5) + jekyll-theme-architect (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-cayman (0.1.1) - jekyll (~> 3.5) + jekyll-theme-cayman (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-dinky (0.1.1) - jekyll (~> 3.5) + jekyll-theme-dinky (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-hacker (0.1.1) - jekyll (~> 3.5) + jekyll-theme-hacker (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-leap-day (0.1.1) - jekyll (~> 3.5) + jekyll-theme-leap-day (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-merlot (0.1.1) - jekyll (~> 3.5) + jekyll-theme-merlot (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-midnight (0.1.1) - jekyll (~> 3.5) + jekyll-theme-midnight (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-minimal (0.1.1) - jekyll (~> 3.5) + jekyll-theme-minimal (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-modernist (0.1.1) - jekyll (~> 3.5) + jekyll-theme-modernist (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-primer (0.5.4) + jekyll-theme-primer (0.6.0) jekyll (> 3.5, < 5.0) jekyll-github-metadata (~> 2.9) jekyll-seo-tag (~> 2.0) - jekyll-theme-slate (0.1.1) - jekyll (~> 3.5) + jekyll-theme-slate (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-tactile (0.1.1) - jekyll (~> 3.5) + jekyll-theme-tactile (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) - jekyll-theme-time-machine (0.1.1) - jekyll (~> 3.5) + jekyll-theme-time-machine (0.2.0) + jekyll (> 3.5, < 5.0) jekyll-seo-tag (~> 2.0) jekyll-titles-from-headings (0.5.3) jekyll (>= 3.3, < 5.0) jekyll-watch (2.2.1) listen (~> 3.0) - jemoji (0.11.1) + jemoji (0.12.0) gemoji (~> 3.0) html-pipeline (~> 2.2) jekyll (>= 3.0, < 5.0) - kramdown (1.17.0) - liquid (4.0.3) - listen (3.2.1) + kramdown (2.3.2) + rexml + kramdown-parser-gfm (1.1.0) + kramdown (~> 2.0) + liquid (4.0.4) + listen (3.8.0) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) mercenary (0.3.6) - mini_portile2 (2.8.0) minima (2.5.1) jekyll (>= 3.5, < 5.0) jekyll-feed (~> 0.9) jekyll-seo-tag (~> 2.1) - minitest (5.14.1) - multipart-post (2.1.1) - nokogiri (1.13.7) - mini_portile2 (~> 2.8.0) + minitest (5.19.0) + nokogiri (1.14.3-arm64-darwin) racc (~> 1.4) - nokogumbo (2.0.2) - nokogiri (~> 1.8, >= 1.8.4) - octokit (4.18.0) - faraday (>= 0.9) - sawyer (~> 0.8.0, >= 0.5.3) - parallel (1.19.1) + nokogiri (1.14.3-x86_64-linux) + racc (~> 1.4) + octokit (4.25.1) + faraday (>= 1, < 3) + sawyer (~> 0.9) pathutil (0.16.2) forwardable-extended (~> 2.6) - public_suffix (3.1.1) - racc (1.6.0) - rainbow (3.0.0) - rb-fsevent (0.10.4) + pdf-reader (2.11.0) + Ascii85 (~> 1.0) + afm (~> 0.2.1) + hashery (~> 2.0) + ruby-rc4 + ttfunk + public_suffix (4.0.7) + racc (1.6.2) + rainbow (3.1.1) + rb-fsevent (0.11.2) rb-inotify (0.10.1) ffi (~> 1.0) - rouge (3.19.0) - ruby-enum (0.8.0) - i18n - rubyzip (2.3.0) + rexml (3.2.5) + rouge (3.26.0) + ruby-rc4 (0.1.5) + ruby2_keywords (0.0.5) + rubyzip (2.3.2) safe_yaml (1.0.5) sass (3.7.4) sass-listen (~> 4.0.0) sass-listen (4.0.0) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) - sawyer (0.8.2) + sawyer (0.9.2) addressable (>= 2.3.5) - faraday (> 0.8, < 2.0) + faraday (>= 0.17.3, < 3) + simpleidn (0.2.1) + unf (~> 0.1.4) terminal-table (1.8.0) unicode-display_width (~> 1.1, >= 1.1.1) - thread_safe (0.3.6) + timers (4.3.5) + ttfunk (1.7.0) typhoeus (1.4.0) ethon (>= 0.9.0) - tzinfo (1.2.10) - thread_safe (~> 0.1) - unicode-display_width (1.7.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unf (0.1.4) + unf_ext + unf_ext (0.0.8.2) + unicode-display_width (1.8.0) + webrick (1.8.1) yell (2.2.2) - zeitwerk (2.3.0) + zeitwerk (2.6.7) PLATFORMS - ruby + arm64-darwin-22 + x86_64-linux DEPENDENCIES eip_validator (>= 0.8.2) - github-pages (= 206) - html-proofer (>= 3.3.1) - jekyll-feed (~> 0.11) + github-pages (= 228) + html-proofer (>= 5.0.7) minima (~> 2.0) tzinfo-data + webrick (~> 1.8) BUNDLED WITH - 1.17.2 + 2.4.12 diff --git a/README.md b/README.md index e364988d33ad9e..8cf30844c472a5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Ethereum Improvement Proposals (EIPs) +> **_ATTENTION_**: The EIPs repository has recently [undergone](https://github.com/ethereum/EIPs/pull/7206) a separation of ERCs and EIPs. ERCs are now accessible at [https://github.com/ethereum/ercs](https://github.com/ethereum/ercs). All new ERCs and updates to existing ones must be directed at this new repository. The editors apologize for this inconvenience. + The goal of the EIP project is to standardize and provide high-quality documentation for Ethereum itself and conventions built upon it. This repository tracks past and ongoing improvements to Ethereum in the form of Ethereum Improvement Proposals (EIPs). [EIP-1](https://eips.ethereum.org/EIPS/eip-1) governs how EIPs are published. The [status page](https://eips.ethereum.org/) tracks and lists EIPs, which can be divided into the following categories: @@ -27,7 +29,7 @@ Consider any document not published at as a working All pull requests in this repository must pass automated checks before they can be automatically merged: -- [eip-review-bot](https://github.com/Pandapip1/eip-review-bot/) determines when PRs can be automatically merged [^1] +- [eip-review-bot](https://github.com/ethereum/eip-review-bot/) determines when PRs can be automatically merged [^1] - EIP-1 rules are enforced using [`eipw`](https://github.com/ethereum/eipw)[^2] - HTML formatting and broken links are enforced using [HTMLProofer](https://github.com/gjtorikian/html-proofer)[^2] - Spelling is enforced with [CodeSpell](https://github.com/codespell-project/codespell)[^2] @@ -50,13 +52,13 @@ eipv 1. Open Terminal. -2. Check whether you have Ruby 2.1.0 or higher installed: +2. Check whether you have Ruby 3.1.4 installed. Later [versions are not supported](https://stackoverflow.com/questions/14351272/undefined-method-exists-for-fileclass-nomethoderror). ```sh ruby --version ``` -3. If you don't have Ruby installed, install Ruby 2.1.0 or higher. +3. If you don't have Ruby installed, install Ruby 3.1.4. 4. Install Bundler: diff --git a/_config.yml b/_config.yml index a6d969f35b1d38..8bcdfcd61d701e 100644 --- a/_config.yml +++ b/_config.yml @@ -16,11 +16,12 @@ title: Ethereum Improvement Proposals description: >- Ethereum Improvement Proposals (EIPs) describe standards for the Ethereum - platform, including core protocol specifications, client APIs, and contract - standards. + platform, such as core protocol specifications. url: "https://eips.ethereum.org" github_username: ethereum repository: ethereum/EIPs +lang: en +timezone: UTC header_pages: - all.html @@ -39,7 +40,7 @@ kramdown: parse_block_html: false # This is the default, but be explicit as some EIPs depend on it auto_ids: true - # This is to ensure more determistic behaviour + # This is to ensure more deterministic behaviour auto_id_stripping: true syntax_highlighter: rouge diff --git a/_includes/head.html b/_includes/head.html index afa500aa72f2c4..bc8a94533ae6cf 100644 --- a/_includes/head.html +++ b/_includes/head.html @@ -41,10 +41,11 @@ {%- feed_meta -%} - + + - + - +